示例#1
0
 public void ConfigureInspectionMiddleWare(BotFrameworkAdapter adapter, BotSettings settings, IStorage storage)
 {
     if (settings?.Feature?.UseInspectionMiddleware == true)
     {
         adapter.Use(new InspectionMiddleware(new InspectionState(storage)));
     }
 }
示例#2
0
 public void ConfigureInspectionMiddleWare(BotFrameworkAdapter adapter, BotSettings settings, IServiceProvider s)
 {
     if (settings?.Feature?.UseInspectionMiddleware == true)
     {
         adapter.Use(s.GetService <TelemetryInitializerMiddleware>());
     }
 }
示例#3
0
 public void ConfigureShowTypingMiddleWare(BotFrameworkAdapter adapter, BotSettings settings)
 {
     if (settings?.Feature?.UseShowTypingMiddleware == true)
     {
         adapter.Use(new ShowTypingMiddleware());
     }
 }
        /// <summary>
        /// Adds and configures services for a <typeparamref name="TBot">specified bot type</typeparamref> to the <see cref="IServiceCollection" />.
        /// </summary>
        /// <typeparam name="TBot">A concrete type of <see cref="IBot"/> that is to be registered and exposed to the Bot Framework.</typeparam>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <param name="configureAction">A callback that can further be used to configure the bot.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceCollection AddBot <TBot>(this IServiceCollection services, Action <BotFrameworkOptions> configureAction = null)
            where TBot : class, IBot
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configureAction != null)
            {
                services.Configure(configureAction);
            }

            services.AddTransient <IBot, TBot>();

            services.AddSingleton(sp =>
            {
                var options             = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider, options.ConnectorClientRetryPolicy, options.HttpClient)
                {
                    OnTurnError = options.OnTurnError,
                };

                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                return(botFrameworkAdapter);
            });

            return(services);
        }
示例#5
0
        protected override IAdapterIntegration CreateAdapter()
        {
            var adapter = new BotFrameworkAdapter(_credentialProvider, middleware: new DataBagsMiddleware(Accessors));

            adapter.Use(new AutoSaveStateMiddleware(Accessors.BotStates));
            return(adapter);
        }
示例#6
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();

            var options = new BotFrameworkOptions();

            options.Middleware.Add(new ShowTypingMiddleware());

            var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider)
            {
                OnTurnError = options.OnTurnError,
            };

            foreach (var middleware in options.Middleware)
            {
                botFrameworkAdapter.Use(middleware);
            }

            //return botFrameworkAdapter;

            var adapter = new InteceptorAdapter(botFrameworkAdapter);

            container.RegisterInstance <IAdapterIntegration>(adapter);

            container.RegisterType <IBot, TestBot>();
        }
示例#7
0
 public void ConfigureSetSpeakMiddleWare(BotFrameworkAdapter adapter, BotSettings settings)
 {
     if (settings?.Feature?.UseSetSpeakMiddleware == true && settings.Speech != null)
     {
         adapter.Use(new SetSpeakMiddleware(settings.Speech.VoiceFontName, settings.Speech.FallbackToTextForSpeechIfEmpty));
     }
 }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IAdapterIntegration>(sp =>
            {
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;

                IStorage dataStore = new MemoryStorage();
                options.State.Add(new ConversationState(dataStore));
                options.Middleware.Add(new AutoSaveStateMiddleware(options.State.ToArray()));
                options.Middleware.Add(new ShowTypingMiddleware());

                var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider, options.ChannelProvider, options.ConnectorClientRetryPolicy, options.HttpClient)
                {
                    OnTurnError = options.OnTurnError,
                };

                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                //return botFrameworkAdapter;

                return(new InteceptorAdapter(botFrameworkAdapter));
            });

            services.AddBot <TestBot>();

            //services.AddBot<TestBot>(options =>
            //{
            //    IStorage dataStore = new MemoryStorage();
            //    options.State.Add(new ConversationState(dataStore));
            //    options.Middleware.Add(new AutoSaveStateMiddleware(options.State.ToArray()));
            //    options.Middleware.Add(new ShowTypingMiddleware());
            //});

            services.AddSingleton(sp =>
            {
                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 accessors = new TestBotAccessors
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState")
                };

                return(accessors);
            });
        }
示例#9
0
        public static HttpConfiguration MapBotFramework(this HttpConfiguration httpConfiguration, Action <BotFrameworkConfigurationBuilder> configurer)
        {
            var options        = new BotFrameworkOptions();
            var optionsBuilder = new BotFrameworkConfigurationBuilder(options);

            configurer(optionsBuilder);

            ConfigureBotRoutes(BuildAdapter());

            return(httpConfiguration);

            BotFrameworkAdapter BuildAdapter()
            {
                var adapter = new BotFrameworkAdapter(options.CredentialProvider);

                foreach (var middleware in options.Middleware)
                {
                    adapter.Use(middleware);
                }

                return(adapter);
            }

            void ConfigureBotRoutes(BotFrameworkAdapter adapter)
            {
                var routes  = httpConfiguration.Routes;
                var baseUrl = options.Paths.BasePath;

                if (!baseUrl.EndsWith("/"))
                {
                    baseUrl += "/";
                }

                if (options.EnableProactiveMessages)
                {
                    routes.MapHttpRoute(
                        "BotFramework - Proactive Message Handler",
                        baseUrl + options.Paths.ProactiveMessagesPath,
                        defaults: null,
                        constraints: null,
                        handler: new BotProactiveMessageHandler(adapter));
                }

                routes.MapHttpRoute(
                    "BotFramework - Message Handler",
                    baseUrl + options.Paths.MessagesPath,
                    defaults: null,
                    constraints: null,
                    handler: new BotMessageHandler(adapter));
            }
        }
示例#10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(sp =>
            {
                IStorage dataStore = new MemoryStorage();

                var conversationState = new ConversationState(dataStore);

                var accessors = new TestBotAccessors
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    ConversationState       = new ConversationState(dataStore)
                };

                return(accessors);
            });

            services.AddSingleton <IAdapterIntegration>(sp =>
            {
                var options   = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                var accessors = sp.GetRequiredService <TestBotAccessors>();

                options.Middleware.Add(new AutoSaveStateMiddleware(accessors.ConversationState));
                options.Middleware.Add(new ShowTypingMiddleware());

                var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider, options.ChannelProvider, options.ConnectorClientRetryPolicy, options.HttpClient)
                {
                    OnTurnError = options.OnTurnError,
                };

                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                //return botFrameworkAdapter;

                return(new InteceptorAdapter(botFrameworkAdapter));
            });

            services.AddBot <TestBot>();

            //services.AddBot<TestBot>(options =>
            //{
            //    IStorage dataStore = new MemoryStorage();
            //    options.State.Add(new ConversationState(dataStore));
            //    options.Middleware.Add(new AutoSaveStateMiddleware(options.State.ToArray()));
            //    options.Middleware.Add(new ShowTypingMiddleware());
            //});
        }
        /// <summary>
        /// Adds and configures services for a <typeparamref name="TBot">specified bot type</typeparamref> to the <see cref="IServiceCollection" />.
        /// </summary>
        /// <typeparam name="TBot">A concrete type of <see cref="IBot"/> that is to be registered and exposed to the Bot Framework.</typeparam>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <param name="configureAction">A callback that can further be used to configure the bot.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceCollection AddBot <TBot>(this IServiceCollection services, Action <BotFrameworkOptions> configureAction = null)
            where TBot : class, IBot
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configureAction != null)
            {
                services.Configure(configureAction);
            }

            services.TryAddSingleton <ILogger <IAdapterIntegration> >(sp =>
            {
                // Loggers introduce a lock during creation, make a singleton.
                var loggerFactory = sp.GetRequiredService <ILoggerFactory>();
                return(new Logger <IAdapterIntegration>(loggerFactory));
            });

            services.AddTransient <IBot, TBot>();

            services.TryAddSingleton <IAdapterIntegration>(sp =>
            {
                var options             = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                var logger              = sp.GetRequiredService <ILogger <IAdapterIntegration> >();
                var botFrameworkAdapter = new BotFrameworkAdapter(
                    options.CredentialProvider,
                    options.ChannelProvider,
                    options.ConnectorClientRetryPolicy,
                    options.HttpClient,
                    null,
                    logger)
                {
                    OnTurnError = options.OnTurnError,
                };

                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                return(botFrameworkAdapter);
            });

            return(services);
        }
        public static HttpConfiguration MapBotFramework(this HttpConfiguration httpConfiguration, Action <BotFrameworkConfigurationBuilder> configurer)
        {
            var optionsBuilder = new BotFrameworkConfigurationBuilder();

            configurer(optionsBuilder);

            var options = optionsBuilder.BotFrameworkOptions;

            ConfigureBotRoute(BuildAdapter());

            return(httpConfiguration);

            BotFrameworkAdapter BuildAdapter()
            {
                var adapter = new BotFrameworkAdapter(options.AppId, options.AppPassword);

                foreach (var middleware in options.Middleware)
                {
                    adapter.Use(middleware);
                }

                return(adapter);
            }

            void ConfigureBotRoute(BotFrameworkAdapter adapter)
            {
                var botActivitiesRouteUrl = options.RouteBaseUrl;

                if (!botActivitiesRouteUrl.EndsWith("/"))
                {
                    botActivitiesRouteUrl += "/";
                }

                botActivitiesRouteUrl += "activities";

                httpConfiguration.Routes.MapHttpRoute(
                    "BotFrameworkV4 Activities Controller",
                    botActivitiesRouteUrl,
                    defaults: null,
                    constraints: null,
                    handler: new BotActivitiesHandler(adapter));
            }
        }
        /// <summary>
        /// Adds and configures services for a <typeparamref name="TBot">specified bot type</typeparamref> to the <see cref="IServiceCollection" />.
        /// </summary>
        /// <typeparam name="TBot">A concrete type of <see cref="IBot"/ > that is to be registered and exposed to the Bot Framework.</typeparam>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <param name="configureAction">A callback that can further be used to configure the bot.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceCollection AddBot <TBot, TBotState>(this IServiceCollection services)
            where TBot : class, IBot
            where TBotState : class, new()
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddTransient <IBot, TBot>();

            services.AddSingleton(sp =>
            {
                var environmentVariables = Environment.GetEnvironmentVariables();
                var options = new BotFrameworkOptions()
                {
                    CredentialProvider         = new FunctionsCredentialProvider(environmentVariables),
                    ConnectorClientRetryPolicy = new RetryPolicy(new BotFrameworkHttpStatusCodeErrorDetectionStrategy(), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)),
                    HttpClient = new HttpClient(),
                };

                options.Middleware.Add(new CatchExceptionMiddleware <Exception>(async(context, exception) =>
                {
                    await context.TraceActivity("EchoBot Exception", exception);
                    await context.SendActivity("Sorry, it looks like something went wrong!");
                }));

                var memoryStore = new MemoryStorage();
                options.Middleware.Add(new ConversationState <TBotState>(memoryStore));

                var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider, options.ConnectorClientRetryPolicy, options.HttpClient);
                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                return(botFrameworkAdapter);
            });

            return(services);
        }
        public async Task <HttpResponseMessage> OAuthCallback(
            [FromQuery] string code,
            [FromQuery] string state,
            CancellationToken cancellationToken)
        {
            try
            {
                var    queryParams = state;
                object tokenCache  = new Microsoft.Identity.Client.TokenCache();

                var cfbytes = WebEncoders.Base64UrlDecode(queryParams);
                var _cf     = JsonConvert.DeserializeObject <ConversationReference>(System.Text.Encoding.UTF8.GetString(cfbytes));

                // Exchange the Auth code with Access token
                var token = await AuthenticationHelper.GetTokenByAuthCodeAsync(code);

                // create the context from the ConversationReference
                // this require also the storage to store context.state
                CloudStorageAccount csa     = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("TABLE_CONNSTRING"));
                IStorage            storage = new AzureTableStorage(csa, Environment.GetEnvironmentVariable("tablename"));

                BotFrameworkAdapter bot = new BotFrameworkAdapter(Environment.GetEnvironmentVariable("MicrosoftAppId"), Environment.GetEnvironmentVariable("MicrosoftAppPassword"));
                bot.Use(new UserStateManagerMiddleware(storage));
                await bot.ContinueConversation(_cf, async (IBotContext context) =>
                {
                    // store the acces token in the BotState
                    context.State.UserProperties["token"] = token;
                    //send logged in message using context created
                    context.Reply("You are now logged in");
                });

                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
示例#15
0
        /// <summary>
        /// Map the Bot Framework into the request execution pipeline.
        /// </summary>
        /// <param name="httpConfiguration">The <see cref="HttpConfiguration" /> to map the bot into.</param>
        /// <param name="configurer">A callback to configure the bot.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static HttpConfiguration MapBotFramework(this HttpConfiguration httpConfiguration, Action <BotFrameworkConfigurationBuilder> configurer = null)
        {
            if (httpConfiguration == null)
            {
                throw new ArgumentNullException(nameof(httpConfiguration));
            }

            var options        = new BotFrameworkOptions();
            var optionsBuilder = new BotFrameworkConfigurationBuilder(options);

            configurer?.Invoke(optionsBuilder);

            var adapter = httpConfiguration.DependencyResolver.GetService(typeof(IAdapterIntegration)) as IAdapterIntegration;

            if (adapter == null)
            {
                var credentialProvider = ResolveCredentialProvider(options);

                var botFrameworkAdapter = new BotFrameworkAdapter(credentialProvider, options.AuthenticationConfiguration, options.ChannelProvider, options.ConnectorClientRetryPolicy, options.HttpClient);

                // error handler
                botFrameworkAdapter.OnTurnError = options.OnTurnError;

                // add middleware
                foreach (var middleware in options.Middleware)
                {
                    botFrameworkAdapter.Use(middleware);
                }

                adapter = botFrameworkAdapter;
            }

            ConfigureBotRoutes(httpConfiguration, options, adapter);

            ConfigureCustomEndpoints();

            return(httpConfiguration);
        }
示例#16
0
        /// <summary>
        /// Initializes and adds a bot adapter to the HTTP request pipeline, using custom endpoint paths for the bot.
        /// </summary>
        /// <param name="applicationBuilder">The application builder for the ASP.NET application.</param>
        /// <param name="configurePaths">Allows you to modify the endpoints for the bot.</param>
        /// <returns>The updated application builder.</returns>
        /// <remarks>This method adds any middleware from the <see cref="BotFrameworkOptions"/> provided in the
        /// <see cref="ServiceCollectionExtensions.AddBot{TBot}(IServiceCollection, Action{BotFrameworkOptions})"/>
        /// method to the adapter.</remarks>
        public static IApplicationBuilder UseBotFramework(this IApplicationBuilder applicationBuilder, Action <BotFrameworkPaths> configurePaths)
        {
            if (applicationBuilder == null)
            {
                throw new ArgumentNullException(nameof(applicationBuilder));
            }

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

            var options = applicationBuilder.ApplicationServices.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;

            var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider, options.ConnectorClientRetryPolicy);

            foreach (var middleware in options.Middleware)
            {
                botFrameworkAdapter.Use(middleware);
            }

            var paths = new BotFrameworkPaths();

            configurePaths(paths);

            if (options.EnableProactiveMessages)
            {
                applicationBuilder.Map(
                    paths.BasePath + paths.ProactiveMessagesPath,
                    botProactiveAppBuilder => botProactiveAppBuilder.Run(new BotProactiveMessageHandler(botFrameworkAdapter).HandleAsync));
            }

            applicationBuilder.Map(
                paths.BasePath + paths.MessagesPath,
                botActivitiesAppBuilder => botActivitiesAppBuilder.Run(new BotMessageHandler(botFrameworkAdapter).HandleAsync));

            return(applicationBuilder);
        }
        private static BotFrameworkAdapter BotFrameworkAdapterSingletonFactory(IServiceProvider serviceProvider)
        {
            var options = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
            var logger  = serviceProvider.GetRequiredService <ILogger <IAdapterIntegration> >();

            var botFrameworkAdapter = new BotFrameworkAdapter(
                options.CredentialProvider,
                options.ChannelProvider,
                options.ConnectorClientRetryPolicy,
                options.HttpClient,
                null,
                logger)
            {
                OnTurnError = options.OnTurnError,
            };

            foreach (var middleware in options.Middleware)
            {
                botFrameworkAdapter.Use(middleware);
            }

            return(botFrameworkAdapter);
        }
        public static IApplicationBuilder UseBotFramework(this IApplicationBuilder applicationBuilder)
        {
            var options = applicationBuilder.ApplicationServices.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;

            var botFrameworkAdapter = new BotFrameworkAdapter(options.ApplicationId, options.ApplicationPassword);

            foreach (var middleware in options.Middleware)
            {
                botFrameworkAdapter.Use(middleware);
            }

            var botActivitiesPath = new PathString(options.RouteBaseUrl);

            botActivitiesPath.Add("/activities");

            applicationBuilder.Map(
                botActivitiesPath,
                botActivitiesAppBuilder => botActivitiesAppBuilder.Run(BotRequestHandler));

            return(applicationBuilder);

            async Task BotRequestHandler(HttpContext httpContext)
            {
                var request  = httpContext.Request;
                var response = httpContext.Response;

                if (request.Method != HttpMethods.Post)
                {
                    response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;

                    return;
                }

                if (request.ContentType != "application/json")
                {
                    response.StatusCode = (int)HttpStatusCode.NotAcceptable;

                    return;
                }

                if (request.ContentLength == 0)
                {
                    response.StatusCode = (int)HttpStatusCode.BadRequest;

                    return;
                }

                var activity = default(Activity);

                using (var bodyReader = new JsonTextReader(new StreamReader(request.Body, Encoding.UTF8)))
                {
                    activity = ActivitySerializer.Deserialize <Activity>(bodyReader);
                }

                try
                {
                    await botFrameworkAdapter.ProcessActivity(
                        request.Headers["Authorization"],
                        activity,
                        botContext =>
                    {
                        var bot = httpContext.RequestServices.GetRequiredService <IBot>();

                        return(bot.OnReceiveActivity(botContext));
                    });

                    response.StatusCode = (int)HttpStatusCode.OK;
                }
                catch (UnauthorizedAccessException)
                {
                    response.StatusCode = (int)HttpStatusCode.Forbidden;
                }
            }
        }