Ejemplo n.º 1
0
#pragma warning restore 1998

        /// <summary>
        /// Processes a message in a conversation between the bot and the authenticated user.
        /// </summary>
        /// <param name="context">The context for the execution of a dialogs conversational process.</param>
        /// <param name="argument">The message in a conversation between the bot and a user.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="argument"/> is null.
        /// </exception>
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            IMessageActivity message;
            QnAMakerResults  result = null;

            context.AssertNotNull(nameof(context));
            argument.AssertNotNull(nameof(argument));

            try
            {
                message = await argument;

                if (!string.IsNullOrEmpty(message?.Text))
                {
                    result = await QnAService.QueryServiceAsync(message.Text).ConfigureAwait(false);
                }

                message      = context.MakeMessage();
                message.Text = result == null ? Resources.RewordQuestion : result.Answers.First().Answer;

                context.Done(message);
            }
            finally
            {
                message = null;
                result  = null;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates the state to be utilized with the authentication request.
        /// </summary>
        /// <param name="context">Context for the dialog.</param>
        /// <returns>A string that represents the current state for the user.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// </exception>
        private string GenerateState(IDialogContext context)
        {
            Dictionary <string, string> state;
            Guid uniqueId = Guid.NewGuid();

            context.AssertNotNull(nameof(context));

            try
            {
                state = new Dictionary <string, string>
                {
                    { BotConstants.BotIdKey, conversationReference.Bot.Id },
                    { BotConstants.ChannelIdKey, conversationReference.ChannelId },
                    { BotConstants.ConversationIdKey, conversationReference.Conversation.Id },
                    { BotConstants.UniqueIdentifierKey, uniqueId.ToString() },
                    { BotConstants.ServiceUrlKey, conversationReference.ServiceUrl },
                    { BotConstants.UserIdKey, conversationReference.User.Id }
                };

                // Save the unique identifier in the user's private conversation store. This value will be
                // utilized to verify the authentication request.
                context.PrivateConversationData.SetValue(BotConstants.UniqueIdentifierKey, uniqueId);

                return(UrlToken.Encode(state));
            }
            finally
            {
                state = null;
            }
        }
        /// <summary>
        /// Resumes the conversation once the authentication process has completed.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="result">The result returned from </param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// </exception>
        private async Task ResumeAfterAuth(IDialogContext context, IAwaitable <string> result)
        {
            context.AssertNotNull(nameof(context));
            result.AssertNotNull(nameof(result));

            string message = await result;
            await context.PostAsync(message).ConfigureAwait(false);

            await HelpAsync(context).ConfigureAwait(false);
        }
        /// <summary>
        /// Processes the request for help.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        public async Task HelpAsync(IDialogContext context)
        {
            CustomerPrincipal principal;
            IMessageActivity  message;
            StringBuilder     builder;

            context.AssertNotNull(nameof(context));

            try
            {
                message = context.MakeMessage();

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (principal == null)
                {
                    message.Text = Resources.NotAuthenticatedHelpMessage;
                }
                else
                {
                    builder = new StringBuilder();
                    builder.AppendLine($"{Resources.HelpMessage}\n\n");

                    principal.AvailableIntents.Where(x => !string.IsNullOrEmpty(x.Value.HelpMessage)).Aggregate(
                        builder, (sb, pair) => sb.AppendLine($"* {pair.Value.HelpMessage}\n"));

                    message.Text = builder.ToString();
                }

                await context.PostAsync(message).ConfigureAwait(false);

                context.Wait(MessageReceived);
            }
            finally
            {
                builder   = null;
                message   = null;
                principal = null;
            }
        }
        public async Task RouteIntentAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result)
        {
            CustomerPrincipal principal;
            string            key;

            context.AssertNotNull(nameof(context));
            result.AssertNotNull(nameof(result));

            try
            {
                key = result.TopScoringIntent.Intent.ToCamelCase();

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (principal == null)
                {
                    await HelpAsync(context).ConfigureAwait(false);

                    return;
                }

                if (principal.AvailableIntents.ContainsKey(key))
                {
                    await principal.AvailableIntents[key]
                    .ExecuteAsync(context, message, result, provider).ConfigureAwait(false);
                }
                else
                {
                    await HelpAsync(context).ConfigureAwait(false);
                }
            }
            finally
            {
                principal = null;
            }
        }
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services;.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            IMessageActivity messageActivity;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(provider));

            try
            {
                messageActivity = await message;

                await context.Forward(
                    new QuestionDialog(provider),
                    ResumeAfterQnA,
                    messageActivity,
                    CancellationToken.None).ConfigureAwait(false);
            }
            finally
            {
                messageActivity = null;
            }
        }
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services;.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            Customer                    customer = null;
            CustomerPrincipal           principal;
            DateTime                    startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            IMessageActivity            response;
            List <Subscription>         subscriptions;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(principal));

            try
            {
                startTime = DateTime.Now;

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId))
                {
                    customer = await provider.PartnerOperations.GetCustomerAsync(principal).ConfigureAwait(false);

                    response      = context.MakeMessage();
                    response.Text = string.Format(Resources.SubscriptionRequestMessage, customer.CompanyProfile.CompanyName);
                    await context.PostAsync(response).ConfigureAwait(false);
                }

                subscriptions = await provider.PartnerOperations.GetSubscriptionsAsync(principal).ConfigureAwait(false);

                response = context.MakeMessage();
                response.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                response.Attachments      = subscriptions.Select(s => s.ToAttachment()).ToList();

                await context.PostAsync(response).ConfigureAwait(false);

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfSubscriptions", response.Attachments.Count }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "UserId", principal.ObjectId }
                };

                provider.Telemetry.TrackEvent("ListCustomers/Execute", eventProperties, eventMetrics);
            }
            finally
            {
                customer        = null;
                eventMetrics    = null;
                eventProperties = null;
                principal       = null;
                response        = null;
                subscriptions   = null;
            }
        }
Ejemplo n.º 8
0
#pragma warning disable 1998
        /// <summary>
        /// The start of the code that represents the conversational dialog.
        /// </summary>
        /// <param name="context">The dialog context.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// </exception>
        public async Task StartAsync(IDialogContext context)
        {
            context.AssertNotNull(nameof(context));

            context.Wait(MessageReceivedAsync);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            CustomerPrincipal           principal;
            DateTime                    startTime;
            Dictionary <string, double> eventMeasurements;
            Dictionary <string, string> eventProperties;
            IMessageActivity            response;
            List <Customer>             customers;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(provider));

            try
            {
                startTime = DateTime.Now;

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                customers = await provider.PartnerOperations.GetCustomersAsync(principal).ConfigureAwait(false);

                response = context.MakeMessage();
                response.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                response.Attachments = customers.Select(c => (new ThumbnailCard
                {
                    Buttons = new List <CardAction>
                    {
                        new CardAction
                        {
                            Title = Resources.SelectCaptial,
                            Type = ActionTypes.PostBack,
                            Value = $"select customer {c.Id}"
                        }
                    },
                    Subtitle = c.CompanyProfile.Domain,
                    Title = c.CompanyProfile.CompanyName
                }).ToAttachment()).ToList();

                await context.PostAsync(response).ConfigureAwait(false);

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "Locale", response.Locale },
                    { "UserId", principal.ObjectId }
                };

                // Track the event measurements for analysis.
                eventMeasurements = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfCustomers", response.Attachments.Count }
                };

                provider.Telemetry.TrackEvent("ListCustomers/Execute", eventProperties, eventMeasurements);
            }
            finally
            {
                customers         = null;
                eventMeasurements = null;
                eventProperties   = null;
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// The start of the code that represents the conversational dialog.
 /// </summary>
 /// <param name="context"> The context for the execution of a dialog's conversational process.</param>
 /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="context"/> is null.
 /// </exception>
 public async Task StartAsync(IDialogContext context)
 {
     context.AssertNotNull(nameof(context));
     await AuthenticateAsync(context).ConfigureAwait(false);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            CustomerPrincipal           principal;
            Customer                    customer;
            DateTime                    startTime;
            Dictionary <string, double> eventMeasurements;
            Dictionary <string, string> eventProperties;
            EntityRecommendation        indentifierEntity;
            IMessageActivity            response;
            string customerId = string.Empty;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(provider));

            try
            {
                startTime = DateTime.Now;
                response  = context.MakeMessage();

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (result.TryFindEntity("identifier", out indentifierEntity))
                {
                    customerId = indentifierEntity.Entity.Replace(" ", string.Empty);
                    principal.Operation.CustomerId     = customerId;
                    principal.Operation.SubscriptionId = string.Empty;
                    context.StoreCustomerPrincipal(principal);
                }

                if (string.IsNullOrEmpty(customerId))
                {
                    response.Text = Resources.UnableToLocateCustomer;
                }
                else
                {
                    customer = await provider.PartnerOperations.GetCustomerAsync(principal, customerId).ConfigureAwait(false);

                    response.Text = $"{Resources.CustomerContext} {customer.CompanyProfile.CompanyName}";
                }

                await context.PostAsync(response).ConfigureAwait(false);

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", customerId },
                    { "PrincipalCustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "UserId", principal.ObjectId }
                };

                // Track the event measurements for analysis.
                eventMeasurements = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
                };

                provider.Telemetry.TrackEvent("SelectCustomer/ExecuteAsync", eventProperties, eventMeasurements);
            }
            finally
            {
                customer          = null;
                indentifierEntity = null;
                eventMeasurements = null;
                eventProperties   = null;
                message           = null;
            }
        }
        /// <summary>
        /// Performs the operation represented by this intent.
        /// </summary>
        /// <param name="context">The context of the conversational process.</param>
        /// <param name="message">The message from the authenticated user.</param>
        /// <param name="result">The result from Language Understanding cognitive service.</param>
        /// <param name="provider">Provides access to core services;.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="message"/> is null.
        /// or
        /// <paramref name="result"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public async Task ExecuteAsync(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result, IBotProvider provider)
        {
            CustomerPrincipal           principal;
            DateTime                    startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            IMessageActivity            response;
            List <OfficeHealthEvent>    healthEvents;
            ServiceCommunications       serviceComm;
            string authority;
            string customerId;

            context.AssertNotNull(nameof(context));
            message.AssertNotNull(nameof(message));
            result.AssertNotNull(nameof(result));
            provider.AssertNotNull(nameof(provider));

            try
            {
                startTime = DateTime.Now;

                principal = await context.GetCustomerPrincipalAsync(provider).ConfigureAwait(false);

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId, StringComparison.CurrentCultureIgnoreCase))
                {
                    principal.AssertValidCustomerContext(Resources.SelectCustomerFirst);

                    authority  = $"{provider.Configuration.ActiveDirectoryEndpoint}/{principal.Operation.CustomerId}";
                    customerId = principal.Operation.CustomerId;
                }
                else
                {
                    authority  = $"{provider.Configuration.ActiveDirectoryEndpoint}/{principal.CustomerId}";
                    customerId = principal.CustomerId;
                }

                serviceComm = new ServiceCommunications(
                    new Uri(provider.Configuration.OfficeManagementEndpoint),
                    new ServiceCredentials(
                        provider.Configuration.ApplicationId,
                        provider.Configuration.ApplicationSecret.ToUnsecureString(),
                        provider.Configuration.OfficeManagementEndpoint,
                        principal.Operation.CustomerId));

                healthEvents = await serviceComm.GetHealthEventsAsync(principal.Operation.CustomerId).ConfigureAwait(false);

                response = context.MakeMessage();
                response.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                response.Attachments      = healthEvents.Select(e => e.ToAttachment()).ToList();

                await context.PostAsync(response).ConfigureAwait(false);

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfSubscriptions", response.Attachments.Count }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "ChannelId", context.Activity.ChannelId },
                    { "CustomerId", principal.CustomerId },
                    { "LocalTimeStamp", context.Activity.LocalTimestamp.ToString() },
                    { "UserId", principal.ObjectId }
                };

                provider.Telemetry.TrackEvent("OfficeIssues/Execute", eventProperties, eventMetrics);
            }
            catch (Exception ex)
            {
                response      = context.MakeMessage();
                response.Text = Resources.ErrorMessage;

                provider.Telemetry.TrackException(ex);

                await context.PostAsync(response).ConfigureAwait(false);
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
                principal       = null;
                response        = null;
                serviceComm     = null;
            }
        }