private async Task OnInvoke(IInvokeActivity invoke, IConnectorClient connectorClient, IStateClient stateClient, HttpResponseMessage response, CancellationToken token)
        {
            MicrosoftAppCredentials.TrustServiceUrl(invoke.RelatesTo.ServiceUrl);

            var jobject = invoke.Value as JObject;

            if (jobject == null)
            {
                throw new ArgumentException("Request payload must be a valid json object.");
            }

            // This is a temporary workaround for the issue that the channelId for "webchat" is mapped to "directline" in the incoming RelatesTo object
            invoke.RelatesTo.ChannelId = (invoke.RelatesTo.ChannelId == "directline") ? "webchat" : invoke.RelatesTo.ChannelId;

            if (invoke.RelatesTo.User == null)
            {
                // Bot keeps the userId in context.ConversationData[cartId]
                var conversationData = await stateClient.BotState.GetConversationDataAsync(invoke.RelatesTo.ChannelId, invoke.RelatesTo.Conversation.Id, token);

                var cartId = conversationData.GetProperty <string>(RootDialog.CARTKEY);

                if (!string.IsNullOrEmpty(cartId))
                {
                    invoke.RelatesTo.User = new ChannelAccount
                    {
                        Id = conversationData.GetProperty <string>(cartId)
                    };
                }
            }

            var updateResponse = default(object);

            switch (invoke.Name)
            {
            case PaymentOperations.UpdateShippingAddressOperationName:
                updateResponse = await this.ProcessShippingUpdate(jobject.ToObject <PaymentRequestUpdate>(), ShippingUpdateKind.Address, token);

                break;

            case PaymentOperations.UpdateShippingOptionOperationName:
                updateResponse = await this.ProcessShippingUpdate(jobject.ToObject <PaymentRequestUpdate>(), ShippingUpdateKind.Options, token);

                break;

            case PaymentOperations.PaymentCompleteOperationName:
                updateResponse = await this.ProcessPaymentComplete(invoke, jobject.ToObject <PaymentRequestComplete>(), token);

                break;

            default:
                throw new ArgumentException("Invoke activity name is not a supported request type.");
            }

            response.Content = new ObjectContent <object>(
                updateResponse,
                this.Configuration.Formatters.JsonFormatter,
                JsonMediaTypeFormatter.DefaultMediaType);

            response.StatusCode = HttpStatusCode.OK;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ShareEventDialog"/> class.
 /// </summary>
 /// <param name="connectorClient">Connector client</param>
 /// <param name="eventDataProvider">Event data provider instance</param>
 /// <param name="userManagementHelper">UserManagementHelper instance</param>
 /// <param name="logProvider">Logging component</param>
 public ShareEventDialog(IConnectorClient connectorClient, IEventDataProvider eventDataProvider, IUserManagementHelper userManagementHelper, ILogProvider logProvider)
 {
     this.eventDataProvider    = eventDataProvider;
     this.connectorClient      = connectorClient;
     this.logProvider          = logProvider;
     this.userManagementHelper = userManagementHelper;
 }
Example #3
0
 public SupplierConnectorManager(IOptions <SupplierOptions> options,
                                 IConnectorClient connectorClient,
                                 IServiceProvider serviceProvider)
 {
     _options   = options.Value;
     _suppliers = new Dictionary <Suppliers, ISupplierConnector>
     {
         // TODO: Add other suppliers.
         {
             Suppliers.Netstorming,
             new SupplierConnector(connectorClient, _options.Netstorming, serviceProvider.GetRequiredService <ILogger <SupplierConnector> >())
         },
         {
             Suppliers.Illusions,
             new SupplierConnector(connectorClient, _options.Illusions, serviceProvider.GetRequiredService <ILogger <SupplierConnector> >())
         },
         {
             Suppliers.Etg,
             new SupplierConnector(connectorClient, _options.Etg, serviceProvider.GetRequiredService <ILogger <SupplierConnector> >())
         },
         {
             Suppliers.DirectContracts,
             new SupplierConnector(connectorClient, _options.DirectContracts, serviceProvider.GetRequiredService <ILogger <SupplierConnector> >())
         },
         {
             Suppliers.Rakuten,
             new SupplierConnector(connectorClient, _options.Rakuten, serviceProvider.GetRequiredService <ILogger <SupplierConnector> >())
         },
     };
 }
Example #4
0
 public PersistentDialogTask(IPostToBot inner, Message message, IConnectorClient client, IBotToUser botToUser)
 {
     SetField.NotNull(out this.inner, nameof(inner), inner);
     SetField.NotNull(out this.message, nameof(message), message);
     SetField.NotNull(out this.client, nameof(client), client);
     SetField.NotNull(out this.botToUser, nameof(botToUser), botToUser);
 }
 /// <summary>
 /// Handles actions for rest of activity type except message.
 /// </summary>
 /// <param name="connectorClient">IConnectorClient</param>
 /// <param name="message">activity object.</param>
 /// <returns>Task.</returns>
 private async Task HandleSystemMessageAsync(IConnectorClient connectorClient, Activity message)
 {
     this.connectorClient = connectorClient;
     if (message.Type == ActivityTypes.DeleteUserData)
     {
         // Implement user deletion here
     }
     else if (message.Type == ActivityTypes.ConversationUpdate)
     {
         if (message.MembersAdded?.Count > 0)
         {
             await this.HandleMemberAddedActionAsync(message);
         }
         else if (message.MembersRemoved?.Count > 0)
         {
             await this.HandleMemberDeletedActionAsync(message);
         }
     }
     else if (message.Type == ActivityTypes.ContactRelationUpdate)
     {
     }
     else if (message.Type == ActivityTypes.Typing)
     {
     }
     else if (message.Type == ActivityTypes.Ping)
     {
     }
 }
Example #6
0
        /// <summary>
        /// Loads the message data from connector.
        /// </summary>
        /// <param name="client"> Instance of connector client.</param>
        /// <param name="botId"> Id of the bot.</param>
        /// <param name="userId"> Id of the user.</param>
        /// <param name="conversationId"> Id of the conversation.</param>
        /// <param name="token"> The cancelation token.</param>
        /// <returns> A message with appropriate data fields.</returns>
        public static async Task <Message> LoadMessageData(this IConnectorClient client, string botId, string userId, string conversationId, CancellationToken token = default(CancellationToken))
        {
            var continuationMessage = new Message
            {
                ConversationId = conversationId,
                To             = new ChannelAccount
                {
                    Id = botId
                },
                From = new ChannelAccount
                {
                    Id = userId
                }
            };

            var dataRetrievalTasks = new List <Task <BotData> > {
                client.Bots.GetConversationDataAsync(botId, conversationId, token),
                client.Bots.GetUserDataAsync(botId, userId, token),
                client.Bots.GetPerUserConversationDataAsync(botId, conversationId, userId, token)
            };


            await Task.WhenAll(dataRetrievalTasks);

            continuationMessage.BotConversationData          = dataRetrievalTasks[0].Result?.Data;
            continuationMessage.BotUserData                  = dataRetrievalTasks[1].Result?.Data;
            continuationMessage.BotPerUserInConversationData = dataRetrievalTasks[2].Result?.Data;

            return(continuationMessage);
        }
Example #7
0
 public SupplierConnector(Suppliers supplier, IConnectorClient connectorClient, string baseUrl, ILogger <SupplierConnector> logger)
 {
     _supplier        = supplier;
     _connectorClient = connectorClient;
     _baseUrl         = baseUrl;
     _logger          = logger;
 }
Example #8
0
 public MeetingService(IConnectorClient connectorClient, IChatRoomUserService chatRoomUserService,
                       IMetingAnswersRepository metingAnswersRepository, IRoomRepository roomRepository)
 {
     _connectorClient         = connectorClient;
     _userService             = chatRoomUserService;
     _metingAnswersRepository = metingAnswersRepository;
     _roomRepository          = roomRepository;
 }
Example #9
0
        private static void AssertConnectorClientValues(IConnectorClient client, string expectedAppId, Uri expectedServiceUrl, string expectedScope = AuthenticationConstants.ToChannelFromBotOAuthScope)
        {
            var creds = (AppCredentials)client.Credentials;

            Assert.AreEqual(expectedAppId, creds.MicrosoftAppId);
            Assert.AreEqual(expectedScope, creds.OAuthScope);
            Assert.AreEqual(expectedServiceUrl, client.BaseUri);
        }
Example #10
0
        private async Task PersistMessageData(IConnectorClient client, string botId, string userId, string conversationId, Message msg)
        {
            await client.Bots.SetConversationDataAsync(botId, conversationId, new BotData(msg.BotConversationData));

            await client.Bots.SetUserDataAsync(botId, userId, new BotData(msg.BotUserData));

            await client.Bots.SetPerUserInConversationDataAsync(botId, conversationId, userId, new BotData(msg.BotPerUserInConversationData));
        }
Example #11
0
        /// <summary>
        /// Receives message from user and reply to it
        /// </summary>
        /// <param name="activity">Activity object</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation</returns>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            try
            {
                UserTelemetryInitializer.SetTelemetryUserId(HttpContext.Current, activity.From.Id);
                this.LogUserActivity(activity);

                using (var dialogScope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    this.connectorClient = dialogScope.Resolve <IConnectorClient>();

                    if (activity.Type == ActivityTypes.Message)
                    {
                        if (activity.Value != null)
                        {
                            // Process messageBack events using the dialog framework
                            var dialog = dialogScope.Resolve <RootDialog>();
                            await Conversation.SendAsync(activity, () => dialog);
                        }
                        else
                        {
                            // Send welcome card if user send any message to bot
                            var reply = activity.CreateReply();
                            reply.Attachments.Add(CelebrationCard.GetWelcomeCardInResponseToUserMessage().ToAttachment());
                            await this.connectorClient.Conversations.SendToConversationWithRetriesAsync(reply);
                        }
                    }
                    else if (activity.Type == ActivityTypes.ConversationUpdate)
                    {
                        this.logProvider.LogInfo("Processing conversationUpdate activity");
                        switch (activity.Conversation.ConversationType)
                        {
                        case "personal":
                            await this.HandlePersonalConversationUpdateAsync(activity);

                            break;

                        case "channel":
                            await this.HandleTeamConversationUpdateAsync(activity);

                            break;

                        default:
                            this.logProvider.LogWarning($"Received unexpected conversationUpdate activity with conversationType {activity.Conversation.ConversationType}");
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.logProvider.LogError($"Failed to process activity {activity.Type}", ex);
                throw;
            }

            return(this.Request.CreateResponse(HttpStatusCode.OK));
        }
Example #12
0
 public PersistentDialogTask(Func <IPostToBot> makeInner, Message message, IConnectorClient client, IBotToUser botToUser, IBotData botData)
 {
     SetField.NotNull(out this.message, nameof(message), message);
     SetField.NotNull(out this.client, nameof(client), client);
     SetField.NotNull(out this.botToUser, nameof(botToUser), botToUser);
     SetField.NotNull(out this.botData, nameof(botData), botData);
     SetField.CheckNull(nameof(makeInner), makeInner);
     this.inner = new Lazy <IPostToBot>(() => makeInner());
 }
 public NetstormingResponseService(IConnectorClient connectorClient,
                                   IBookingResponseProcessor responseProcessor,
                                   IOptions <SupplierOptions> supplierOptions,
                                   ILogger <NetstormingResponseService> logger)
 {
     _connectorClient   = connectorClient;
     _supplierOptions   = supplierOptions.Value;
     _responseProcessor = responseProcessor;
     _logger            = logger;
 }
Example #14
0
        public static async Task <ApiResponse <T> > GetAsync <T>(IConnectorClient connectorClient, Uri requestUri, CancellationToken cancellationToken = default)
        {
            var request = new Request <T>
            {
                HttpMethod = HttpMethod.Get,
                RequestUri = requestUri,
            };

            return(await SendAsync(connectorClient, request, cancellationToken));
        }
Example #15
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            _turtle = FindViewById <ImageView>(Resource.Id.slowerButton);
            _rabbit = FindViewById <ImageView>(Resource.Id.fasterButton);
            _man    = FindViewById <ImageView>(Resource.Id.normalButton);

            _turtle.Click += (sender, args) =>
            {
                ShowActive(_turtle);
                ShowInactive(_rabbit);
                ShowInactive(_man);
                BlinkLowSpeed();
            };

            _rabbit.Click += (sender, args) =>
            {
                ShowActive(_rabbit);
                ShowInactive(_turtle);
                ShowInactive(_man);
                BlinkHighSpeed();
            };

            _man.Click += (sender, args) =>
            {
                ShowPassive(_man);
                ShowInactive(_rabbit);
                ShowInactive(_turtle);
                StopBlinking();
            };

            try
            {
                client = new ConnectorClient();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }

            lastResult = new List <string>();

            if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.RecordAudio) == Permission.Granted)
            {
                BeginProcessing();
            }
            else
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.RecordAudio }, 312);
            }
        }
Example #16
0
        public static async Task <ApiResponse <T> > PatchAsync <T>(IConnectorClient connectorClient, Uri requestUri, object payload, CancellationToken cancellationToken = default)
        {
            var request = new Request <T>
            {
                HttpMethod = HttpMethod.Patch,
                RequestUri = requestUri,
                Payload    = payload,
            };

            return(await SendAsync(connectorClient, request, cancellationToken));
        }
 public DeleteTicketTeamsImplementation(IServiceProvider serviceProvider)
 {
     _conversationState            = serviceProvider.GetService <ConversationState>();
     _settings                     = serviceProvider.GetService <BotSettings>();
     _services                     = serviceProvider.GetService <BotServices>();
     _stateAccessor                = _conversationState.CreateProperty <SkillState>(nameof(SkillState));
     _serviceManager               = serviceProvider.GetService <IServiceManager>();
     _activityReferenceMapAccessor = _conversationState.CreateProperty <ActivityReferenceMap>(nameof(ActivityReferenceMap));
     _connectorClient              = serviceProvider.GetService <IConnectorClient>();
     _teamsTicketUpdateActivity    = serviceProvider.GetService <ITeamsActivity <AdaptiveCard> >();
 }
Example #18
0
        public static async Task <string> GetTokenAsync(this IConnectorClient connector)
        {
            var credentials = connector.Credentials as MicrosoftAppCredentials;

            if (credentials != null)
            {
                return(await credentials.GetTokenAsync());
            }

            return(null);
        }
Example #19
0
        public static HealthCheckResponse CreateHealthCheckResponse(IConnectorClient connector)
        {
            // A derived class may override this, however, the default is that the bot is healthy given we have got to here.
            var healthResults = new HealthResults {
                Success = true
            };

            if (connector != null)
            {
                try
                {
                    // This is a mock secure SendToConversation to grab the exact HTTP headers.
                    // If you have no appId and no secret this code will run but not produce an Authorization header.
                    using (var captureHandler = new CaptureRequestHandler())
                    {
                        using (var client = new ConnectorClient(connector.BaseUri, connector.Credentials, captureHandler))
                        {
                            var activity = new Activity
                            {
                                Type         = ActivityTypes.Message,
                                Conversation = new ConversationAccount {
                                    Id = "capture"
                                }
                            };
                            client.Conversations.SendToConversation(activity);
                            var headers = captureHandler.Request.Headers;
                            healthResults.Authorization = headers.Authorization?.ToString();
                            healthResults.UserAgent     = headers.UserAgent?.ToString();
                        }
                    }
                }
#pragma warning disable CA1031 // Do not catch general exception types (ignoring, see comment in catch block)
                catch (Exception)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    // This exception happens when you have a valid appId but invalid or blank secret.
                    // No callbacks will be possible, although the bot maybe healthy in other respects.
                }
            }

            var successMessage = "Health check succeeded.";
            healthResults.Messages = healthResults.Authorization != null
                ? new[] { successMessage }
                : new[]
            {
                successMessage,
                "Callbacks are not authorized."
            };

            return(new HealthCheckResponse {
                HealthResults = healthResults
            });
        }
Example #20
0
 public static async Task <ApiResponse <T> > SendAsync <T>(IConnectorClient connectorClient, IRequest <T> request, CancellationToken cancellationToken = default)
 {
     using (var req = new HttpRequestMessage(request.HttpMethod, request.RequestUri))
     {
         if (request.Payload != null)
         {
             string requestCmd = JsonConvert.SerializeObject(request.Payload, SerializationSettings);
             req.Content = new StringContent(requestCmd, Encoding.UTF8, ContentTypes.ApplicationJson);
         }
         return(await SendAsync <T>(connectorClient, req, cancellationToken));
     }
 }
        /// <summary>
        /// Initializes client properties.
        /// </summary>
        /// <param name="connectorClient">The connector client.</param>
        /// <returns>Teams connector client.</returns>
        internal static TeamsConnectorClient Initialize(IConnectorClient connectorClient)
        {
            if (connectorClient as ConnectorClient == null)
            {
                throw new ArgumentException("Cast to ConnectorClient failed. Ensure the client is dervied from ConnectorClient");
            }

            return(new TeamsConnectorClient
            {
                Teams = new TeamsOperations(connectorClient as ConnectorClient)
            });
        }
Example #22
0
        private static async Task <TeamsPagedMembersResult> GetPagedMembersAsync(IConnectorClient connectorClient, string conversationId, string continuationToken, CancellationToken cancellationToken, int?pageSize = default(int?))
        {
            if (conversationId == null)
            {
                throw new InvalidOperationException("The GetMembers operation needs a valid conversation Id.");
            }

            var pagedMemberResults = await connectorClient.Conversations.GetConversationPagedMembersAsync(conversationId, pageSize, continuationToken, cancellationToken).ConfigureAwait(false);

            var teamsPagedMemberResults = new TeamsPagedMembersResult(pagedMemberResults.ContinuationToken, pagedMemberResults.Members);

            return(teamsPagedMemberResults);
        }
 public AccommodationPreloader(NakijinContext context,
                               IConnectorClient connectorClient, ILoggerFactory loggerFactory,
                               IOptions <StaticDataLoadingOptions> options,
                               ILocationNameNormalizer locationNameNormalizer, TracerProvider tracerProvider, ISupplierOptionsClient supplierOptionsClient)
 {
     _context                = context;
     _logger                 = loggerFactory.CreateLogger <AccommodationPreloader>();
     _options                = options.Value;
     _connectorClient        = connectorClient;
     _locationNameNormalizer = locationNameNormalizer;
     _tracerProvider         = tracerProvider;
     _supplierOptionsClient  = supplierOptionsClient;
 }
Example #24
0
        /// <summary>
        /// Endpoint for bot request from Teams client
        /// </summary>
        /// <param name="activity">Request details</param>
        /// <returns>success</returns>
        /// POST: api/Faq
        public async Task <IHttpActionResult> PostAsync([FromBody] Activity activity)
        {
            var replyActivity = activity.CreateReply();

            this.connectorClient = new ConnectorClient(
                new Uri(activity.ServiceUrl),
                ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppIdKey],
                ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppPasswordKey]);

            if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                var membersAdded = activity.MembersAdded.ToList();
                if (membersAdded.Any() && membersAdded.Exists(m => m.Id == activity.Recipient.Id))
                {
                    replyActivity.Text = "Hi there, I'm an FAQ Bot. " +
                                         "I'm here to help you answer common questions. Ask me a question!";

                    await connectorClient.Conversations.SendToConversationWithRetriesAsync(
                        replyActivity,
                        activity.Conversation.Id);
                }
            }

            if (activity.Type == ActivityTypes.Message)
            {
                try
                {
                    // route activity text to QnA service
                    var questionResponse = await qNaRepo.GenerateAnswer(
                        new AskQuestionRequest
                    {
                        Question = activity.Text,
                        Top      = 1
                    },
                        getQnaServiceDetails());

                    replyActivity.Text = questionResponse.Answers.FirstOrDefault().Answer;
                }
                catch
                {
                    replyActivity.Text = "Uh oh. Brain freeze! Try asking me again :)";
                }

                await connectorClient.Conversations.SendToConversationWithRetriesAsync(
                    replyActivity,
                    activity.Conversation.Id);
            }

            return(Ok());
        }
Example #25
0
 public static async Task <ApiResponse <T> > SendAsync <T>(IConnectorClient connectorClient, HttpRequestMessage request, CancellationToken cancellationToken = default)
 {
     using (var httpResponse = await SendAsyncCancellationSafeAsync(connectorClient.HttpClient, request, cancellationToken))
     {
         if (IsJsonContentType(httpResponse))
         {
             return(await OnJsonResponse <T>(httpResponse));
         }
         else
         {
             return(await OnResponse <T>(httpResponse));
         }
     }
 }
 public NetstormingResponseService(
     IConnectorClient connectorClient,
     IDistributedFlow flow,
     IBookingRecordsManager bookingRecordsManager,
     IBookingResponseProcessor responseProcessor,
     IOptions <SupplierOptions> supplierOptions,
     ILogger <NetstormingResponseService> logger)
 {
     _connectorClient       = connectorClient;
     _supplierOptions       = supplierOptions.Value;
     _flow                  = flow;
     _bookingRecordsManager = bookingRecordsManager;
     _responseProcessor     = responseProcessor;
     _logger                = logger;
 }
        private static async Task <string> SendMessageWithAttachments(Activity activity,
                                                                      IList <Attachment> attachments)
        {
            var reply = activity.CreateReply();

            reply.Attachments = attachments;
            if (connectorClient == null)
            {
                connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
            }

            var resourceResponse = await connectorClient.Conversations.SendToConversationAsync(reply);

            return(resourceResponse.Id);
        }
Example #28
0
        public static async Task <List <string> > GetTeamMembers(ITurnContext turnContext)
        {
            try
            {
                IConnectorClient connector = turnContext.TurnState.Get <IConnectorClient>();
                var members = await connector.Conversations.GetConversationMembersAsync(turnContext.Activity.Conversation.Id);

                var mamberNames = members.Select(c => c.Name).ToList();
                return(mamberNames);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Example #29
0
        public static async Task <string> GetUserEmailId <T>(ITurnContext <T> turnContext) where T : Microsoft.Bot.Schema.IActivity
        {
            // Fetch the members in the current conversation
            try
            {
                IConnectorClient connector = turnContext.TurnState.Get <IConnectorClient>();
                var members = await connector.Conversations.GetConversationMembersAsync(turnContext.Activity.Conversation.Id);

                return(AsTeamsChannelAccounts(members).FirstOrDefault(m => m.Id == turnContext.Activity.From.Id).UserPrincipalName);
            }
            catch (Exception ex)
            {
                return("");
            }
        }
Example #30
0
        public static async Task <IList <ChannelAccount> > GetConversationMembers(this ITurnContext <IConversationUpdateActivity> turnContext)
        {
            IConnectorClient connector = turnContext.TurnState.Get <IConnectorClient>();
            var channelData            = turnContext.Activity.GetChannelData <TeamsChannelData>();
            var conversationId         = turnContext.Activity.Conversation.Id;

            if (turnContext.Activity.Conversation.ConversationType == "channel")
            {
                conversationId = channelData.Team.Id;
            }

            var members = await connector.Conversations.GetConversationMembersAsync(conversationId);

            return(members);
        }
Example #31
0
 public AlwaysSendDirect_BotToUser(IMessageActivity toBot, IConnectorClient client)
 {
     SetField.NotNull(out this.toBot, nameof(toBot), toBot);
     SetField.NotNull(out this.client, nameof(client), client);
 }
Example #32
0
 public SendLastInline_BotToUser(Message toBot, IConnectorClient client)
 {
     SetField.NotNull(out this.toBot, nameof(toBot), toBot);
     SetField.NotNull(out this.client, nameof(client), client);
 }