コード例 #1
0
        private static Task <bool> DateTimePromptValidator(PromptValidatorContext <IList <DateTimeResolution> > promptContext, CancellationToken cancellationToken)
        {
            if (promptContext.Recognized.Succeeded)
            {
                // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                var timex = promptContext.Recognized.Value[0].Timex.Split('T')[0];

                // If this is a definite Date including year, month and day we are good otherwise reprompt.
                // A better solution might be to let the user know what part is actually missing.
                var isDefinite = new TimexProperty(timex).Types.Contains(Constants.TimexTypes.Definite);

                return(Task.FromResult(isDefinite));
            }

            return(Task.FromResult(false));
        }
コード例 #2
0
        /// <summary>
        /// Validator function to verify if the user name meets required constraints.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateName(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            // Validate that the user entered a minimum length for their name.
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (value.Length >= EnquiryTypeLengthMinValue)
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"Enquiry type needs to be at least `{EnquiryTypeLengthMinValue}` characters long.");

                return(false);
            }
        }
コード例 #3
0
        private static Task <bool> StartPromptValidatorAsync(
            PromptValidatorContext <IList <DateTimeResolution> > promptContext,
            CancellationToken cancellationToken)
        {
            if (promptContext.Recognized.Succeeded)
            {
                // Initialize a TimexProperty from the first
                // recognized value
                var timex = new TimexProperty(
                    promptContext.Recognized.Value[0].Timex);

                // If it has a definite date and time, it's valid
                return(Task.FromResult(TimexHasDateAndTime(timex)));
            }

            return(Task.FromResult(false));
        }
コード例 #4
0
 private Task CustomValidator(ITurnContext turnContext, PromptValidatorContext <IList <DateTimeResolution> > prompt, CancellationToken cancellationToken)
 {
     if (prompt.Recognized.Succeeded)
     {
         var resolution = prompt.Recognized.Value.First();
         // re-write the resolution to just include the date part.
         var rewrittenResolution = new DateTimeResolution
         {
             Timex = resolution.Timex.Split('T')[0],
             Value = resolution.Value.Split(' ')[0]
         };
         prompt.End(new List <DateTimeResolution> {
             rewrittenResolution
         });
     }
     return(Task.CompletedTask);
 }
コード例 #5
0
        private async Task <bool> EmailFormValidator(PromptValidatorContext <string> promptcontext, CancellationToken cancellationtoken)
        {
            var _DialogInfo = await _dialogInfoStateProperty.GetAsync(promptcontext.Context);

            var dialogsMUI = DecisionMaker.GetDialogsMui(_DialogInfo.Language);

            try
            {
                var mail = new System.Net.Mail.MailAddress(promptcontext.Context.Activity.Text);
                return(await Task.FromResult(true));
            }
            catch
            {
                promptcontext.Context.SendActivityAsync(MessageFactory.Text(dialogsMUI.EmailDictionary["wrongFormat"]), cancellationtoken);
                return(await Task.FromResult(false));
            }
        }
コード例 #6
0
        private Task <bool> CallbackTimeValidatorAsync(PromptValidatorContext <IList <DateTimeResolution> > promptContext, CancellationToken cancellationToken)
        {
            var valid = false;

            if (promptContext.Recognized.Succeeded)
            {
                var      resolution   = promptContext.Recognized.Value.First();
                DateTime selectedDate = Convert.ToDateTime(resolution.Value);
                TimeSpan start        = new TimeSpan(9, 0, 0);  // 10 o'clock
                TimeSpan end          = new TimeSpan(17, 0, 0); // 12 o'clock
                if ((selectedDate.TimeOfDay >= start) && (selectedDate.TimeOfDay <= end))
                {
                    valid = true;
                }
            }
            return(Task.FromResult(valid));
        }
コード例 #7
0
        /// <summary>
        /// Validator function to verify if city meets required constraints.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateCity(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            // Validate that the user entered a minimum lenght for their name
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (value.Length > CityLengthMinValue)
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"City names needs to be at least `{CityLengthMinValue}` characters long.").ConfigureAwait(false);

                return(false);
            }
        }
コード例 #8
0
        public static async Task <bool> UserFeedbackValidator(PromptValidatorContext <string> promptContext,
                                                              CancellationToken cancellationToken)
        {
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (value.Length > 2)
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"I need a little more feedback.").ConfigureAwait(false);

                return(false);
            }
        }
コード例 #9
0
        private async Task <bool> LocationValidatorAsync(
            PromptValidatorContext <Activity> promptContext,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!promptContext.Recognized.Succeeded)
            {
                await promptContext.Context.SendActivityAsync(
                    "Please enter a date of time for your event.",
                    cancellationToken : cancellationToken);

                return(false);
            }



            return(true);
        }
コード例 #10
0
        private async Task <bool> DateValidatorAsync(
            PromptValidatorContext <IList <DateTimeResolution> > promptContext,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!promptContext.Recognized.Succeeded)
            {
                await promptContext.Context.SendActivityAsync(
                    "Please enter a date of time for your event.",
                    cancellationToken : cancellationToken);

                return(false);
            }

            DateTimeResolution value = promptContext.Recognized.Value.FirstOrDefault();

            return(true);
        }
コード例 #11
0
        private Task <bool> ShoeSizeAsync(PromptValidatorContext <float> promptContext, CancellationToken cancellationToken)
        {
            var shoesize = promptContext.Recognized.Value;

            // show sizes can range from 0 to 16
            if (shoesize >= 0 && shoesize <= 16)
            {
                // we only accept round numbers or half sizes
                if (Math.Floor(shoesize) == shoesize || Math.Floor(shoesize * 2) == shoesize * 2)
                {
                    // indicate success by returning the value
                    return(Task.FromResult(true));
                }
            }

            return(Task.FromResult(false));
        }
コード例 #12
0
        /// <summary>
        /// Validator function to verify if the date is valid.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateDate(PromptValidatorContext <IList <DateTimeResolution> > promptContext, CancellationToken cancellationToken)
        {
            if (!promptContext.Recognized.Succeeded || string.IsNullOrEmpty(promptContext?.Recognized?.Value?[0]?.Timex))
            {
                return(false);
            }
            var timex = new TimexProperty(promptContext.Recognized.Value[0].Timex);

            if (promptContext.Recognized.Succeeded &&
                timex?.Year != null &&
                timex?.Month != null &&
                timex?.DayOfMonth != null)
            {
                var hour = timex.Hour ?? 0;
                var date = new DateTime(
                    timex.Year.Value,
                    timex.Month.Value,
                    timex.DayOfMonth.Value,
                    hour,
                    0,
                    0);

                if (date.Subtract(DateTime.Today).Days > 365)
                {
                    await promptContext.Context.SendActivityAsync($"Sorry, you cannot make a reservation more than 365 days into the future.").ConfigureAwait(false);

                    return(false);
                }

                if (date < DateTime.Today)
                {
                    await promptContext.Context.SendActivityAsync($"Sorry, you cannot make a reservation in the past - the time machine is down 😊").ConfigureAwait(false);

                    return(false);
                }

                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"Sorry, I couldn't understand the date. Can you please rephrase it?").ConfigureAwait(false);

                return(false);
            }
        }
コード例 #13
0
        /// <summary>
        /// Validator function to verify if the quantity the user entered gets recognized.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateQuantity(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            var result  = promptContext.Recognized.Value ?? string.Empty;
            var results = NumberRecognizer.RecognizeNumber(result, culture);

            if (results.Count == 0)
            {
                await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                return(false);
            }

            if (results.First().TypeName == "number" && double.TryParse(results.First().Resolution["value"].ToString(), out double value))
            {
                // Validate number
                if ((value < 1) || (value % 1 != 0))
                {
                    await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                    return(false);
                }

                if (value > 100)
                {
                    await promptContext.Context.SendActivityAsync(InvalidOverQuantityErrorMessage);

                    return(false);
                }

                var quantityRoses   = Convert.ToInt32(results.First().Resolution["value"]);
                var quantityMessage = quantityRoses == 1
                ? "I'll send just one rose."
                : $"I'll send {quantityRoses} roses.";
                promptContext.Recognized.Value = quantityRoses.ToString();
                await promptContext.Context.SendActivityAsync(quantityMessage);

                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                return(false);
            }
        }
コード例 #14
0
        private async Task <bool> ValidateEmail(
            PromptValidatorContext <string> promptContext,
            CancellationToken cancellationToken)
        {
            var email = promptContext.Recognized.Value;

            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return(addr.Address == email);
            }
            catch
            {
                await promptContext.Context.SendActivityAsync(Messages.GetUserInfoEmailIsNotValid);

                return(false);
            }
        }
コード例 #15
0
        private async Task <bool> AmountPeopleValidatorAsync(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (!int.TryParse(value, out int numberPeople))
            {
                var msg = "The amount of people should be a number.";
                await promptContext.Context.SendActivityAsync(msg)
                .ConfigureAwait(false);

                return(false);
            }
            else
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
        }
コード例 #16
0
        /// <summary>
        /// Method used to do a very poor email validation.
        /// </summary>
        /// <param name="promptContext">This is used to grab our users response from the previous prompt.</param>
        /// <param name="cancellationToken">Used to cancel work.</param>
        /// <returns>Task that is queued to be executed.</returns>
        private async Task <bool> ValidateEmailAsync(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            // Validate that the user entered at least a @ character
            // for their email
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (value.Contains("@"))
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"Your email needs to be in the format of [email protected]").ConfigureAwait(false);

                return(false);
            }
        }
コード例 #17
0
        public async Task <bool> ProvValidatorAsync(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            if (!promptContext.Recognized.Succeeded)
            {
                await promptContext.Context.SendActivityAsync(
                    "Inserire un formato valido.",
                    cancellationToken : cancellationToken);

                return(false);
            }

            if (promptContext.Recognized.Value.ToUpper() == "BACK")
            {
                return(true);
            }

            return(XmlManager.ReadXml(promptContext.Recognized.Value));
        }
コード例 #18
0
        private Task <bool> Validator(PromptValidatorContext <string> promptcontext, CancellationToken cancellationtoken)
        {
            var exitSynonyms = new[] { "exit", "done", "return" };

            switch (promptcontext.Recognized.Value)
            {
            case var s1 when exitSynonyms.Contains(s1.ToLower()):
                promptcontext.Recognized.Value = "exit";

                return(Task.FromResult(true));

            case var s2 when Guid.TryParse(s2, out _):
                return(Task.FromResult(true));

            default:
                return(Task.FromResult(false));
            }
        }
コード例 #19
0
        /// <summary>
        /// Method to execute the task which is to validate name of the city of staring point airport.
        /// </summary>
        /// <param name="promptValidatorContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Boolean true if validation passed, false if validation fails.</returns>
        public async Task <bool> FromValidatorAsync(PromptValidatorContext <string> promptValidatorContext, CancellationToken cancellationToken)
        {
            //Get starting point airport and convert it to list.
            string fromAirport = promptValidatorContext.Recognized.Value;

            string[] splited = fromAirport.Split(null);
            //Validate if starting point airport name is 1 or 2 words long.
            if (string.IsNullOrEmpty(fromAirport) || splited.Length < 1 || splited.Length > 2)
            {
                await promptValidatorContext.Context.SendActivityAsync("Please type in correct departure airport.", cancellationToken : cancellationToken);

                return(false);
            }
            else
            {
                return(true);
            }
        }
コード例 #20
0
        /// <summary>
        /// Method to execute the task which is to validate passenger's name.
        /// </summary>
        /// <param name="promptValidatorContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Boolean true if validation passed, false if validation fails.</returns>
        public async Task <bool> PassengerNameValidatorAsync(PromptValidatorContext <string> promptValidatorContext, CancellationToken cancellationToken)
        {
            //Get user answer and convert it to list.
            string passengerName = promptValidatorContext.Recognized.Value.Trim();

            string[] splited = passengerName.Split(null);
            //Validate if passengers name is 1 or 3 words long.
            if (string.IsNullOrEmpty(passengerName) || splited.Length < 1 || splited.Length > 3)
            {
                await promptValidatorContext.Context.SendActivityAsync("Please type in correct name.", cancellationToken : cancellationToken);

                return(false);
            }
            else
            {
                return(true);
            }
        }
コード例 #21
0
ファイル: DateTimePromptTests.cs プロジェクト: DDEfromOR/se
 private Task <bool> CustomValidator(PromptValidatorContext <IList <DateTimeResolution> > prompt, CancellationToken cancellationToken)
 {
     if (prompt.Recognized.Succeeded)
     {
         var resolution = prompt.Recognized.Value.First();
         // re-write the resolution to just include the date part.
         var rewrittenResolution = new DateTimeResolution
         {
             Timex = resolution.Timex.Split('T')[0],
             Value = resolution.Value.Split(' ')[0]
         };
         prompt.Recognized.Value = new List <DateTimeResolution> {
             rewrittenResolution
         };
         return(Task.FromResult(true));
     }
     return(Task.FromResult(false));
 }
コード例 #22
0
        private async Task <bool> ValidateBookingSelectionConfirmation(PromptValidatorContext <bool> promptContext, CancellationToken cancellationToken)
        {
            var state = await ConversationStateAccessor.GetAsync(promptContext.Context, cancellationToken : cancellationToken);

            var reservation = state.Booking;

            if (promptContext.Recognized.Succeeded == true)
            {
                reservation.Confirmed = promptContext.Recognized.Value;

                var reply = TemplateManager.GenerateActivity(RestaurantBookingSharedResponses.BookRestaurantRestaurantSearching);
                await promptContext.Context.SendActivityAsync(reply, cancellationToken);

                return(true);
            }

            return(false);
        }
コード例 #23
0
        private async Task <bool> ValidateReservationTime(PromptValidatorContext <IList <DateTimeResolution> > promptContext, CancellationToken cancellationToken)
        {
            var state = await ConversationStateAccessor.GetAsync(promptContext.Context, cancellationToken : cancellationToken);

            var reservation = state.Booking;

            if (promptContext.Recognized.Succeeded)
            {
                // Add the time element to the existing date that we have
                var recognizerValue = promptContext.Recognized.Value.First();

                reservation.ReservationTime = DateTime.Parse(recognizerValue.Value);

                return(true);
            }

            return(false);
        }
コード例 #24
0
        /// <summary>
        /// Runs custom validation logic for the media type choice prompt.
        /// </summary>
        /// <param name="promptContext">The prompt validation context.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>Return <code>true</code> to indicate that the input is valid; otherwise,
        /// <code>false</code>.</remarks>
        private async Task <bool> ChoiceValidatorAsync(
            PromptValidatorContext <FoundChoice> promptContext,
            CancellationToken cancellationToken)
        {
            // Pull key information from the prompt validator context.
            var options = promptContext.Options.Validations as ValidationOptions;
            var success = promptContext.Recognized.Succeeded;

            // If the input was recognized as a valid choice, allow the prompt to succeed, and
            // return the recognized value.
            if (success)
            {
                return(true);
            }

            // Otherwise, this attempt failed.
            return(await FailValidation(promptContext, options, cancellationToken));
        }
コード例 #25
0
        /// <summary>
        /// Validate the chosen time.
        /// </summary>
        /// <param name="promptContext">Prompt Validator Context.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>Dialog Turn Result.</returns>
        private async Task <bool> ValidateAmbiguousTimePrompt(PromptValidatorContext <FoundChoice> promptContext, CancellationToken cancellationToken)
        {
            var state = await ConversationStateAccessor.GetAsync(promptContext.Context, cancellationToken : cancellationToken);

            if (promptContext.Recognized.Succeeded)
            {
                var timexFromNaturalLanguage = state.AmbiguousTimexExpressions.First(t => t.Value == promptContext.Recognized.Value.Value);
                if (!string.IsNullOrEmpty(timexFromNaturalLanguage.Key))
                {
                    var property = new TimexProperty(timexFromNaturalLanguage.Key);
                    state.Booking.ReservationTime = DateTime.Parse($"{property.Hour.Value}:{property.Minute.Value}:{property.Second.Value}");

                    return(true);
                }
            }

            return(false);
        }
コード例 #26
0
        /// <summary>
        /// Validator function to verify if the user name meets required constraints.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateOTP(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            // Validate that the user entered a minimum length for their name.
            var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;

            if (value.Length >= passminlen)
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                obj.adddata("Bot: OTP needs to be at least 6 characters long.");
                await promptContext.Context.SendActivityAsync($"OTP needs to be at least 6 characters long.");

                return(false);
            }
        }
コード例 #27
0
        private async Task <bool> NamePromptValidatorAsync(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            var valid = false;

            if (promptContext.Recognized.Succeeded)
            {
                var name = promptContext.Recognized.Value?.Trim();
                //check if the string has a minimal and if it contains only characters
                if (name.Length >= 3 && name.Length <= 100)
                {
                    if (name.IsNameValid())
                    {
                        valid = true;
                    }
                }
            }
            return(await Task.FromResult(valid));
        }
コード例 #28
0
        public static async Task <bool> CarYearValidator(PromptValidatorContext <int> promptContext,
                                                         CancellationToken cancellationToken)
        {
            var value = promptContext.Recognized.Value;

            if (value >= 1900 && value <= 2018)
            {
                promptContext.Recognized.Value = value;
                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync($"Your car year should be between 1900 and 2018.")
                .ConfigureAwait(false);

                return(false);
            }
        }
コード例 #29
0
        private async Task <bool> _validator(PromptValidatorContext <Activity> promptContext, CancellationToken cancellationToken)
        {
            var activity = promptContext.Recognized.Value;

            if (activity.Type == ActivityTypes.Event)
            {
                if ((int)activity.Value == 2)
                {
                    promptContext.Recognized.Value = MessageFactory.Text(activity.Value.ToString());
                    return(true);
                }
            }
            else
            {
                await promptContext.Context.SendActivityAsync("Please send an 'event'-type Activity with a value of 2.");
            }
            return(false);
        }
コード例 #30
0
 private static Task <bool> DateTimePromptValidator(PromptValidatorContext <IList <DateTimeResolution> > promptContext, CancellationToken cancellationToken)
 {
     if (promptContext.Recognized.Succeeded)
     {
         var timex      = promptContext.Recognized.Value[0].Timex.Split('T')[0];
         var res        = Convert.ToDateTime(timex);
         var isDefinite = new TimexProperty(timex).Types.Contains(Constants.TimexTypes.Definite);
         if (res < DateTime.Now && res.Year >= DateTime.Now.Year)
         {
             isDefinite = false;
         }
         return(Task.FromResult(isDefinite));
     }
     else
     {
         return(Task.FromResult(false));
     }
 }