Beispiel #1
0
        public InitialDialog(UserState userState) : base(nameof(InitialDialog))
        {
            _userAccessor = userState.CreateProperty <User>("User");

            var waterfallSteps = new WaterfallStep[]
            {
                SubscriptionIdStepAsync,
                TenantIdStepAsync,
                ClientIdStepAsync,
                ClientSecretStepAsync,
                ConfirmStepAsync,
                SummaryStepAsync,
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new NumberPrompt <int>(nameof(NumberPrompt <int>)));
            AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #2
0
        public EventDialog(UserState userState) : base(nameof(EventDialog))
        {
            _attendeeProperty = userState.CreateProperty <Attendee>("Attendee");

            // This array defines how the Waterfall will execute.
            var waterfallSteps = new WaterfallStep[]
            {
                NameStepAsync,
                PhoneNumberStepAsync,
                EmailAsync,
                ConfirmAsync,
                SummaryAsync
            };

            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #3
0
 public OrderPizzaDialog(UserState userState, OrderPizzaRecognizer recognizer, IPizzaRepository pizzaRepository, IIngredientRepository ingredientRepository)
     : base(nameof(OrderPizzaDialog), recognizer)
 {
     _userState            = userState;
     _pizzaRepository      = pizzaRepository;
     _ingredientRepository = ingredientRepository;
     _orderInfo            = _userState.CreateProperty <OrderInfo>("OrderInfo");
     AddDialog(new TextPrompt(nameof(TextPrompt)));
     AddDialog(new NumberPrompt <int>(nameof(NumberPrompt <int>), null, "es"));
     AddDialog(new ChoicePrompt(nameof(ChoicePrompt), null, "es"));
     AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt), ValidateConfirmation, "es"));
     AddDialog(new PizzaSelectionDialog(_userState, Recognizer, _pizzaRepository, _ingredientRepository));
     AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
     {
         NumberOfPizzasAsync,
         OrderTypeAsync,
         ConfirmPizzaSelectionAsync,
         StartPizzaConfigurationAsync,
         EndTransactionAsync,
     }));
     InitialDialogId = nameof(WaterfallDialog);
 }
Beispiel #4
0
        public MainDialog(
            BotSettings settings,
            BotServices services,
            ResponseManager responseManager,
            UserState userState,
            ConversationState conversationState,
            SampleDialog sampleDialog,
            IBotTelemetryClient telemetryClient)
            : base(nameof(MainDialog), telemetryClient)
        {
            _settings        = settings;
            _services        = services;
            _responseManager = responseManager;
            TelemetryClient  = telemetryClient;

            // Initialize state accessor
            _stateAccessor   = conversationState.CreateProperty <SkillState>(nameof(SkillState));
            _contextAccessor = userState.CreateProperty <SkillContext>(nameof(SkillContext));

            // Register dialogs
            AddDialog(sampleDialog);
        }
Beispiel #5
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var ConversationStateAccessor = _conversationstate.CreateProperty <ConversationData>(nameof(ConversationData));
            var conversationData          = await ConversationStateAccessor.GetAsync(turnContext, () => new ConversationData());

            var UserStateAccessor = _userstate.CreateProperty <UserProfile>(nameof(UserProfile));
            var userProfile       = await UserStateAccessor.GetAsync(turnContext, () => new UserProfile());

            if (string.IsNullOrEmpty(userProfile.Name))
            {
                if (conversationData.PromptUserName)
                {
                    userProfile.Name = turnContext.Activity.Text?.Trim();
                    await turnContext.SendActivityAsync(MessageFactory.Text(string.Format("Hi. {0}", userProfile.Name)));

                    conversationData.PromptUserName = false;
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text("Whats Your Name?"));

                    conversationData.PromptUserName = true;
                }
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("Have a Good Day..."));

                await turnContext.SendActivityAsync(MessageFactory.Text("Last Message Details are:"));

                var MessageTime = (DateTimeOffset)turnContext.Activity.Timestamp;
                var LocalTime   = MessageTime.ToLocalTime();
                conversationData.TStamp    = LocalTime.ToString();
                conversationData.ChannelId = turnContext.Activity.ChannelId.ToString();
                await turnContext.SendActivityAsync(MessageFactory.Text(string.Format("Received At: {0}", conversationData.TStamp)));

                await turnContext.SendActivityAsync(MessageFactory.Text(string.Format("Channel Id: {0}", conversationData.ChannelId)));
            }
        }
        public override void Initialize()
        {
            // Initialize service collection
            Services = new ServiceCollection();

            var conversationState = new ConversationState(new MemoryStorage());

            Services.AddSingleton(conversationState);

            var dialogState = conversationState.CreateProperty <DialogState>(nameof(SkillDialogTestBase));

            Dialogs = new DialogSet(dialogState);

            // Initialise UserState and the SkillContext property uses to provide slots to Skills
            UserState            = new UserState(new MemoryStorage());
            SkillContextAccessor = UserState.CreateProperty <SkillContext>(nameof(SkillContext));
            Services.AddSingleton(UserState);

            Services.AddSingleton(new BotSettingsBase());
            Services.AddSingleton <TestAdapter, DefaultTestAdapter>();
            Services.AddSingleton <ISkillTransport, SkillWebSocketTransport>();
        }
        public MainDialog(
            BotSettings settings,
            BotServices services,
            ResponseManager responseManager,
            UserState userState,
            ConversationState conversationState,
            FindEventsDialog findEventsDialog,
            IBotTelemetryClient telemetryClient)
            : base(nameof(MainDialog), telemetryClient)
        {
            _settings        = settings;
            _services        = services;
            _responseManager = responseManager;
            TelemetryClient  = telemetryClient;

            // Initialize state accessor
            _stateAccessor   = conversationState.CreateProperty <EventSkillState>(nameof(EventSkillState));
            _contextAccessor = userState.CreateProperty <SkillContext>(nameof(SkillContext));

            // Register dialogs
            AddDialog(findEventsDialog ?? throw new ArgumentNullException(nameof(findEventsDialog)));
        }
Beispiel #8
0
        public async Task BotStateSet_SaveAsync()
        {
            var storage = new MemoryStorage();

            // setup userstate
            var userState    = new UserState(storage);
            var userProperty = userState.CreateProperty <int>("userCount");

            // setup convState
            var convState    = new ConversationState(storage);
            var convProperty = convState.CreateProperty <int>("convCount");

            var stateSet = new BotStateSet(userState, convState);

            Assert.Equal(2, stateSet.BotStates.Count);
            var context = TestUtilities.CreateEmptyContext();
            await stateSet.LoadAllAsync(context);

            var userCount = await userProperty.GetAsync(context, () => 0);

            Assert.Equal(0, userCount);
            var convCount = await convProperty.GetAsync(context, () => 0);

            Assert.Equal(0, convCount);

            await userProperty.SetAsync(context, 10);

            await convProperty.SetAsync(context, 20);

            await stateSet.SaveAllChangesAsync(context);

            userCount = await userProperty.GetAsync(context, () => 0);

            Assert.Equal(10, userCount);

            convCount = await convProperty.GetAsync(context, () => 0);

            Assert.Equal(20, convCount);
        }
Beispiel #9
0
        public CountryDialog(UserState userState) : base(nameof(CountryDialog))
        {
            _globalUserStateAccessor = userState.CreateProperty <GlobalUserState>(nameof(GlobalUserState));

            // Add waterfall dialog steps
            var waterfallSteps = new WaterfallStep[]
            {
                SayHiAsync,
                AskCountryAsync,
                HandleCountryAsync,
                SaveStateAsync,
                SummaryAsync,
                EndAsync,
            };

            // Child dialogs
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(CountryPromptName));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #10
0
        public AddGroupDialog(UserState userState, IFlowClient flowClient) : base(nameof(AddGroupDialog))
        {
            _flowClient       = flowClient;
            _userDataAccessor = userState.CreateProperty <UserData>(nameof(UserData));

            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new List <WaterfallStep>
            {
                AskNameStepAsync,
                AskDescriptionStepAsync,
                AskMailNicknameStepAsync,
                AskChannelName,
                AskChannelDescription,
                AskTabName,
                AskTabUrl,
                AskUsers,
                EndDialog
            }));

            InitialDialogId = nameof(WaterfallDialog);
        }
        public MultiTurnBot(BotServices services, UserState userState, ConversationState conversationState, BotSettings botSettings, IBotIntents botIntents, ILoggerFactory loggerFactory)
        {
            _userState         = userState.CheckNullReference();
            _conversationState = conversationState.CheckNullReference();
            _botSettings       = botSettings.CheckNullReference();
            _botIntents        = botIntents.CheckNullReference();

            // Verify LUIS configuration.
            if (!services.CheckNullReference().LuisServices.ContainsKey(botSettings.LuisConfiguration))
            {
                throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{botSettings.LuisConfiguration}`.");
            }
            _luisRecognizer = services.LuisServices[botSettings.LuisConfiguration];


            _entityStateAccessor = _userState.CreateProperty <EntityState>(nameof(EntityState));
            var dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            _dialogSet = new BotDialogSet(dialogStateAccessor, _entityStateAccessor, loggerFactory);

            _logger = loggerFactory.CheckNullReference().CreateLogger <MultiTurnBot>();
        }
Beispiel #12
0
        public IncidentDialog(UserState userState)
            : base(nameof(IncidentDialog))
        {
            _incidentAccessor = userState.CreateProperty <Incident>("Incident");

            // This array defines how the Waterfall will execute.
            var waterfallSteps = new WaterfallStep[]
            {
                LocationStepAsync,
                ProblemStepAsync,
                ContactStepAsync,
                SummaryStepAsync,
            };

            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #13
0
        public MainDispatcher(
            BotServices services,
            IStatePropertyAccessor <OnTurnState> onTurnAccessor,
            UserState userState,
            ConversationState conversationState,
            ILoggerFactory loggerFactory,
            IPimbotServiceProvider provider)
            : base(nameof(MainDispatcher))
        {
            _services               = services ?? throw new ArgumentNullException(nameof(services));
            _logger                 = loggerFactory.CreateLogger <MainDispatcher>();
            _onTurnAccessor         = onTurnAccessor;
            _mainDispatcherAccessor = conversationState.CreateProperty <DialogState>(MainDispatcherStateProperty);
            _userState              = userState;
            _conversationState      = conversationState;
            _customerStateAccessor  = conversationState.CreateProperty <CustomerState>("customerProperty");

            if (conversationState == null)
            {
                throw new ArgumentNullException(nameof(conversationState));
            }

            if (userState == null)
            {
                throw new ArgumentNullException(nameof(userState));
            }

            _cartStateAccessor = userState.CreateProperty <CartState>(nameof(CartState));
            _dialogs           = new DialogSet(_mainDispatcherAccessor);
            AddDialog(new AddItemDialog(services, onTurnAccessor, _cartStateAccessor, provider));
            AddDialog(new RemoveItemDialog(services, onTurnAccessor, _cartStateAccessor));
            AddDialog(new GetUserInfoDialog(services, onTurnAccessor, _cartStateAccessor, _customerStateAccessor, provider));
            AddDialog(new FindItemDialog(services, onTurnAccessor, _cartStateAccessor, provider));
            AddDialog(new ShowCartDialog(services, onTurnAccessor, _cartStateAccessor, provider));
            AddDialog(new ShowOrdersDialog(services, onTurnAccessor, provider));
            AddDialog(new ShowCategoriesDialog(services, onTurnAccessor, provider));
            AddDialog(new DetailItemDialog(services, onTurnAccessor, provider));
        }
Beispiel #14
0
        public async Task State_ForceCallsSaveWithoutCachedBotStateChanges()
        {
            // Mock a storage provider, which counts writes
            var storeCount = 0;
            var dictionary = new Dictionary <string, object>();
            var mock       = new Mock <IStorage>();

            mock.Setup(ms => ms.WriteAsync(It.IsAny <Dictionary <string, object> >(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Callback(() => storeCount++);
            mock.Setup(ms => ms.ReadAsync(It.IsAny <string[]>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(result: (IDictionary <string, object>)dictionary));

            // Arrange
            var userState = new UserState(mock.Object);
            var context   = TestUtilities.CreateEmptyContext();

            // Act
            var propertyA = userState.CreateProperty <string>("propertyA");

            // Set initial value and save
            await propertyA.SetAsync(context, "test");

            await userState.SaveChangesAsync(context);

            // Assert
            Assert.AreEqual(1, storeCount);

            // Saving without changes and wthout force does NOT call .WriteAsync
            await userState.SaveChangesAsync(context);

            Assert.AreEqual(1, storeCount);

            // Forcing save without changes DOES call .WriteAsync
            await userState.SaveChangesAsync(context, true);

            Assert.AreEqual(2, storeCount);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CoreBot"/> class.
        /// <param name="botServices">Bot services.</param>
        /// <param name="accessors">Bot State Accessors.</param>
        /// </summary>
        public ContactAssistantBot(StateBotAccessors accessors, BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory)
        {
            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));

            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState));
            _dialogStateAccessor   = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            // Verify LUIS configuration.
            if (!_services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`.");
            }

            Dialogs = new DialogSet(_dialogStateAccessor);
            Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory));
            Dialogs.Add(new AddContactDialogue(_accessors, loggerFactory));
            Dialogs.Add(new ViewContactsDialogue(_accessors, loggerFactory));
            Dialogs.Add(new DeleteContactDialogue(_accessors, loggerFactory));
        }
Beispiel #16
0
 public PizzaSelectionDialog(UserState userState, OrderPizzaRecognizer recognizer, IPizzaRepository pizzaRepository, IIngredientRepository ingredientRepository)
     : base(nameof(PizzaSelectionDialog), userState, recognizer)
 {
     _userState            = userState;
     _pizzaRepository      = pizzaRepository;
     _ingredientRepository = ingredientRepository;
     _orderInfo            = _userState.CreateProperty <OrderInfo>("OrderInfo");
     AddDialog(new TextPrompt("ChoosePizza", ValidatePizza));
     AddDialog(new ChoicePrompt("ChoicePizzaSize", ValidateMaxAttemptsReached, "es"));
     AddDialog(new ChoicePrompt("ChoicePizzaDough", ValidateMaxAttemptsReached, "es"));
     AddDialog(new ConfirmPrompt("ConfirmPizzaConfiguration", ValidateConfirmation, "es"));
     AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
     {
         AskForPizzaAsync,
         SetPizzaAsync,
         AskForPizzaSizeAsync,
         AskForDoughTypeAsync,
         ConfirmPizzaAsync,
         EndPizzaAsync,
     }));
     AddDialog(new CustomPizzaDialog(_userState, Recognizer, _pizzaRepository, _ingredientRepository));
     InitialDialogId = nameof(WaterfallDialog);
 }
Beispiel #17
0
        public SendEmailDialog(UserState userState, IConfiguration configuration)
            : base(nameof(SendEmailDialog))
        {
            Configuration = configuration;
            UserState     = userState;

            var connectionName = Configuration.GetSection("ConnectionName")?.Value;

            _originatorId = Configuration.GetSection("OriginatorId")?.Value;

            _targetEmail = userState.CreateProperty <string>(TargetEmailProperty);

            var steps = new WaterfallStep[] {
                SignInAsync,
                DisplayTokenAsync,
            };

            AddDialog(new WaterfallDialog(nameof(SendEmailDialog), steps));
            AddDialog(new OAuthPrompt(nameof(OAuthPrompt), new OAuthPromptSettings()
            {
                ConnectionName = connectionName, Text = "Please sign in to continue", Title = "Sign In"
            }));
        }
Beispiel #18
0
        public MainDialog(ConversationState conversationState, UserState userState)
            : base(nameof(MainDialog))
        {
            ConversationState = conversationState;
            UserState         = userState;
            Accessors         = new ChatbotAccessors(conversationState: ConversationState as ConversationState,
                                                     userState: UserState as UserState)
            {
                ConversationStateImplAccessor = ConversationState.CreateProperty <ConversationStateImpl>
                                                    (ChatbotAccessors.ConversationStateImplName),
                UserStateImplAccessor = UserState.CreateProperty <UserStateImpl>
                                            (ChatbotAccessors.UserStateImplName)
            };

            WaterfallStep[] steps = new WaterfallStep[] {
                RouteAsync,
                RefreshAsync
            };

            AddDialog(new WaterfallDialog(WaterfallDialogName, steps));
            AddDialog(new WelcomeDialog(Accessors, DialogTypes.Welcome.ToString()));
            AddDialog(new EchoDialog(Accessors, DialogTypes.Echo.ToString()));
        }
Beispiel #19
0
        public MainDialog(
            SkillConfigurationBase services,
            ConversationState conversationState,
            UserState userState,
            IBotTelemetryClient telemetryClient,
            IServiceManager serviceManager,
            bool skillMode)
            : base(nameof(MainDialog), telemetryClient)
        {
            _skillMode         = skillMode;
            _services          = services;
            _conversationState = conversationState;
            _userState         = userState;
            _serviceManager    = serviceManager;
            TelemetryClient    = telemetryClient;

            // Initialize state accessor
            _conversationStateAccessor = _conversationState.CreateProperty <SkillConversationState>(nameof(SkillConversationState));
            _userStateAccessor         = _userState.CreateProperty <SkillUserState>(nameof(SkillUserState));

            // RegisterDialogs
            RegisterDialogs();
        }
Beispiel #20
0
        public async Task LocaleConverterMiddleware_ConvertFromFrench()
        {
            var userState          = new UserState(new MemoryStorage());
            var userLocaleProperty = userState.CreateProperty <string>("locale");

            TestAdapter adapter = new TestAdapter()
                                  .Use(userState)
                                  .Use(new LocaleConverterMiddleware(userLocaleProperty, "en-us", LocaleConverter.Converter));

            await new TestFlow(adapter, async(context, cancellationToken) =>
            {
                if (!await ChangeLocaleRequest(context, userLocaleProperty))
                {
                    await context.SendActivityAsync(context.Activity.AsMessageActivity().Text);
                }
                return;
            })
            .Send("set my locale to fr-fr")
            .AssertReply("Changing your locale to fr-fr")
            .Send("Set a meeting on 30/9/2017")
            .AssertReply("Set a meeting on 9/30/2017")
            .StartTestAsync();
        }
        public async Task TranslatorMiddleware_TranslateFrenchToEnglishToUserLanguage()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Post, "https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
            .Respond("application/jwt", "<--valid-bearer-token-->");
            mockHttp.When(HttpMethod.Get, GetRequestDetect("salut"))
            .Respond("application/xml", GetResponseDetect("fr"));
            mockHttp.When(HttpMethod.Get, GetRequestDetect("Hello"))
            .Respond("application/xml", GetResponseDetect("en"));
            mockHttp.When(HttpMethod.Post, @"https://api.microsofttranslator.com/v2/Http.svc/TranslateArray2")
            .WithPartialContent("salut</string>")
            .Respond("application/xml", GetResponse("TranslatorMiddleware_TranslateFrenchToEnglishToUserLanguage_Salut.xml"));
            mockHttp.When(HttpMethod.Post, @"https://api.microsofttranslator.com/v2/Http.svc/TranslateArray2")
            .WithPartialContent("Hello</string>")
            .Respond("application/xml", GetResponse("TranslatorMiddleware_TranslateFrenchToEnglishToUserLanguage_Hello.xml"));

            var userState             = new UserState(new MemoryStorage());
            var languageStateProperty = userState.CreateProperty("languageState", () => "en");

            var adapter = new TestAdapter()
                          .Use(userState)
                          .Use(new TranslationMiddleware(new[] { "en" }, _translatorKey, new Dictionary <string, List <string> >(), new CustomDictionary(), languageStateProperty, true, mockHttp.ToHttpClient()));

            await new TestFlow(adapter, async(context, cancellationToken) =>
            {
                if (!await HandleChangeLanguageRequest(context, languageStateProperty))
                {
                    await context.SendActivityAsync(context.Activity.AsMessageActivity().Text);
                }
            })
            .Send("set my language to fr")
            .AssertReply("Changing your language to fr")
            .Send("salut")
            .AssertReply("Salut")
            .StartTestAsync();
        }
Beispiel #22
0
        public async Task LocaleConverterMiddleware_ConvertFromSpanishSpain()
        {
            var userState          = new UserState(new MemoryStorage());
            var userLocaleProperty = userState.CreateProperty <string>("locale");


            TestAdapter adapter = new TestAdapter()
                                  .Use(userState)
                                  .Use(new LocaleConverterMiddleware(userLocaleProperty, "en-us", LocaleConverter.Converter));

            await new TestFlow(adapter, async(context, cancellationToken) =>
            {
                if (!await ChangeLocaleRequest(context, userLocaleProperty))
                {
                    await context.SendActivityAsync(context.Activity.AsMessageActivity().Text);
                }
                return;
            })
            .Send("set my locale to es-es")
            .AssertReply("Changing your locale to es-es")
            .Send("La reunión será a las 15:00")
            .AssertReply("La reunión será a las 3:00 PM")
            .StartTestAsync();
        }
Beispiel #23
0
        public async Task LocaleConverterMiddleware_ConvertToChinese()
        {
            var userState          = new UserState(new MemoryStorage());
            var userLocaleProperty = userState.CreateProperty <string>("locale");

            TestAdapter adapter = new TestAdapter()
                                  .Use(userState)
                                  .Use(new LocaleConverterMiddleware(userLocaleProperty, "zh-cn", LocaleConverter.Converter));


            await new TestFlow(adapter, async(context, cancellationToken) =>
            {
                if (!await ChangeLocaleRequest(context, userLocaleProperty))
                {
                    await context.SendActivityAsync(context.Activity.AsMessageActivity().Text);
                }
                return;
            })
            .Send("set my locale to en-us")
            .AssertReply("Changing your locale to en-us")
            .Send("Book me a plane ticket for France on 12/25/2018")
            .AssertReply("Book me a plane ticket for France on 2018/12/25")
            .StartTestAsync();
        }
        public OnboardingDialog(
            BotServices botServices,
            UserState userState,
            IBotTelemetryClient telemetryClient)
            : base(nameof(OnboardingDialog))
        {
            _accessor       = userState.CreateProperty <OnboardingState>(nameof(OnboardingState));
            InitialDialogId = nameof(OnboardingDialog);

            var onboarding = new WaterfallStep[]
            {
                AskForName,
                FinishOnboardingDialog,
            };

            // To capture built-in waterfall dialog telemetry, set the telemetry client
            // to the new waterfall dialog and add it to the component dialog
            TelemetryClient = telemetryClient;
            AddDialog(new WaterfallDialog(InitialDialogId, onboarding)
            {
                TelemetryClient = telemetryClient
            });
            AddDialog(new TextPrompt(DialogIds.NamePrompt));
        }
Beispiel #25
0
        public UserProfileDialog(string dialogId, UserState userState) : base(dialogId)
        {
            _userProfileAccessor = userState.CreateProperty <UserProfile>("UserProfile");

            var waterfallSteps = new WaterfallStep[]
            {
                FirstNameStep,
                LastNameStep,
                EmailStep,
                CompanyNameStep,
                ConfirmStep,
                SummaryStep
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new TextPrompt("EmailPrompt", EmailPromptValidatorAsync));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt))
            {
                Style = ListStyle.HeroCard
            });

            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #26
0
        public async Task BotStateSet_ReturnsDefaultForNullValueType()
        {
            var storage = new MemoryStorage();

            var turnContext = TestUtilities.CreateEmptyContext();

            // setup userstate
            var userState    = new UserState(storage);
            var userProperty = userState.CreateProperty <SomeComplexType>("userStateObject");

            // setup convState
            var convState    = new ConversationState(storage);
            var convProperty = convState.CreateProperty <SomeComplexType>("convStateObject");

            var stateSet = new BotStateSet(userState, convState);

            Assert.Equal(2, stateSet.BotStates.Count);

            var userObject = await userProperty.GetAsync(turnContext, () => null);

            Assert.Null(userObject);

            // Ensure we also get null on second attempt
            userObject = await userProperty.GetAsync(turnContext, () => null);

            Assert.Null(userObject);

            var convObject = await convProperty.GetAsync(turnContext, () => null);

            Assert.Null(convObject);

            // Ensure we also get null on second attempt
            convObject = await convProperty.GetAsync(turnContext, () => null);

            Assert.Null(convObject);
        }
    public UserProfileDialog(UserState userState)
        : base(nameof(UserProfileDialog))
    {
        _userProfileAccessor = userState.CreateProperty <UserProfile>("UserProfile");
        // This array defines how the Waterfall will execute.
        var waterfallSteps = new WaterfallStep[]
        {
            TransportStepAsync,
            NameStepAsync,
            NameConfirmStepAsync,
            AgeStepAsync,
            ConfirmStepAsync,
            SummaryStepAsync,
        };

        // Add named dialogs to the DialogSet. These names are saved in the dialog state.
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
        AddDialog(new TextPrompt(nameof(TextPrompt)));
        AddDialog(new NumberPrompt <int>(nameof(NumberPrompt <int>), AgePromptValidatorAsync));
        AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
        AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
        // The initial child Dialog to run.
        InitialDialogId = nameof(WaterfallDialog);
    }
Beispiel #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IStorage dataStore         = new MemoryStorage();
            var      conversationState = new ConversationState(dataStore);
            var      userState         = new UserState(dataStore);
            var      userStateMap      = userState.CreateProperty <StateMap>("user");

            // Get Bot file
            string rootDialog = string.Empty;
            var    botFile    = Configuration.GetSection("bot").Get <BotFile>();
            var    botProject = BotProject.Load(botFile);

            rootDialog = botProject.entry;

            var accessors = new TestBotAccessors
            {
                ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                ConversationState       = conversationState,
                RootDialogFile          = botProject.path + rootDialog
            };

            services.AddBot <IBot>(
                (IServiceProvider sp) =>
            {
                return(new TestBot(accessors));
            },
                (BotFrameworkOptions options) =>
            {
                options.OnTurnError = async(turnContext, exception) =>
                {
                    await conversationState.ClearStateAsync(turnContext);
                    await conversationState.SaveChangesAsync(turnContext);
                };
                options.Middleware.Add(new AutoSaveStateMiddleware(conversationState));
            });
        }
        public EventDialogBase(
            string dialogId,
            BotSettings settings,
            BotServices services,
            ResponseManager responseManager,
            ConversationState conversationState,
            UserState userState,
            IBotTelemetryClient telemetryClient)
            : base(dialogId)
        {
            Services        = services;
            ResponseManager = responseManager;
            StateAccessor   = conversationState.CreateProperty <EventSkillState>(nameof(EventSkillState));
            UserAccessor    = userState.CreateProperty <EventSkillUserState>(nameof(EventSkillUserState));
            TelemetryClient = telemetryClient;

            // NOTE: Uncomment the following if your skill requires authentication
            // if (!settings.OAuthConnections.Any())
            // {
            //    throw new Exception("You must configure an authentication connection before using this component.");
            // }

            // AddDialog(new MultiProviderAuthDialog(settings.OAuthConnections));
        }
        public UserProfileDialog(UserState userState)
            : base(nameof(UserProfileDialog))
        {
            _userProfileAccessor = userState.CreateProperty <UserProfile>("UserProfile");


            // This array defines how the Waterfall will execute.
            var waterfallSteps = new WaterfallStep[]
            {
                CpfConfirmStepAsync,
                ConsultaDebitosStepAsync,
                VerificarDividaStepAsync,
                ValorEntradaStepAsync,
                ParcelarDividaStepAsync,
                GerarContratoStepAsync,
                ContratoEnviadoStepAsync,
            };

            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));

            AddDialog(new NumberPrompt <long>(nameof(NumberPrompt <long>), CpfCnpjPromptValidatorAsync));
            AddDialog(new TextPrompt("ValorEntrada", ValorEntradaPromptValidatorAsync));
            AddDialog(new TextPrompt("ValidarEmail", EmailPromptValidatorAsync));

            AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt), null, "pt-BR"));



            //this.Dialogs.Add(Keys.Money, new Microsoft.Bot.Builder.Dialogs.NumberPrompt<int>(Culture.English, Validators.MoneyValidator));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }