· 6 years ago · Feb 08, 2019, 07:48 PM
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System;
5using System.Linq;
6using Microsoft.AspNetCore.Builder;
7using Microsoft.AspNetCore.Hosting;
8using Microsoft.Bot.Builder;
9using Microsoft.Bot.Builder.Integration;
10using Microsoft.Bot.Builder.Integration.AspNet.Core;
11using Microsoft.Bot.Configuration;
12using Microsoft.Bot.Connector.Authentication;
13using Microsoft.Extensions.Configuration;
14using Microsoft.Extensions.DependencyInjection;
15using Microsoft.Extensions.Logging;
16
17namespace WeatherBotv4
18{
19 public class Startup
20 {
21 private ILoggerFactory _loggerFactory;
22 private readonly bool _isProduction;
23
24 public Startup(IHostingEnvironment env)
25 {
26 _isProduction = env.IsProduction();
27 var builder = new ConfigurationBuilder()
28 .SetBasePath(env.ContentRootPath)
29 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
30 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
31 .AddEnvironmentVariables();
32
33 Configuration = builder.Build();
34 }
35
36 public IConfiguration Configuration { get; }
37
38 public void ConfigureServices(IServiceCollection services)
39 {
40 var secretKey = Configuration.GetSection("botFileSecret")?.Value;
41 var botFilePath = Configuration.GetSection("botFilePath")?.Value;
42
43 var botConfig = BotConfiguration.Load(botFilePath ?? @".\WeatherBotv4.bot", secretKey);
44 services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
45
46 var connectedServices = new Services.BotService(botConfig);
47 services.AddSingleton(sp => connectedServices);
48 services.AddSingleton(sp => botConfig);
49
50 services.AddBot<WeatherBotv4Bot>(options =>
51 {
52 var environment = _isProduction ? "production" : "development";
53 var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment);
54
55 if (!(service is EndpointService endpointService))
56 throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
57
58 options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
59
60 ILogger logger = _loggerFactory.CreateLogger<WeatherBotv4Bot>();
61
62 options.OnTurnError = async (context, exception) =>
63 {
64 logger.LogError($"Exception caught : {exception}");
65 await context.SendActivityAsync("Sorry, it looks like something went wrong.");
66 };
67
68 IStorage dataStore = new MemoryStorage();
69
70 var conversationState = new ConversationState(dataStore);
71 options.State.Add(conversationState);
72 });
73 }
74
75 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
76 {
77 _loggerFactory = loggerFactory;
78
79 app.UseDefaultFiles()
80 .UseStaticFiles()
81 .UseBotFramework();
82 }
83 }
84}