public static void Main(string[] args = null) { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); if (args == null) { // Add defaultConfigurationStrings configurationBuilder.AddInMemoryCollection( DefaultConfigurationStrings); } else { configurationBuilder .AddInMemoryCollection(DefaultConfigurationStrings) .AddJsonFile("Config.json", true) // bool indicates file is optional // "EssentialDotNetConfiguration" is an optional prefix for all // environment configuration keys .AddEnvironmentVariables("EssentialDotNetConfiguration") .AddCommandLine( args, GetSwitchMappings(DefaultConfigurationStrings)); } Configuration = configurationBuilder.Build(); Console.WriteLine($"Hello {Configuration["Profile:UserName"]}"); ConsoleWindow consoleWindow = Configuration.Get<ConsoleWindow>("AppConfiguration:MainWindow"); ConsoleWindow.SetConsoleWindow(consoleWindow); }
/// <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="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(IHostingEnvironment hostingEnvironment) { IConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); // Add configuration from the config.json file. configurationBuilder.AddJsonFile("config.json"); // Add configuration from an optional config.development.json, config.staging.json or // config.production.json file, depending on the environment. These settings override the ones in the // config.json file. configurationBuilder.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true); // This reads the configuration keys from the secret store. This allows you to store connection strings // and other sensitive settings, 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 configurationBuilder.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 configurationBuilder.AddEnvironmentVariables(); return configurationBuilder.Build(); }
public void ConfigureConfigServerClientSettingsOptions_WithDefaults() { // Arrange var services = new ServiceCollection().AddOptions(); var environment = new HostingEnvironment(); // Act and Assert var builder = new ConfigurationBuilder().AddConfigServer(environment); var config = builder.Build(); services.Configure<ConfigServerClientSettingsOptions>(config); var service = services.BuildServiceProvider().GetService<IOptions<ConfigServerClientSettingsOptions>>(); Assert.NotNull(service); var options = service.Value; Assert.NotNull(options); ConfigServerTestHelpers.VerifyDefaults(options.Settings); Assert.Equal(ConfigServerClientSettings.DEFAULT_PROVIDER_ENABLED, options.Enabled); Assert.Equal(ConfigServerClientSettings.DEFAULT_FAILFAST, options.FailFast); Assert.Equal(ConfigServerClientSettings.DEFAULT_URI, options.Uri); Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, options.Environment); Assert.Equal(ConfigServerClientSettings.DEFAULT_CERTIFICATE_VALIDATION, options.ValidateCertificates); Assert.Null(options.Name); Assert.Null(options.Label); Assert.Null(options.Username); Assert.Null(options.Password); }
//<inheritdoc/> public IEnumerable<Tenant> GetEnabledTenants() { var fileProvider = _hostingEnvironment.ContentRootFileProvider; var tenantFolders = fileProvider .GetDirectoryContents("tenants") .Where(info => info.IsDirectory); foreach (var tenantFolder in tenantFolders) { var tenantFileName = "tenant.json"; var tenantDirectoryPath = Path.Combine("tenants", tenantFolder.Name); var tenantFilePath = Path.Combine(tenantDirectoryPath, tenantFileName); var tenantFileInfo = fileProvider.GetFileInfo(tenantFilePath); if (tenantFileInfo.Exists) { var builder = new ConfigurationBuilder(); builder.SetFileProvider(fileProvider); builder.AddJsonFile(tenantFilePath); var config = builder.Build(); var tenant = new Tenant { TenantId = tenantFolder.Name, Configuration = config, Identities = config.GetSection("Identities").GetChildren().Select(t => t.Value), Extensions = config.GetSection("Extensions").GetChildren().Select(t => t.Value), Path = tenantFolder.PhysicalPath }; yield return tenant; } } }
public static void Main(string[] args) { var configBuilder = new ConfigurationBuilder().AddCommandLine(args); Configuration = configBuilder.Build(); string configFile = Configuration["config"]; if (configFile != null) { configBuilder.AddJsonFile(configFile, optional: false); Configuration = configBuilder.Build(); } ConfigurationBinder.Bind(Configuration.GetSection("startup"), _startupOptions); ConfigurationBinder.Bind(Configuration.GetSection("security"), _securityOptions); _loggerFactory .AddDebug() .AddConsole(LogLevel.Trace) .AddProvider(new FileLoggerProvider(_startupOptions.Name)); _logger = _loggerFactory.CreateLogger<Program>(); if (_startupOptions.Name != null) { _logger.LogInformation(Resources.Info_BrokerName, _startupOptions.Name); } var tlsConfig = new TlsConfiguration(_logger, _securityOptions); var httpsOptions = tlsConfig.GetHttpsOptions(Configuration); Uri uri = GetServerUri(Configuration); try { CreateWebHost(httpsOptions).Run(); } catch(AggregateException ex) when (ex.IsPortInUseException()) { _logger.LogError(0, ex.InnerException, Resources.Error_ConfiguredPortNotAvailable, uri?.Port); } }
public Startup(IHostingEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); this.Configuration = builder.Build(); Configuration = builder.Build(); }
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); Configuration = builder.Build(); ApplicationBasePath = env.ContentRootPath; }
public Startup(IHostingEnvironment env) { // Ugly patch to allow create startup class on tests if (env != null) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); // TODO: override configuration depending on environment (Windows of Linux) builder.AddEnvironmentVariables(); LogginConfiguration = builder.Build().GetSection("Logging"); RemoteMediaConfiguration = builder.Build().Get<RemoteMediaConfiguration>(); } }
public static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json"); builder.AddEnvironmentVariables(); var config = builder.Build(); builder.AddEntityFramework(options => options.UseSqlServer(config["Data:DefaultConnection:ConnectionString"])); config = builder.Build(); Console.WriteLine("key1={0}", config["key1"]); Console.WriteLine("key2={0}", config["key2"]); Console.WriteLine("key3={0}", config["key3"]); }
public void ConfigureServices(IServiceCollection services) { // Configure swagger. For more details see e.g. // http://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/ services.AddSwaggerGen(); services.ConfigureSwaggerDocument(options => options.SingleApiVersion( new Info { Version = "v1", Title = "Demo" })); // Use the new configuration model here. Note the use of // different configuration sources (json, env. variables, // middleware-specific configuration). services.AddOptions(); var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddApplicationInsightsSettings(developerMode: true); var configuration = builder.Build(); // Publish options read from configuration file. With that, // controllers can use ASP.NET DI to get options (see // BooksController). services.Configure<BooksDemoDataOptions>( configuration.GetSection("booksDemoDataOptions")); // Add AI configuration services.AddApplicationInsightsTelemetry(configuration); // Publish singleton for name generator services.AddSingleton(typeof(INameGenerator), typeof(NameGenerator)); // Configure middlewares (CORS and MVC) services.AddCors(); services.AddMvc(); }
public static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); IConfigurationRoot Configuration = builder.Build(); string message = string.Empty; using (SqlConnection conn = new SqlConnection(Configuration["Data:DefaultConnection:ConnectionString"])) { try { using (SqlCommand cmd = new SqlCommand("SELECT @@version;", conn)) { conn.Open(); var result = cmd.ExecuteScalar(); if (result != null) message = result.ToString(); conn.Close(); } } catch(Exception ex) { message = ex.Message; } finally { conn.Close(); } } Console.WriteLine("Connect to SQL Server: \n\r" + message); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json"); Configuration = builder.Build(); }
public Startup() { var builder = new ConfigurationBuilder() // You can write a AddXmlFile extension method yourself. .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); }
static void Main(string[] args) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("app.json", optional: true, reloadOnChange: false) .AddEnvironmentVariables() .AddCommandLine(args); configuration = builder.Build(); var configObj = GetConfigurationObject(configuration); foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.template", SearchOption.AllDirectories)) { var template = Template.Parse(File.ReadAllText(file)); var output = template.Render(Hash.FromDictionary(configObj)); using (var fs = new FileStream(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), FileMode.Create, FileAccess.Write)) { using (var writter = new StreamWriter(fs)) { writter.Write(output); } } } }
public StartupAzureDev(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddEnvironmentVariables(); Configuration = builder.Build(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public Startup(IHostingEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); AppSetting.AppSettings["hostdir"] = env.ContentRootPath; HostingEnvironment.SetRootPath(env.ContentRootPath); Phyah.Configuration.ConfigurationStartup.RootConfigurePath = System.IO.Path.Combine(env.ContentRootPath, "setting.json"); Phyah.Configuration.ConfigurationManager.Manager.Configure(); Phyah.Web.Initialization.Initialize(); Phyah.Web.Initialization.InitializePipeline(new SynchronizationPipeline( (ex) => { var resp = AccessorContext.DefaultContext.Get <HttpContext>().Response; resp.Clear(); resp.WriteAsync(ex.ToString()); }) .AddLast("begin", () => { var context = AccessorContext.DefaultContext.Get <HttpContext>(); var req = context.Request; //context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); string host = req.Host.Host; if (req.Headers.ContainsKey("request-host")) { host = req.Headers["request-host"].ToString(); } else if (req.Headers.ContainsKey("origin")) { host = req.Headers["origin"].ToString(); } AccessorContext.DefaultContext.Set <string>("host", host); }) .AddLast("initialized", new InitializedHandler()) .AddLast("pathreset", new PathResetHandler()) .AddLast("process", new ProcessHandler()) ); TypeContainer.Container.Inject(typeof(ICardService), typeof(CardService)); TypeContainer.Container.Inject(typeof(IArticleService), typeof(ArticleService)); TypeContainer.Container.Inject(typeof(ICardService), typeof(CardService)); TypeContainer.Container.Inject(typeof(IPartialViewService), typeof(PartialViewService)); TypeContainer.Container.Inject(typeof(IMenuService), typeof(MenuService)); TypeContainer.Container.Inject(typeof(IRoleService), typeof(RoleService)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(CardsBehavior)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(ArticleBehavior)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(ContactorBehavior)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(PartialViewBehavior)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(MenuBehavior)); Phyah.Web.BehaviorFactory.Factory.Cache(typeof(RoleBehavior)); }
public ConfigurationResult Build(Action <IConfigurationBuilder> additionalSetup = null) { try { var configBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddEnvironmentVariables("OMNISHARP_"); if (_environment.AdditionalArguments?.Length > 0) { configBuilder.AddCommandLine(_environment.AdditionalArguments); } // Use the global omnisharp config if there's any in the shared path configBuilder.CreateAndAddGlobalOptionsFile(_environment); // Use the local omnisharp config if there's any in the root path configBuilder.AddJsonFile( new PhysicalFileProvider(_environment.TargetDirectory).WrapForPolling(), Constants.OptionsFile, optional: true, reloadOnChange: true); // bootstrap additional host configuration at the end additionalSetup?.Invoke(configBuilder); var config = configBuilder.Build(); return(new ConfigurationResult(config)); } catch (Exception ex) { return(new ConfigurationResult(ex)); } }
public Startup(IHostingEnvironment env) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("version.json") .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } else if (env.IsStaging() || env.IsProduction()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: false); } Configuration = builder.Build(); Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json }
private static IWebHost BuildWebHost(string[] args) { var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Development.json", true, false) .AddJsonFile("appsettings.Production.json", true, false) .AddEnvironmentVariables() .AddCommandLine(args); if (args != null) { configurationBuilder.AddCommandLine(args); } var hostingconfig = configurationBuilder.Build(); var url = hostingconfig[addressKey] ?? defaultAddress; return(WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration(config => { config.AddJsonFile("appsettings.json", false, true); }) .UseConfiguration(hostingconfig) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls(url) .UseStartup <Startup>() .Build()); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); var configuration = builder.Build(); optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]); }
public DependencyInjectionFixture() { var enviromentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Test"; var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{enviromentName}.json", true); var configuration = builder.Build(); var services = new ServiceCollection(); services.AddSingleton(p => configuration); services.AddLogging(); services.AddOptions(); services.AddTransient <ITenant <TenantReadModel> >(provider => new TenantValue <TenantReadModel>(new TenantReadModel { Id = Data.Constants.Tenant.Test, Slug = "Test", Name = "Test" })); services.KickStart(config => config .IncludeAssemblyFor <InstructorIQContext>() .IncludeAssemblyFor <DependencyInjectionFixture>() .Data(ConfigurationServiceModule.ConfigurationKey, configuration) .Data("hostProcess", "test") .UseStartupTask() ); }
private void ContinueStartup() { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Configuration = builder.Build(); var services = new ServiceCollection(); services.AddOptions(); services.Configure <ConfigWrapper>(Configuration); services.AddSingleton <IGraphService, GraphService>(); services.AddSingleton <IHueService, HueService>(); services.AddSingleton <LIFXService, LIFXService>(); services.AddSingleton <IYeelightService, YeelightService>(); services.AddSingleton <ICustomApiService, CustomApiService>(); services.AddSingleton <LIFXOAuthHelper, LIFXOAuthHelper>(); services.AddSingleton <MainWindow>(); DiagnosticsClient.Initialize(); ServiceProvider = services.BuildServiceProvider(); var mainWindow = ServiceProvider.GetRequiredService <MainWindow>(); mainWindow.Show(); }
public Startup() { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appSettings.json"); Configuration = builder.Build(); }
private BloggingContext Create(string basePath, string environmentName) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(basePath) .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); IConfiguration Configuration = builder.Build(); var connstr = Configuration["DBInfo:ConnectionString"]; connstr = connstr.Replace("database=mydb", $"database={DbName}"); if (String.IsNullOrWhiteSpace(connstr) == true) { throw new InvalidOperationException( $"Could not find a connection string named '({DbName})'."); } else { return(Create(connstr)); } }
protected override (Stream clientOutput, Stream serverInput) SetupServer() { var clientPipe = new Pipe(TestOptions.DefaultPipeOptions); var serverPipe = new Pipe(TestOptions.DefaultPipeOptions); _host = new LanguageServerHost( clientPipe.Reader.AsStream(), serverPipe.Writer.AsStream(), options => options .ConfigureLogging(x => x.AddLanguageProtocolLogging()) .WithServices(services => { services.AddSingleton(_loggerFactory); }) .OnInitialize((server, request, token) => { var configBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddConfiguration(server.Configuration.GetSection("csharp")) .AddConfiguration(server.Configuration.GetSection("omnisharp")); if (_setupConfiguration != null) configBuilder.AddConfiguration(_setupConfiguration); var config = configBuilder.Build(); OmniSharpTestHost = CreateOmniSharpHost(config, new LanguageServerEventEmitter(server)); var handlers = LanguageServerHost.ConfigureCompositionHost(server, OmniSharpTestHost.CompositionHost); _host.UnderTest(OmniSharpTestHost.ServiceProvider, OmniSharpTestHost.CompositionHost); LanguageServerHost.RegisterHandlers(server, OmniSharpTestHost.CompositionHost, handlers); return Task.CompletedTask; }), CancellationTokenSource.CreateLinkedTokenSource(CancellationToken) ); startUpTask = _host.Start(); return (serverPipe.Reader.AsStream(), clientPipe.Writer.AsStream()); }
public static void Main(string[] args) { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json"); var configuration = configBuilder.Build(); var hostBuilder = new WebHostBuilder(); // set urls and environment hostBuilder .UseUrls(configuration["urls"]) .UseEnvironment(configuration["environment"]); // set other common things hostBuilder .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>(); var host = hostBuilder.Build(); host.Run(); }
public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("Config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); }
/// <summary> /// Gets a connection from a ConfigName. This will search in System.Configuration.ConfigurationManager.ConnectionStrings /// and System.Configuration.ConfigurationManager.AppSettings for any valid Entity Framework or Sql Server connection string /// </summary> /// <param name="configName"></param> /// <param name="defaultProviderFactory">The default factory if none is specified</param> /// <returns></returns> public static DbConnection GetConnectionFromConfig(string configName, DbProviderFactory defaultProviderFactory) { #if !NETSTD if (System.Configuration.ConfigurationManager.ConnectionStrings[configName] != null) { return(GetConnectionFromEFString(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString, defaultProviderFactory)); } else if (System.Configuration.ConfigurationManager.AppSettings[configName] != null) { return(GetConnectionFromEFString(System.Configuration.ConfigurationManager.AppSettings[configName], defaultProviderFactory)); } #else var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, false); var Configuration = builder.Build(); var value = Configuration["ConnectionStrings:" + configName]; if (!string.IsNullOrEmpty(value)) { return(GetConnectionFromEFString(value, defaultProviderFactory)); } #endif return(GetConnectionFromEnvironment(configName, true, defaultProviderFactory) !); }
IEnumerable<ShellSettings> IShellSettingsManager.LoadSettings() { var shellSettings = new List<ShellSettings>(); foreach (var tenant in _appDataFolder.ListDirectories(_optionsAccessor.Value.Location)) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("ShellSettings found in '{0}', attempting to load.", tenant.Name); } var configurationContainer = new ConfigurationBuilder() .SetBasePath(_appDataFolder.RootPath) .AddJsonFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "json")), true) .AddXmlFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "xml")), true) .AddYamlFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "txt")), false); var config = configurationContainer.Build(); var shellSetting = ShellSettingsSerializer.ParseSettings(config); shellSettings.Add(shellSetting); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Loaded ShellSettings for tenant '{0}'", shellSetting.Name); } } return shellSettings; }
private static DungeonParameters GatherParameters() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json") .AddEnvironmentVariables(); var configuration = builder.Build(); return new DungeonParameters { Width = configuration.GetValue<int>("Map:Width"), Height = configuration.GetValue<int>("Map:Height"), CellSparseFactor = configuration.GetValue<int>("Map:CellSparseFactor"), DeadEndSparseFactor = configuration.GetValue<int>("Map:DeadEndSparseFactor"), TwistFactor = configuration.GetValue<int>("Map:TwistFactor"), RoomParameters = new RoomParameters { Count = configuration.GetValue<int>("Map:Room:Count"), MinWidth = configuration.GetValue<int>("Map:Room:MinWidth"), MaxWidth = configuration.GetValue<int>("Map:Room:MaxWidth"), MinHeight = configuration.GetValue<int>("Map:Room:MinHeight"), MaxHeight = configuration.GetValue<int>("Map:Room:MaxHeight") } }; }
public static void Test() { Settings_t env = new Settings_t(); Microsoft.Extensions.Configuration.IConfigurationBuilder builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ProjectRootPath) // .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) // Microsoft.Extensions.Configuration.Json.dll // .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) // .AddJsonFile("settings.json") // .AddYamlFile("settings.yml", optional: false) // Microsoft.Extensions.Configuration.Yaml.dll .AddRegistryKey(@"HKEY_CURRENT_USER\Software\COR\All", "/etc/COR/All") .AddRegistryKey(@"HKEY_CURRENT_USER\Software\COR\SchemaPorter", "/etc/COR/SchemaPorter") // .AddEnvironmentVariables() // Microsoft.Extensions.Configuration.EnvironmentVariables.dll ; Microsoft.Extensions.Configuration.IConfigurationRoot Configuration = builder.Build(); // IConfigurationSection thisSection = Configuration.GetSection("AppSettings:token"); // thisSection.Key // thisSection.Value; // services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig")); // Just the value of the token // string configValue = Configuration["AppSettings:token"]; // https://stackoverflow.com/questions/31453495/how-to-read-appsettings-values-from-config-json-in-asp-net-core Newtonsoft.Json.Linq.JObject conf = GetConfigAsJObject(Configuration); string configValues = Newtonsoft.Json.JsonConvert.SerializeObject(conf, Newtonsoft.Json.Formatting.Indented); System.Console.WriteLine(configValues); } // End Sub Test
IEnumerable<ShellSettings> IShellSettingsManager.LoadSettings() { var shellSettings = new List<ShellSettings>(); foreach (var tenant in _appDataFolder.ListDirectories("Sites")) { _logger.LogInformation("ShellSettings found in '{0}', attempting to load.", tenant.Name); var configurationContainer = new ConfigurationBuilder() .AddJsonFile(_appDataFolder.Combine(tenant.PhysicalPath, string.Format(SettingsFileNameFormat, "json")), true) .AddXmlFile(_appDataFolder.Combine(tenant.PhysicalPath, string.Format(SettingsFileNameFormat, "xml")), true) .AddYamlFile(_appDataFolder.Combine(tenant.PhysicalPath, string.Format(SettingsFileNameFormat, "txt")), false); var config = configurationContainer.Build(); var shellSetting = new ShellSettings(config); shellSettings.Add(shellSetting); _logger.LogInformation("Loaded ShellSettings for tenant '{0}'", shellSetting.Name); } return shellSettings; }
public int Main(string[] args) { var builder = new ConfigurationBuilder(); //builder.Add(new JsonConfigurationSource("config.json")); builder.AddJsonFile("config.json"); var config = builder.Build(); var webjobsConnectionString = config["Data:AzureWebJobsStorage:ConnectionString"]; var dbConnectionString = config["Data:DefaultConnection:ConnectionString"]; if (string.IsNullOrWhiteSpace(webjobsConnectionString)) { Console.WriteLine("The configuration value for Azure Web Jobs Connection String is missing."); return 10; } if (string.IsNullOrWhiteSpace(dbConnectionString)) { Console.WriteLine("The configuration value for Database Connection String is missing."); return 10; } var jobHostConfig = new JobHostConfiguration(webjobsConnectionString); var host = new JobHost(jobHostConfig); host.RunAndBlock(); return 0; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { //Setting up configuration builder var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddEnvironmentVariables(); if (!env.IsProduction()) { builder.AddUserSecrets(); } else { } Configuration = builder.Build(); //Setting up configuration if (!env.IsProduction()) { var confConnectString = Configuration.GetSection("Data:DefaultConnection:ConnectionString"); confConnectString.Value = @"Server=(localdb)\mssqllocaldb;Database=GetHabitsAspNet5;Trusted_Connection=True;"; var identityConnection = Configuration.GetSection("Data:IdentityConnection:ConnectionString"); identityConnection.Value = @"Server=(localdb)\mssqllocaldb;Database=GetHabitsIdentity;Trusted_Connection=True;"; } else { } }
public static void Main(string[] args) { var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Development.json", true, false) .AddJsonFile("appsettings.Production.json", true, false) .AddEnvironmentVariables() .AddCommandLine(args); if (args != null) { configurationBuilder.AddCommandLine(args); } var hostingconfig = configurationBuilder.Build(); var url = hostingconfig[addressKey] ?? defaultAddress; IWebHostBuilder builder = new WebHostBuilder(); builder.ConfigureServices(s => { s.AddSingleton(builder); }); builder.UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(hostingconfig) .UseIISIntegration() .UseUrls(url) .UseStartup <Startup>(); var host = builder.Build(); host.Run(); }
public Startup( IHostingEnvironment env, IApplicationEnvironment appEnv) { _env = env; // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) // standard config file .AddJsonFile("config.json") // environment specific config.<environment>.json file .AddJsonFile($"config.{env.EnvironmentName}.json", true /* override if exists */) // standard Windows environment variables .AddEnvironmentVariables(); if (env.IsDevelopment()) { // this one adds not using directive to keep it secret, only a dnx reference // the focus is not on Secrets but on User, so these are User specific settings // we can also make it available only for developers builder.AddUserSecrets(); } Configuration = builder.Build(); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnvironment) { _appEnvironment = appEnvironment; _hostingEnvironment = env; var RollingPath = Path.Combine(appEnvironment.ApplicationBasePath, "logs/myapp-{Date}.txt"); Log.Logger = new LoggerConfiguration() .WriteTo.RollingFile(RollingPath) .CreateLogger(); Log.Information("Ah, there you are!"); // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile("appsettings-filters.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); // Initialize the global configuration static GlobalConfigurationRoot.Configuration = Configuration; }
/// <summary> /// This is annoying cos it should be in the constructor but we need to set up the file before calling startup so its a step. /// </summary> public void GivenOcelotIsRunning(OcelotPipelineConfiguration ocelotPipelineConfig) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile("ocelot.json", false, false) .AddEnvironmentVariables(); var configuration = builder.Build(); _webHostBuilder = new WebHostBuilder(); _webHostBuilder.ConfigureServices(s => { s.AddSingleton(_webHostBuilder); }); _ocelotServer = new TestServer(_webHostBuilder .UseConfiguration(configuration) .ConfigureServices(s => { s.AddOcelot(configuration); }) .ConfigureLogging(l => { l.AddConsole(); l.AddDebug(); }) .Configure(a => { a.UseOcelot(ocelotPipelineConfig).Wait(); })); _ocelotClient = _ocelotServer.CreateClient(); }
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); Configuration = builder.Build(); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development")) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } // this file name is ignored by gitignore // so you can create it and use on your local dev machine // remember last config source added wins if it has the same settings builder.AddJsonFile("appsettings.local.overrides.json", optional: true); // most common use of environment variables would be in azure hosting // since it is added last anything in env vars would trump the same setting in previous config sources // so no risk of messing up settings if deploying a new version to azure builder.AddEnvironmentVariables(); Configuration = builder.Build(); //env.MapPath appBasePath = appEnv.ApplicationBasePath; }
private static IConfigurationRoot GetConfiguration(IDictionary <string, string> data) { var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); configurationBuilder.AddInMemoryCollection(data); return(configurationBuilder.Build()); }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder().AddEnvironmentVariables(); Configuration = builder.Build(); }
public void Run() { try { Console.WriteLine("Reading Configuration"); var builder = new ConfigurationBuilder() .SetBasePath(PlatformServices.Default.Application.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); _config = builder.Build(); _ctx = new OldWilderContext(_config); _newCtx = new WilderContext(_config); _repo = new WilderRepository(_config, _newCtx); Console.WriteLine("Migrating Stories"); MigrateStories(); //TODO More migration } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.ReadKey(); } }
private void OnStartup(object sender, StartupEventArgs e) { SetAddRemoveProgramsIcon(); var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Configuration = builder.Build(); var services = new ServiceCollection(); services.AddOptions(); services.Configure <ConfigWrapper>(Configuration); services.AddSingleton <IGraphService, GraphService>(); services.AddSingleton <IHueService, HueService>(); services.AddSingleton <MainWindow>(); DiagnosticsClient.Initialize(); ServiceProvider = services.BuildServiceProvider(); var mainWindow = ServiceProvider.GetRequiredService <MainWindow>(); mainWindow.Show(); }
// ReSharper disable once UnusedParameter.Local public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables("Dorothy:"); Configuration = builder.Build(); }
public void Configure(IApplicationBuilder app) { var builder = new ConfigurationBuilder(); builder.Add(new MemoryConfigurationProvider { {"MySettings:RetryCount", "42"}, {"MySettings:DefaultAdBlock", "House"}, {"MySettings:AdBlock:House:ProductCode", "123"}, {"MySettings:AdBlock:House:Origin", "blob-456"}, {"MySettings:AdBlock:Contoso:ProductCode", "contoso2014"}, {"MySettings:AdBlock:Contoso:Origin", "sql-789"}, }); var config = builder.Build(); var mySettings = new MySettings(); mySettings.Read(config.GetSection("MySettings")); app.Run(async ctx => { ctx.Response.ContentType = "text/plain"; await ctx.Response.WriteAsync(string.Format("Retry Count {0}\r\n", mySettings.RetryCount)); await ctx.Response.WriteAsync(string.Format("Default Ad Block {0}\r\n", mySettings.DefaultAdBlock)); foreach (var adBlock in mySettings.AdBlocks.Values) { await ctx.Response.WriteAsync(string.Format( "Ad Block {0} Origin {1} Product Code {2}\r\n", adBlock.Name, adBlock.Origin, adBlock.ProductCode)); } }); }
/// <summary> /// initialize cache /// </summary> private void InitializeCache() { //Name of cache to connect with // Providers must be deployed with that cache //Name of provider to be deployed //PersistenceReadThru , PersistenceWriteThru and PersistenceStartupLoadewr var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); string cacheId = configuration["NCache:cacheName"]; if (String.IsNullOrEmpty(cacheId)) { Console.WriteLine("The CacheID cannot be null or empty."); return; } _cacheId = cacheId; // Initialize an instance of the cache to begin performing operations: _cache = CacheManager.GetCache(cacheId); // Print output on console Console.WriteLine(string.Format("\nCache '{0}' is initialized.", cacheId)); }
public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); #if DEBUG URLS.Api_url = "http://localhost:58517/"; URLS.Html_url = "http://localhost:7079/oauth.html"; URLS.Idt_url = "http://localhost:58058/"; URLS.Mvc_url = "http://localhost:7079/signin-oidc"; #endif #if RELEASE URLS.Api_url = "http://it4govwebapi.azurewebsites.net/"; URLS.Html_url = "http://it4govwebapp.azurewebsites.net/oauth.html"; URLS.Idt_url = "http://it4govidentityserver.azurewebsites.net"; URLS.Mvc_url = "http://it4govwebapp.azurewebsites.net/signin-oidc"; #endif // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); builder.AddEnvironmentVariables(); Configuration = builder.Build().ReloadOnChanged("appsettings.json"); }
public Startup(IHostingEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile($"setup.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets <Startup>(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); var threadCountInString = Configuration.GetSection("ThreadCount").Value; var threadCount = threadCountInString != null?Convert.ToInt32(threadCountInString) : 200; ThreadPool.SetMinThreads(threadCount, threadCount); Env = env; }
private static IConfigurationRoot CreateConfiguration(IEnumerable <KeyValuePair <string, string> > configurationData, IDotNetCliService dotNetCliService) { var info = dotNetCliService.GetInfo(); var msbuildSdksPath = Path.Combine(info.BasePath, "Sdks"); var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.AddInMemoryCollection(configurationData); // We need to set the "UseLegacySdkResolver" for tests because // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs // that we install locally in the ".dotnet" directory. // This property will cause the MSBuild project loader to set the // MSBuildSDKsPath environment variable to the correct path "Sdks" folder // within the appropriate .NET Core SDK. var msbuildProperties = new Dictionary <string, string>() { [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true", [$"MSBuild:{nameof(MSBuildOptions.MSBuildSDKsPath)}"] = msbuildSdksPath }; builder.AddInMemoryCollection(msbuildProperties); return(builder.Build()); }
public Startup(IHostingEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddEnvironmentVariables(); Configuration = builder.Build(); }
public IConfiguration Build() { Validate(); IConfigurationBuilder builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.AddJsonFile(Path.Combine(_filePath, _fileName)); return(builder.Build()); }
/// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public Startup(IConfiguration configuration) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
public Program() { // Set up configuration sources. var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("cache.json"); this.Configuration = builder.Build(); }
public CoreAppConfiguration(IHostingEnvironment env) { var cfgBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("config.json"); var cfg = cfgBuilder.Build(); _homeGreeting = cfg["Greeting"]; }
/// <summary> /// Loads the configuration from settings json. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="sectionName">Name of the section.</param> protected void LoadFromSettingsJson(string filePath, string sectionName) { IConfigurationBuilder builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile(filePath); IConfigurationRoot configRoot = builder.Build(); LoadFromConfiguration(configRoot, sectionName); }
public Startup(IHostingEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.SetBasePath(env.ContentRootPath) .AddJsonFile("configuration.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); }
static ConfigurationManager() { IConfigurationBuilder builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); //.AddJsonFile("appsettings." + environmentName + ".json", optional: false, reloadOnChange: true); _Configuration = builder.Build(); }
public Startup(IConfiguration configuration) { var environment = "prod"; var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.{environment}.json", false, true); Configuration = builder.Build(); }