Exemplo n.º 1
0
        public void Configure(IApplicationBuilder app)
        {
            var config = new Configuration();
            config.AddEnvironmentVariables();
            config.AddJsonFile("config.json");
            config.AddJsonFile("config.dev.json", true);
            config.AddUserSecrets();

            var password = config.Get("password");

            if (config.Get<bool>("RecreateDatabase"))
            {
                var context = app.ApplicationServices.GetService<Models.BlogDataContext>();
                context.Database.EnsureDeleted();
                System.Threading.Thread.Sleep(2000);
                context.Database.EnsureCreated();
            }


            if (config.Get<bool>("debug"))
            {
                app.UseErrorPage();
                app.UseRuntimeInfoPage();
            }
            else
            {
                app.UseErrorHandler("/home/error");
            }

            app.UseMvc(routes => routes.MapRoute(
                "Default", "{controller=Home}/{action=Index}/{id?}"));

            app.UseFileServer();
        }
Exemplo n.º 2
0
        internal Settings(string projectDirectory, string settingsFile)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile(Path.Combine(projectDirectory, settingsFile));

            _configuration = configuration;
        }
Exemplo n.º 3
0
        public Startup(
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Startup>();

            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();
            var loggingConfiguration = configuration.GetSubKey("Logging");

            var serilog = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .Enrich.WithMachineName()
                .Enrich.WithProcessId()
                .Enrich.WithThreadId();

            if (string.Equals(hostingEnvironment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
            {
                serilog.WriteTo.ColoredConsole();
            }

            string elasticSearchConnectionString;
            if (loggingConfiguration.TryGet("ElasticSearch:Server", out elasticSearchConnectionString))
            {
                serilog.WriteTo.ElasticSearch(node: new Uri(elasticSearchConnectionString));
            }

            loggerFactory.AddSerilog(serilog);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Loads a json configuration file
        /// </summary>
        internal IConfiguration LoadConfigurationFile(IFile configFile)
        {
            var configuration = new Microsoft.Framework.ConfigurationModel.Configuration();

            configuration.AddJsonFile(configFile.FullPath);

            return(configuration);
        }
        public void Configure(IApplicationBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                services.AddAssembly(this);

                // Add EF services to the services container
                services.AddEntityFramework()
                    .AddSqlServer();

                // Configure DbContext
                services.SetupOptions<DbContextOptions>(options =>
                {
                    options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                });
                
                //// Add Identity services to the services container
                //services.AddIdentitySqlServer<ApplicationDbContext, ApplicationUser>()
                //    .AddAuthentication();

                // Add MVC services to the services container
                services.AddMvc();

                services.AddTransient(typeof(IService1), typeof(Service1));
            });

            // Enable Browser Link support
            //app.UseBrowserLink();

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login"),
            });

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default", 
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });
        }
        /// <summary>
        /// Creates and configures the application configuration, where key value pair settings are stored. See
        /// http://docs.asp.net/en/latest/fundamentals/configuration.html
        /// http://weblog.west-wind.com/posts/2015/Jun/03/Strongly-typed-AppSettings-Configuration-in-ASPNET-5
        /// </summary>
        /// <param name="applicationEnvironment">The location the application is running in</param>
        /// <param name="hostingEnvironment">The environment the application is running under. This can be Development, 
        /// Staging or Production by default.</param>
        /// <returns>A collection of key value pair settings.</returns>
        private static IConfiguration ConfigureConfiguration(
            IApplicationEnvironment applicationEnvironment,
            IHostingEnvironment hostingEnvironment)
        {
            // Beta 5 update
            //ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(
            //  applicationEnvironment.ApplicationBasePath);
            
            Configuration configuration = new Configuration();

            // Add configuration from the config.json file.
            configuration.AddJsonFile("config.json");

            // Add configuration from an optional config.development.json, config.staging.json or 
            // config.production.json file, depending on on the environment. These settings override the ones in 
            // the config.json file.
            configuration.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true);

            if (hostingEnvironment.IsEnvironment(EnvironmentName.Development))
            {
                // This reads the configuration keys from the secret store. This allows you to store connection strings
                // and other sensitive settings on your development environment, so you don't have to check them into
                // your source control provider. See http://go.microsoft.com/fwlink/?LinkID=532709 and
                // http://docs.asp.net/en/latest/security/app-secrets.html
                configuration.AddUserSecrets();
            }

            // Add configuration specific to the Development, Staging or Production environments. This config can 
            // be stored on the machine being deployed to or if you are using Azure, in the cloud. These settings 
            // override the ones in all of the above config files.
            // Note: To set environment variables for debugging navigate to:
            // Project Properties -> Debug Tab -> Environment Variables
            // Note: To get environment variables for the machine use the following command in PowerShell:
            // $env:[VARIABLE_NAME]
            // Note: To set environment variables for the machine use the following command in PowerShell:
            // $env:[VARIABLE_NAME]="[VARIABLE_VALUE]"
            // Note: Environment variables use a colon separator e.g. You can override the site title by creating a 
            // variable named AppSettings:SiteTitle. See 
            // http://docs.asp.net/en/latest/security/app-secrets.html
            configuration.AddEnvironmentVariables();

            // return configurationBuilder.Build();
            return configuration;
        }
        public static ApiConfigDetails Get(string configPath)
        {
            var apiConfig = new ApiConfigDetails();

            var config = new Configuration();
            config.AddJsonFile(configPath);

            apiConfig.ApiKey = config.Get("SimpleConfigServiceApiKey");
            apiConfig.UriFormat = config.Get("SimpleConfigServiceUriFormat");

            return apiConfig;
        }
Exemplo n.º 8
0
        public ConfigSetup()
        {
            // Make individual calls to AddXXX extension methods
            var config = new Configuration();
            config.AddJsonFile("config.json");
            config.AddEnvironmentVariables();

            // Fluent configuration
            var configFluent = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }
Exemplo n.º 9
0
        public void Configure(IBuilder app)
        {
            // Enable Browser Link support
            app.UseBrowserLink();

            // Setup configuration sources
            var configuration = new Configuration();

            //configuration.AddIniFile("config.ini");
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            //app.Run(async context =>
            //{
            //    await context.Response.WriteAsync(configuration.Get("Data:Configuration"));
            //});

            app.Run(async context =>
            {
                var asm = Assembly.Load(new AssemblyName("klr.host"));
                var assemblyVersion = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>();

                await context.Response.WriteAsync(assemblyVersion.InformationalVersion);
            });

            // Set up application services
            app.UseServices(services =>
            {
                // Add EF services to the services container
                services.AddEntityFramework().AddInMemoryStore();
                services.AddScoped<PersonContext>();

                // Add MVC services to the services container
                services.AddMvc();
            });

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default", 
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });
        }
Exemplo n.º 10
0
        public TestConfig()
        {
            _dataSource = Environment.GetEnvironmentVariable("PERFRUN_DataSource");
            RuntimeFlavor = getRuntimeFlavor();

            var resultsDirectory = Environment.GetEnvironmentVariable("PERFRUN_ResultsDirectory");
            ResultsDirectory = string.IsNullOrEmpty(resultsDirectory) ? ResultsDirectory : resultsDirectory;

            const string cliConfigPath = "LocalConfig.json";
            const string vsConfigPath = "..\\..\\LocalConfig.json";

            if (_dataSource != null)
            {
                RunPerfTests = true;
            }
            else
            {
                var configuration = new Configuration();
                if (File.Exists(cliConfigPath))
                {
                    configuration.AddJsonFile(cliConfigPath);
                }
                else if (File.Exists(vsConfigPath))
                {
                    configuration.AddJsonFile(vsConfigPath);
                }

                if (configuration.TryGet("Data:DefaultDataSource:DataSource", out _dataSource))
                {
                    _dataSource = _dataSource.Trim();
                    string runPerfTests;
                    configuration.TryGet("Data:RunPerfTests", out runPerfTests);
                    RunPerfTests = !string.IsNullOrEmpty(runPerfTests) && !runPerfTests.ToLower().Equals("false");
                }
            }
        }
Exemplo n.º 11
0
        public void Configure(IApplicationBuilder app)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapModuleRoute();

                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
Exemplo n.º 12
0
        public void Configure(IApplicationBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                // Add EF services to the services container
                services.AddEntityFramework()
                    .AddSqlServer();

                // Configure DbContext
                services.SetupOptions<DbContextOptions>(options =>
                {
                    options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                });

                // Add MVC services to the services container
                services.AddMvc();
            });

            // Enable Browser Link support
            app.UseBrowserLink();

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });
        }
Exemplo n.º 13
0
        public void LoadAndCombineKeyValuePairsFromDifferentConfigurationSources()
        {
            // Arrange
            var config = new Configuration();

            // Act
            config.AddIniFile(_iniConfigFilePath);
            config.AddJsonFile(_jsonConfigFilePath);
            config.AddXmlFile(_xmlConfigFilePath);
            var memConfigSrc = new MemoryConfigurationSource(_memConfigContent);

            config.Add(memConfigSrc);

            // Assert
            Assert.Equal(24, CountAllEntries(config));

            Assert.Equal("IniValue1", config.Get("IniKey1"));
            Assert.Equal("IniValue2", config.Get("IniKey2:IniKey3"));
            Assert.Equal("IniValue3", config.Get("IniKey2:IniKey4"));
            Assert.Equal("IniValue4", config.Get("IniKey2:IniKey5:IniKey6"));
            Assert.Equal("IniValue5", config.Get("CommonKey1:CommonKey2:IniKey7"));

            Assert.Equal("JsonValue1", config.Get("JsonKey1"));
            Assert.Equal("JsonValue2", config.Get("Json.Key2:JsonKey3"));
            Assert.Equal("JsonValue3", config.Get("Json.Key2:Json.Key4"));
            Assert.Equal("JsonValue4", config.Get("Json.Key2:JsonKey5:JsonKey6"));
            Assert.Equal("JsonValue5", config.Get("CommonKey1:CommonKey2:JsonKey7"));

            Assert.Equal("XmlValue1", config.Get("XmlKey1"));
            Assert.Equal("XmlValue2", config.Get("XmlKey2:XmlKey3"));
            Assert.Equal("XmlValue3", config.Get("XmlKey2:XmlKey4"));
            Assert.Equal("XmlValue4", config.Get("XmlKey2:XmlKey5:XmlKey6"));
            Assert.Equal("XmlValue5", config.Get("CommonKey1:CommonKey2:XmlKey7"));

            Assert.Equal("MemValue1", config["MemKey1"]);
            Assert.Equal("MemValue2", config["MemKey2:MemKey3"]);
            Assert.Equal("MemValue3", config["MemKey2:MemKey4"]);
            Assert.Equal("MemValue4", config["MemKey2:MemKey5:MemKey6"]);
            Assert.Equal("MemValue5", config["CommonKey1:CommonKey2:MemKey7"]);

            Assert.Equal("MemValue6", config["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
        }
Exemplo n.º 14
0
        public Startup()
        {
            var configuration = new Configuration()
                 .AddJsonFile("config.json");

            if (Program.Environment.OtherArgs != null)
            {
                configuration.AddCommandLine(Program.Environment.OtherArgs);
            }

            // Use the local omnisharp config if there's any in the root path
            if (File.Exists(Program.Environment.ConfigurationPath))
            {
                configuration.AddJsonFile(Program.Environment.ConfigurationPath);
            }

            configuration.AddEnvironmentVariables();

            Configuration = configuration;
        }
Exemplo n.º 15
0
        public void CanOverrideValuesWithNewConfigurationSource()
        {
            // Arrange
            var config = new Configuration();

            // Act & Assert
            config.AddIniFile(_iniConfigFilePath);
            Assert.Equal("IniValue6", config.Get("CommonKey1:CommonKey2:CommonKey3:CommonKey4"));

            config.AddJsonFile(_jsonConfigFilePath);
            Assert.Equal("JsonValue6", config.Get("CommonKey1:CommonKey2:CommonKey3:CommonKey4"));

            config.AddXmlFile(_xmlConfigFilePath);
            Assert.Equal("XmlValue6", config.Get("CommonKey1:CommonKey2:CommonKey3:CommonKey4"));

            var memConfigSrc = new MemoryConfigurationSource(_memConfigContent);

            config.Add(memConfigSrc);
            Assert.Equal("MemValue6", config.Get("CommonKey1:CommonKey2:CommonKey3:CommonKey4"));
        }
Exemplo n.º 16
0
		public void Configure(IApplicationBuilder app)
        {
			// For more information on how to configure your application, 
			// visit http://go.microsoft.com/fwlink/?LinkID=398940

			// Setup configuration sources
			Configuration configuration = new Configuration();

			configuration.AddJsonFile("config.json");
			configuration.AddIniFile("config.ini");
			// this cannot be accessed if XML fomratters were removed
			configuration.AddXmlFile("config.xml");
			configuration.AddEnvironmentVariables();

			string url_home = configuration.Get<string>("UrlLogo");

			app.UseMvc();
			app.UseWelcomePage();

			return;
		}
Exemplo n.º 17
0
        public void CanCommitChangeBackToLastConfigFile()
        {
            // Arrange
            var config = new Configuration();

            config.AddIniFile(_iniConfigFilePath);
            config.AddJsonFile(_jsonConfigFilePath);
            config.AddXmlFile(_xmlConfigFilePath);
            config.Set("CommonKey1:CommonKey2:CommonKey3:CommonKey4", "NewValue");

            // Act
            config.Commit();

            // Assert
            Assert.Equal(_iniConfigFileContent, File.ReadAllText(_iniConfigFilePath));

            Assert.Equal(_jsonConfigFileContent, File.ReadAllText(_jsonConfigFilePath));

            var updatedXmlContent = _xmlConfigFileContent.Replace("XmlValue6", "NewValue");

            Assert.Equal(updatedXmlContent, File.ReadAllText(_xmlConfigFilePath));
        }
Exemplo n.º 18
0
        public void CanSetValuesAndReloadValues()
        {
            // Arrange
            var config = new Configuration();

            config.AddIniFile(_iniConfigFilePath);
            config.AddJsonFile(_jsonConfigFilePath);
            config.AddXmlFile(_xmlConfigFilePath);

            // Act & Assert
            // Set value with Set() method
            config.Set("CommonKey1:CommonKey2:CommonKey3:CommonKey4", "NewValue");

            // All config sources must be updated
            foreach (var src in config)
            {
                Assert.Equal("NewValue",
                             (src as BaseConfigurationSource).Data["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
            }

            // Recover values by reloading
            config.Reload();
            Assert.Equal("XmlValue6", config.Get("CommonKey1:CommonKey2:CommonKey3:CommonKey4"));

            // Set value with indexer
            config["CommonKey1:CommonKey2:CommonKey3:CommonKey4"] = "NewValue";

            // All config sources must be updated
            foreach (var src in config)
            {
                Assert.Equal("NewValue",
                             (src as BaseConfigurationSource).Data["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
            }

            // Recover values by reloading
            config.Reload();
            Assert.Equal("XmlValue6", config["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
        }
Exemplo n.º 19
0
        public void Configure(IBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddJsonFile("Config.json");
            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                // Add MVC services to the services container
                services.AddMvc();
            });

            // Enable Browser Link support
            app.UseBrowserLink();

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "defaultWithArea",
                    template: "{controller}/{action}/{area}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });
        }
Exemplo n.º 20
0
        public void Configure(IBuilder app)
        {
            /* Adding IConfiguration as a service in the IoC to avoid instantiating Configuration again.
                 * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
                 * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            */
            var configuration = new Configuration();
            configuration.AddJsonFile("LocalConfig.json");
            configuration.AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.

            app.UseServices(services =>
            {
                // Add EF services to the services container
                services.AddEntityFramework()
                        .AddSqlServer();

                // Configure DbContext           
                services.SetupOptions<IdentityDbContextOptions>(options =>
                {
                    options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername");
                    options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword");
                    options.UseSqlServer(configuration.Get("Data:IdentityConnection:ConnectionString"));
                });

                // Add Identity services to the services container
                services.AddIdentitySqlServer<ApplicationDbContext, ApplicationUser>()
                        .AddAuthentication()
                        .SetupOptions(options =>
                        {
                            options.Password.RequireDigit = false;
                            options.Password.RequireLowercase = false;
                            options.Password.RequireUppercase = false;
                            options.Password.RequireNonLetterOrDigit = false;
                        });

                // Add MVC services to the services container
                services.AddMvc();
            });

            /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline.
             * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production.
             */
            app.UseErrorPage(ErrorPageOptions.ShowAll);

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login"),
                Notifications = new CookieAuthenticationNotifications
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(0))
                }
            });

            app.UseTwoFactorSignInCookies();

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });
            });

            //Populates the MusicStore sample data
            SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Loads a json configuration file
        /// </summary>
        internal IConfiguration LoadConfigurationFile(IFile configFile)
        {
            var configuration = new Microsoft.Framework.ConfigurationModel.Configuration();
            configuration.AddJsonFile(configFile.FullPath);

            return configuration;
        }
Exemplo n.º 22
0
        public void Configure(IBuilder app)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile("localconfig.json");

            // Custom Middleware
            //app.UseMiddleware<LoggingMiddleware>();

            app.UseStaticFiles();
            app.UseErrorPage();

            app.UseServices(services =>
            {
                services.AddEntityFramework().AddSqlServer();

                services.AddScoped<MessengerDataContext>();

                services.SetupOptions<MessengerDbContextOptions>(options =>
                    {
                        options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                    });

                // Identity
                /*
                services.AddIdentitySqlServer<MessengerDataContext, ApplicationUser>()
                    .AddAuthentication()
                    .SetupOptions(options =>
                    {
                        options.Password.RequireDigit = false;
                        options.Password.RequireLowercase = false;
                        options.Password.RequireUppercase = false;
                        options.Password.RequireNonLetterOrDigit = false;
                    });
                */

                services.AddMvc();
            });

            // Identity
            /*
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login"),
                Notifications = new CookieAuthenticationNotifications
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(0))
                }
            });

            app.UseTwoFactorSignInCookies();
            */

            app.UseMvc();

            // Custom Routing
            /*
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "Default",
                    template: "{controller=Messages}/{action=Index}/{id?}");
                });
            */
            app.UseWelcomePage();
        }
Exemplo n.º 23
0
        public void Configure(IBuilder app)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            app.UseStaticFiles();

            app.UseServices(services =>
            {
                services.AddMvc();

                var runningOnMono = Type.GetType("Mono.Runtime") != null;
                if (runningOnMono)
                {
                    services.AddEntityFramework().AddInMemoryStore();
                }
                else
                {
                    // Microsoft.Framework.DependencyInjection.SqlSer
                    services.AddEntityFramework().AddSqlServer();
                }

                services.AddScoped<BoomContext>();

                services.SetupOptions<DbContextOptions>(options =>
                {
                    if (runningOnMono)
                    {
                        options.UseInMemoryStore();
                    }
                    else
                    {
                        options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                    }
                }
                );
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "BacklogOptionsRoute",
                    template: "backlogs/{backlogId}/options/{id?}",
                    defaults: new { controller = "BacklogOptions" });

                routes.MapRoute(
                  name: "SurveyOptionsRoute",
                  template: "surveys/{surveyId}/options/{id?}",
                  defaults: new { controller = "SurveyOptions" });

                routes.MapRoute(
                  name: "SurveyParticipantsRoute",
                  template: "surveys/{surveyId}/participants",
                  defaults: new { controller = "SurveyParticipants" });

                routes.MapRoute(
                  name: "SurveyVotesRoute",
                  template: "surveys/{surveyId}/votes",
                  defaults: new { controller = "SurveyVotes" });

                routes.MapRoute(
                    name:  "ApiRoute", 
                    template:  "{controller}/{id?}");
            });

            DbHelper.DropDatabase("BoomDb");
            DbHelper.EnsureDbCreated(app);
        }
Exemplo n.º 24
0
        public void Configure(IBuilder app)
        {
            /* Adding IConfiguration as a service in the IoC to avoid instantiating Configuration again.
                 * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
                 * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            */
            var configuration = new Configuration();
            configuration.AddJsonFile("LocalConfig.json");
            configuration.AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.

	     /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline.
             * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production.
             */
            app.UseErrorPage(ErrorPageOptions.ShowAll);

            app.UseServices(services =>
            {
                //If this type is present - we're on mono
                var runningOnMono = Type.GetType("Mono.Runtime") != null;

                // Add EF services to the services container
                if (runningOnMono)
                {
                    services.AddEntityFramework()
                            .AddInMemoryStore();
                }
                else
                {
                    services.AddEntityFramework()
                            .AddSqlServer();
                }

                services.AddScoped<MusicStoreContext>();

                // Configure DbContext           
                services.SetupOptions<MusicStoreDbContextOptions>(options =>
                        {
                            options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername");
                            options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword");
                            if (runningOnMono)
                            {
                                options.UseInMemoryStore();
                            }
                            else
                            {
                                options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                            }
                        });

                // Add Identity services to the services container
                services.AddIdentitySqlServer<MusicStoreContext, ApplicationUser>()
                        .AddAuthentication();

                // Add MVC services to the services container
                services.AddMvc();
            });

            // Add static files to the request pipeline
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login"),
            });

            // Add MVC to the request pipeline
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });

            //Populates the MusicStore sample data
            SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
        }