Exemplo n.º 1
0
        /// <summary>
        /// Attempts to recognize the user's input.
        /// </summary>
        /// <param name="turnContext">Context for the current turn of conversation with the user.</param>
        /// <param name="state">Contains state for the current instance of the prompt on the dialog stack.</param>
        /// <param name="options">A prompt options object constructed from the options initially provided
        /// in the call to <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <remarks>If the task is successful, the result describes the result of the recognition attempt.</remarks>
        protected override Task <PromptRecognizerResult <string> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <string>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                if (message.Text != null)
                {
                    result.Succeeded = true;
                    result.Value     = message.Text;
                }
            }

            return(Task.FromResult(result));
        }
Exemplo n.º 2
0
        protected override Task <PromptRecognizerResult <IList <Attachment> > > OnRecognizeAsync(ITurnContext context, IDictionary <string, object> state, PromptOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var result = new PromptRecognizerResult <IList <Attachment> >();

            if (context.Activity.Type == ActivityTypes.Message)
            {
                var message = context.Activity.AsMessageActivity();
                if (message.Attachments != null && message.Attachments.Count > 0)
                {
                    result.Succeeded = true;
                    result.Value     = message.Attachments;
                }
            }

            return(Task.FromResult(result));
        }
        private static async Task <bool> CheckValidatorAsync(DialogContext dc, PromptValidator <TokenResponse> validator, TokenResponse tokenResponse, CancellationToken cancellationToken)
        {
            const string AttemptCount = "AttemptCount";

            if (validator != null)
            {
                // Increment attempt count.
                var promptState = dc.ActiveDialog.State[OAuthHelper.PersistedState].CastTo <IDictionary <string, object> >();
                promptState[AttemptCount] = Convert.ToInt32(promptState[AttemptCount], CultureInfo.InvariantCulture) + 1;

                // Call the custom validator.
                var recognized = new PromptRecognizerResult <TokenResponse> {
                    Succeeded = tokenResponse != null, Value = tokenResponse
                };
                var promptOptions = dc.ActiveDialog.State[OAuthHelper.PersistedOptions].CastTo <PromptOptions>();
                var promptContext = new PromptValidatorContext <TokenResponse>(dc.Context, recognized, promptState, promptOptions);
                return(await validator(promptContext, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                return(tokenResponse != null);
            }
        }
Exemplo n.º 4
0
        private async Task <PromptRecognizerResult <TokenResponse> > RecognizeTokenAsync(ITurnContext context)
        {
            var result = new PromptRecognizerResult <TokenResponse>();

            if (IsTokenResponseEvent(context))
            {
                var tokenResponseObject = context.Activity.Value as JObject;
                var token = tokenResponseObject?.ToObject <TokenResponse>();
                result.Succeeded = true;
                result.Value     = token;
            }
            else if (IsTeamsVerificationInvoke(context))
            {
                // TODO: add missing code
            }
            else if (context.Activity.Type == ActivityTypes.Message)
            {
                var matched = magicCodeRegex.Match(context.Activity.Text);
                if (matched.Success)
                {
                    if (!(context.Adapter is BotFrameworkAdapter adapter))
                    {
                        throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
                    }

                    var token = await adapter.GetUserTokenAsync(context, _settings.ConnectionName, matched.Value, default(CancellationToken)).ConfigureAwait(false);

                    if (token != null)
                    {
                        result.Succeeded = true;
                        result.Value     = token;
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Attempts to recognize the user's input.
        /// </summary>
        /// <param name="turnContext">Context for the current turn of conversation with the user.</param>
        /// <param name="state">Contains state for the current instance of the prompt on the dialog stack.</param>
        /// <param name="options">A prompt options object constructed from the options initially provided
        /// in the call to <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <remarks>If the task is successful, the result describes the result of the recognition attempt.</remarks>
        protected override Task <PromptRecognizerResult <FoundChoice> > OnRecognizeAsync(
            ITurnContext turnContext,
            IDictionary <string, object> state,
            PromptOptions options,
            CancellationToken cancellationToken = default)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var choices = options.Choices ?? new List <Choice>();

            var result = new PromptRecognizerResult <FoundChoice>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var activity  = turnContext.Activity;
                var utterance = activity.Text;
                if (string.IsNullOrEmpty(utterance))
                {
                    return(Task.FromResult(result));
                }

                var opt = RecognizerOptions ?? new FindChoicesOptions();
                opt.Locale = DetermineCulture(activity, opt);
                var results = ChoiceRecognizers.RecognizeChoices(utterance, choices, opt);
                if (results != null && results.Count > 0)
                {
                    result.Succeeded = true;
                    result.Value     = results[0].Resolution;
                }
            }

            return(Task.FromResult(result));
        }
Exemplo n.º 6
0
        protected override Task <PromptRecognizerResult <T> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <T>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                var results = NumberRecognizer.RecognizeNumber(message.Text, culture);
                if (results.Count > 0)
                {
                    // Try to parse value based on type
                    var text = results[0].Resolution["value"].ToString();
                    if (typeof(T) == typeof(float))
                    {
                        if (float.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(int))
                    {
                        if (int.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(long))
                    {
                        if (long.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(double))
                    {
                        if (double.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(decimal))
                    {
                        if (decimal.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else
                    {
                        throw new NotSupportedException($"NumberPrompt: type argument T of type 'typeof(T)' is not supported");
                    }
                }
            }

            return(Task.FromResult(result));
        }
Exemplo n.º 7
0
        private async Task <PromptRecognizerResult <TokenResponse> > RecognizeTokenAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            var result = new PromptRecognizerResult <TokenResponse>();

            if (IsTokenResponseEvent(turnContext))
            {
                var tokenResponseObject = turnContext.Activity.Value as JObject;
                var token = tokenResponseObject?.ToObject <TokenResponse>();
                result.Succeeded = true;
                result.Value     = token;
            }
            else if (IsTeamsVerificationInvoke(turnContext))
            {
                var magicCodeObject = turnContext.Activity.Value as JObject;
                var magicCode       = magicCodeObject.GetValue("state")?.ToString();

                if (!(turnContext.Adapter is IUserTokenProvider adapter))
                {
                    throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
                }

                // Getting the token follows a different flow in Teams. At the signin completion, Teams
                // will send the bot an "invoke" activity that contains a "magic" code. This code MUST
                // then be used to try fetching the token from Botframework service within some time
                // period. We try here. If it succeeds, we return 200 with an empty body. If it fails
                // with a retriable error, we return 500. Teams will re-send another invoke in this case.
                // If it failes with a non-retriable error, we return 404. Teams will not (still work in
                // progress) retry in that case.
                try
                {
                    var token = await adapter.GetUserTokenAsync(turnContext, _settings.ConnectionName, magicCode, cancellationToken).ConfigureAwait(false);

                    if (token != null)
                    {
                        result.Succeeded = true;
                        result.Value     = token;

                        await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse }, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse, Value = new InvokeResponse {
                                                                               Status = 404
                                                                           } }, cancellationToken).ConfigureAwait(false);
                    }
                }
                catch
                {
                    await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse, Value = new InvokeResponse {
                                                                           Status = 500
                                                                       } }, cancellationToken).ConfigureAwait(false);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var matched = _magicCodeRegex.Match(turnContext.Activity.Text);
                if (matched.Success)
                {
                    if (!(turnContext.Adapter is IUserTokenProvider adapter))
                    {
                        throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
                    }

                    var token = await adapter.GetUserTokenAsync(turnContext, _settings.ConnectionName, matched.Value, cancellationToken).ConfigureAwait(false);

                    if (token != null)
                    {
                        result.Succeeded = true;
                        result.Value     = token;
                    }
                }
            }

            return(result);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Attempts to recognize the user's input.
        /// </summary>
        /// <param name="turnContext">Context for the current turn of conversation with the user.</param>
        /// <param name="state">Contains state for the current instance of the prompt on the dialog stack.</param>
        /// <param name="options">A prompt options object constructed from the options initially provided
        /// in the call to <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <remarks>If the task is successful, the result describes the result of the recognition attempt.</remarks>
        protected override Task <PromptRecognizerResult <T> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <T>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                var results = NumberRecognizer.RecognizeNumber(message.Text, culture, NumberOptions.SuppressExtendedTypes);
                if (results.Count > 0)
                {
                    // Try to parse value based on type
                    var text = results[0].Resolution["value"].ToString();
                    if (typeof(T) == typeof(float))
                    {
                        if (float.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(int))
                    {
                        if (int.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(long))
                    {
                        if (long.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(double))
                    {
                        if (double.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(decimal))
                    {
                        if (decimal.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                }
            }

            return(Task.FromResult(result));
        }
Exemplo n.º 9
0
 internal PromptValidatorContext(DialogContext dc, IDictionary <string, object> state, PromptOptions options, PromptRecognizerResult <T> recognized)
 {
     _dc        = dc;
     HasEnded   = false;
     EndResult  = null;
     Options    = options;
     Recognized = recognized;
 }