예제 #1
0
        public TurnIdMiddlewareTests()
        {
            _testStorage       = new TestStorage();
            _mockNext          = new Mock <NextDelegate>();
            _conversationState = new ConversationState(_testStorage);
            _userState         = new UserState(_testStorage);
            _mockUserState     = new Mock <UserState>();

            _mockConversationDialogState = new Mock <IStatePropertyAccessor <Microsoft.Bot.Builder.Dialogs.DialogState> >();
            _feedbackBotStateRepository  = new FeedbackBotStateRepository(_conversationState, _userState);
            _feedbackBotStateRepository.ConversationDialogState = _mockConversationDialogState.Object;

            _mockTurnContext = new Mock <ITurnContext>();
            _mockTurnContext
            .Setup(m => m.TurnState)
            .Returns(new TurnContextStateCollection());

            _testActivityList = new List <Activity>();

            // set up the test activity with some random text and known ChannelId and ConversationId
            _testActivity = new Activity
            {
                Type         = ActivityTypes.Message,
                Text         = Guid.NewGuid().ToString(),
                ChannelId    = "Test",
                Conversation = new ConversationAccount()
                {
                    Id = "TestConversation"
                }
            };

            _testActivityList.Add(_testActivity);

            _mockTurnContext
            .Setup(m => m.Activity)
            .Returns(_testActivity);

            _mockTurnContext
            .Setup(m => m.OnSendActivities(It.IsAny <SendActivitiesHandler>()))
            .Callback <SendActivitiesHandler>(async(handler) =>
            {
                await handler.Invoke(_mockTurnContext.Object, _testActivityList, () => Task.FromResult(new List <ResourceResponse>().ToArray()));
            });

            _sut = new TurnIdMiddleware(_feedbackBotStateRepository);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // If using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // configure JSON serializer
            this.ConfigureJsonSerializer();

            // bind configuration settings
            this.ConfigureOptions(services);

            // add & configure localization
            this.ConfigureLocalization(services);

            // register services
            this.RegisterServices(services);

            // register commands. These are usually conversational interrupts
            this.RegisterAllDialogCommands(services);

            // register all surveys
            this.RegisterAllSurveys(services);

            // register all component builders
            this.RegisterAllComponentBuilders(services);

            string secretKey   = this.Configuration.GetSection("botFileSecret")?.Value;
            string botFilePath = this.Configuration.GetSection("botFilePath")?.Value;

            // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
            BotConfiguration botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);

            services.AddSingleton(
                sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded."));

            // Retrieve current endpoint.
            var environment = this.isProduction ? "production" : "development";
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment);

            if (!(service is EndpointService endpointService))
            {
                throw new InvalidOperationException(
                          $"The .bot file does not contain an endpoint with name '{environment}'.");
            }

            IStorage dataStore = this.ConfigureStateDataStore(this.Configuration);

            // add & configure bot framework
            services.AddBot <FeedbackBot>(
                options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(
                    this.Configuration["MicrosoftAppId"],
                    this.Configuration["MicrosoftAppPassword"]);

                // Catches any errors that occur during a conversation turn and logs them.
                options.OnTurnError = async(context, exception) =>
                {
                    await Task.Run(
                        () =>
                    {
                        var botLogger = this.loggerFactory.CreateLogger <FeedbackBot>();
                        botLogger.LogError($"Exception caught: {context.Activity.Text} {Environment.NewLine} {exception}");
                    });
                };

                var conversationState = new ConversationState(dataStore);
                options.State.Add(conversationState);

                var userState = new UserState(dataStore);
                options.State.Add(userState);

                options.Middleware.Add <ConversationLogMiddleware>(services);
                options.Middleware.Add <ChannelConfigurationMiddleware>(services);
                options.Middleware.Add <ConversationLogMiddleware>(services);
                options.Middleware.Add <ActivityIdMiddleware>(services);
                options.Middleware.Add <TurnIdMiddleware>(services);
                options.Middleware.Add <IMessageQueueMiddleware>(services);
            });

            services.AddSingleton <IFeedbackBotStateRepository, FeedbackBotStateRepository>(
                sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException(
                        "BotFrameworkOptions must be configured prior to setting up the State accessors");
                }

                var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();
                if (conversationState == null)
                {
                    throw new InvalidOperationException(
                        "ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                var userState = options.State.OfType <UserState>().FirstOrDefault();
                if (userState == null)
                {
                    throw new InvalidOperationException(
                        "UserState must be defined and added before adding user-scoped state accessors.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var feedbackBotState = new FeedbackBotStateRepository(conversationState, userState)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    UserProfile             = userState.CreateProperty <UserProfile>("UserProfile"),
                };

                return(feedbackBotState);
            });
        }
        public SmsMessageQueueTests()
        {
            _testStorage          = new TestStorage();
            _mockSmsQueueProvider = new Mock <ISmsQueueProvider>();
            _mockNotifyOptions    = new Mock <IOptions <Core.Configuration.Notify> >();

            _testOutgoingQueueName = Guid.NewGuid().ToString();
            var testNotify = new Core.Configuration.Notify {
                OutgoingMessageQueueName = _testOutgoingQueueName
            };

            _mockNotifyOptions.Setup(m => m.Value).Returns(testNotify);

            _mockNext          = new Mock <NextDelegate>();
            _conversationState = new ConversationState(_testStorage);
            _userState         = new UserState(_testStorage);
            _mockUserState     = new Mock <UserState>();

            _mockConversationDialogState = new Mock <IStatePropertyAccessor <Microsoft.Bot.Builder.Dialogs.DialogState> >();
            _feedbackBotStateRepository  = new FeedbackBotStateRepository(_conversationState, _userState);
            _feedbackBotStateRepository.ConversationDialogState = _mockConversationDialogState.Object;

            _mockTurnContext = new Mock <ITurnContext>();
            _mockTurnContext
            .Setup(m => m.TurnState)
            .Returns(new TurnContextStateCollection());

            _testActivityList = new List <Activity>();

            // set up the test activity with some random text and known ChannelId and ConversationId
            _testActivity = new Activity
            {
                Id           = Guid.NewGuid().ToString(),
                Type         = ActivityTypes.Message,
                Text         = Guid.NewGuid().ToString(),
                ChannelId    = "Test",
                Conversation = new ConversationAccount()
                {
                    Id = "TestConversation"
                },
                From = new ChannelAccount {
                    Id = "TestFromAccount"
                },
                Recipient = new ChannelAccount {
                    Id = "TestRecipientAccount"
                },
                ChannelData = new object()
            };

            _mockTurnContext
            .Setup(m => m.Activity)
            .Returns(_testActivity);

            _mockTurnContext
            .Setup(m => m.OnSendActivities(It.IsAny <SendActivitiesHandler>()))
            .Callback <SendActivitiesHandler>(async(handler) =>
            {
                await handler.Invoke(_mockTurnContext.Object, _testActivityList, () => Task.FromResult(new List <ResourceResponse>().ToArray()));
            });

            _sut = new SmsMessageQueue(_mockSmsQueueProvider.Object, _mockNotifyOptions.Object, _feedbackBotStateRepository);
        }