当前位置: 首页>>代码示例>>C#>>正文


C# Configuration.Get方法代码示例

本文整理汇总了C#中Microsoft.Framework.ConfigurationModel.Configuration.Get方法的典型用法代码示例。如果您正苦于以下问题:C# Configuration.Get方法的具体用法?C# Configuration.Get怎么用?C# Configuration.Get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Framework.ConfigurationModel.Configuration的用法示例。


在下文中一共展示了Configuration.Get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ConfigureDataContext

        public static IServiceCollection ConfigureDataContext(this IServiceCollection services, Configuration configuration)
        {
            //If this type is present - we're on mono 
            var runningOnMono = Type.GetType("Mono.Runtime") != null;

            services.AddEntityFramework(configuration)
                .AddStore(runningOnMono)
                .AddDbContext<MyShuttleContext>(options =>
                {
                    if (runningOnMono)
                    {
                        options.UseInMemoryStore();
                    }
                    else
                    {
                        options.UseSqlServer(configuration.Get("EntityFramework:MyShuttleContext:ConnectionstringKey"));
                    }
                });

            // Configure DbContext
            services.Configure<MyShuttleDbContextOptions>(options =>
            {
                options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername");
                options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword");
            });

            return services;
        }
开发者ID:sriramdasbalaji,项目名称:My-Shuttle-Biz,代码行数:28,代码来源:Startup.DataContext.cs

示例2: Configure

        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();
        }
开发者ID:lukehammer,项目名称:AspNetBlog,代码行数:34,代码来源:Startup.cs

示例3: foreach

        IEnumerable<ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var filePaths = _appDataFolder
                .ListDirectories("Sites")
                .SelectMany(path => _appDataFolder.ListFiles(path))
                .Where(path => {
                    var filePathName = Path.GetFileName(path);

                    return _settingFileNameExtensions.Any(p =>
                        string.Equals(filePathName, string.Format(_settingsFileNameFormat, p), StringComparison.OrdinalIgnoreCase)
                    );
                });

            List<ShellSettings> shellSettings = new List<ShellSettings>();

            foreach (var filePath in filePaths) {
                IConfigurationSourceRoot configurationContainer = null;

                var extension = Path.GetExtension(filePath);

                switch (extension) {
                    case ".json":
                        configurationContainer = new Microsoft.Framework.ConfigurationModel.Configuration()
                            .AddJsonFile(filePath);
                        break;
                    case ".xml":
                        configurationContainer = new Microsoft.Framework.ConfigurationModel.Configuration()
                            .AddXmlFile(filePath);
                        break;
                    case ".ini":
                        configurationContainer = new Microsoft.Framework.ConfigurationModel.Configuration()
                            .AddIniFile(filePath);
                        break;
                    case ".txt":
                        configurationContainer = new Microsoft.Framework.ConfigurationModel.Configuration()
                            .Add(new DefaultFileConfigurationSource(_appDataFolder, filePath));
                        break;
                }

                if (configurationContainer != null) {
                    var shellSetting = new ShellSettings {
                        Name = configurationContainer.Get<string>("Name"),
                        DataConnectionString = configurationContainer.Get<string>("DataConnectionString"),
                        DataProvider = configurationContainer.Get<string>("DataProvider"),
                        DataTablePrefix = configurationContainer.Get<string>("DataTablePrefix"),
                        RequestUrlHost = configurationContainer.Get<string>("RequestUrlHost"),
                        RequestUrlPrefix = configurationContainer.Get<string>("RequestUrlPrefix")
                    };

                    TenantState state;
                    shellSetting.State = Enum.TryParse(configurationContainer.Get<string>("State"), true, out state) ? state : TenantState.Uninitialized;

                    shellSettings.Add(shellSetting);
                }
            }

            return shellSettings;
        }
开发者ID:yonglehou,项目名称:Brochard,代码行数:58,代码来源:ShellSettingsManager.cs

示例4: Get

        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;
        }
开发者ID:antonyfrancis,项目名称:simple-config-service,代码行数:12,代码来源:ConfigReader.cs

示例5: CreateDefaultUser

        /// <summary>
        /// Creates a store manager user who can manage the inventory.
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        private static async Task CreateDefaultUser(IServiceProvider serviceProvider)
        {
            var configuration = new Configuration()
                        .AddJsonFile("config.json")
                        .AddEnvironmentVariables();

            var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();

            var user = await userManager.FindByNameAsync(configuration.Get<string>(defaultAdminUserName));
            if (user == null)
            {
                user = new ApplicationUser { UserName = configuration.Get<string>(defaultAdminUserName), CarrierId = _DefaultCarrierId };
                await userManager.CreateAsync(user, configuration.Get<string>(defaultAdminPassword));
                await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
            }
        }
开发者ID:EmiiFont,项目名称:MyShuttle_RC,代码行数:21,代码来源:MyShuttleDataInitializer.cs

示例6: OnConfiguring

 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     var config = new Configuration()
         .AddJsonFile("config.json");
     var constr = config.Get("Data:DefaultConnection:ConnectionString");
     options.UseSqlServer(constr);
 }
开发者ID:LeoLcy,项目名称:MVC6Recipes,代码行数:7,代码来源:ArtistContext.cs

示例7: ConfigureServices

        /// <summary>
        /// Sets up the DI container. Loads types dynamically (http://docs.autofac.org/en/latest/register/scanning.html)
        /// </summary>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            /* TODO: #10
            services.AddCaching();
            services.AddSession();

            services.ConfigureSession(o =>
            {
                o.IdleTimeout = TimeSpan.FromMinutes(5);
            });*/

            services.AddTransient<WopiAuthorizationAttribute>();

            // Autofac resolution
            var builder = new ContainerBuilder();

            // Configuration
            Configuration configuration = new Configuration();
            configuration.AddEnvironmentVariables();
            builder.RegisterInstance(configuration).As<IConfiguration>().SingleInstance();

            // File provider implementation
            var providerAssembly = configuration.Get("WopiFileProviderAssemblyName");
            var assembly = AppDomain.CurrentDomain.Load(new AssemblyName(providerAssembly));
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();

            builder.Populate(services);
            var container = builder.Build();
            return container.Resolve<IServiceProvider>();
        }
开发者ID:FeodorFitsner,项目名称:WopiHost,代码行数:35,代码来源:Startup.cs

示例8: Main

        public void Main(string[] args)
        {
            var config = new Configuration();
            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var context = new HostingContext()
            {
                Configuration = config,
                ServerFactoryLocation = config.Get("server"),
                ApplicationName = config.Get("app")
            };

            var engine = new HostingEngine(_serviceProvider);

            var serverShutdown = engine.Start(context);
            var loggerFactory = context.ApplicationServices.GetRequiredService<ILoggerFactory>();
            var appShutdownService = context.ApplicationServices.GetRequiredService<IApplicationShutdown>();
            var shutdownHandle = new ManualResetEvent(false);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                try
                {
                    serverShutdown.Dispose();
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger<Program>();
                    logger.LogError("Dispose threw an exception.", ex);
                }
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }
开发者ID:Guruanth,项目名称:Hosting,代码行数:47,代码来源:Program.cs

示例9: Configure

        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?}");
            });
        }
开发者ID:david-driscoll,项目名称:DependencyInjection.Annotations,代码行数:58,代码来源:Startup.cs

示例10: CreateOrderProcessTask

        public static void CreateOrderProcessTask([Queue("orders")] CloudQueue orderQueue)
        {
            Console.WriteLine("Starting Create Order Process Task");
            try
            {
                var config = new Configuration().AddJsonFile("config.json");
                var connectionString = config.Get("Data:DefaultConnection:ConnectionString");

                using (var context = new PartsUnlimitedContext(connectionString))
                {
                    var orders = context.Orders.Where(x => !x.Processed).ToList();
                    Console.WriteLine("Found {0} orders to process", orders.Count);

                    foreach (var order in orders)
                    {
                        var productIds = context.OrderDetails.Where(x => x.OrderId == order.OrderId).Select(x => x.ProductId).ToList();
                        var items = context.Products
                            .Where(x => productIds.Contains(x.ProductId))
                            .ToList();

                        var orderItems = items.Select(
                                x => new LegacyOrderItem
                                {
                                    SkuNumber = x.SkuNumber,
                                    Price = x.Price
                                }).ToList();

                        var queueOrder = new LegacyOrder
                        {
                            Address = order.Address,
                            Country = order.Country,
                            City = order.City,
                            Phone = order.Phone,
                            CustomerName = order.Name,
                            OrderDate = order.OrderDate,
                            PostalCode = order.PostalCode,
                            State = order.State,
                            TotalCost = order.Total,
                            Discount = order.Total,
                            Items = orderItems
                        };
                        var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
                        var message = JsonConvert.SerializeObject(queueOrder, settings);
                        orderQueue.AddMessage(new CloudQueueMessage(message));
                        order.Processed = true;
                    }
                    context.SaveChanges();
                    Console.WriteLine("Orders successfully processed.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
开发者ID:rrawla,项目名称:PartsUnlimited,代码行数:55,代码来源:Functions.cs

示例11: Main

        public void Main(string[] args)
        {
            var config = new Configuration().AddEnvironmentVariables();
            string urlOptimizer = config.Get("URLOptimizerJobs") ?? "http://localhost:5004/api/Jobs/";
            Console.WriteLine("Mortgage calculation service listening to {0}", urlOptimizer);

            bool WarnNoMoreJobs = true;
            while (true)
            {
                try
                {
                    var httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    List<Job> jobs = httpClient.GetAsync(urlOptimizer).Result.Content.ReadAsAsync<List<Job>>().Result;

                    List<Job> remainingJobs = jobs.FindAll(j => !j.Taken);
                    if (remainingJobs.Count == 0)
                    {
                        if (WarnNoMoreJobs)
                        {
                            Console.WriteLine("No more jobs !");
                            WarnNoMoreJobs = false;
                        }
                        Task.Delay(1000).Wait();
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("{0} job(s) remaining", remainingJobs.Count);
                        WarnNoMoreJobs = true;
                    }
                    Random engine = new Random(DateTime.Now.Millisecond);
                    Job Taken = remainingJobs[engine.Next(remainingJobs.Count)];
                    Taken.Taken = true;
                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();

                    // The calculation is completely simulated, and does not correspond to any real financial computing
		    // We thus only wait for a given delay and send a random amount for the total cost
		    // Should one be interested in the kind of computation that can truly use scaling, one can take a look
		    // at the use of Genetic Algorithms as shown as in https://github.com/jp-gouigoux/PORCAGEN
                    Task.Delay(20).Wait();
                    Taken.Done = true;
                    Taken.TotalMortgageCost = Convert.ToDecimal(engine.Next(1000));

                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();
                }
                catch
                {
                    Task.Delay(1000).Wait();
                }
            }
        }
开发者ID:booking59,项目名称:mortgage,代码行数:53,代码来源:Program.cs

示例12: Initialize

        public static async Task Initialize(IServiceProvider serviceProvider)
        {
            var configuration = new Configuration()
                        .AddJsonFile("config.json")
                        .AddEnvironmentVariables();

            var userManager = serviceProvider.GetService<UserManager<User>>();
            var roleManager = serviceProvider.GetService<RoleManager<Role>>();
            var defaultAdminRoleValue = configuration.Get<string>(defaultAdminRole);
            if (!await roleManager.RoleExistsAsync(defaultAdminRoleValue))
            {
                await roleManager.CreateAsync(new Role {Name = defaultAdminRoleValue });
            }

            var user = await userManager.FindByNameAsync(configuration.Get<string>(defaultAdminUserName));
            if (user == null)
            {
                user = new User { Username = configuration.Get<string>(defaultAdminUserName) };
                await userManager.CreateAsync(user, configuration.Get<string>(defaultAdminPassword));
                await userManager.AddToRoleAsync(user, defaultAdminRoleValue);
                await userManager.AddClaimAsync(user, new Claim("Administration", "Allowed"));
            }
        }
开发者ID:freemsly,项目名称:CMS,代码行数:23,代码来源:Initializer.cs

示例13: Main

        public static void Main(string[] args)
        {
            var config = new Configuration()
                            .AddJsonFile("config.json")
                            .AddCommandLine(args);

            Console.WriteLine(config.Get("message"));

            foreach (var arg in args)
            {
                Console.WriteLine(arg);
            }

            Console.ReadLine();
        }
开发者ID:OutCust,项目名称:aspnet5samples,代码行数:15,代码来源:Program.cs

示例14: UpdateCount

        public int UpdateCount()
        {
            var config = new Configuration();
            config.Add(new MemoryConfigurationSource());
            var KEY = "count";
            var count = 1;

            var value = config.Get(KEY);
            if (value != null)
            {
                count = int.Parse(value);
                count++;
            }
            config.Set(KEY, count.ToString());
            return count;
        }
开发者ID:LeoLcy,项目名称:MVC6Recipes,代码行数:16,代码来源:HitCounterService.cs

示例15: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            IConfiguration config = new Configuration()
                        .AddJsonFile("config.json")
                        .AddEnvironmentVariables();

            var sqlConnectionString = config.Get("Data:DefaultConnection:ConnectionString");
            if (!String.IsNullOrEmpty(sqlConnectionString))
            {
                services.AddEntityFramework()
                        .AddSqlServer()
                        .AddDbContext<PartsUnlimitedContext>(options =>
                        {
                            options.UseSqlServer(sqlConnectionString);
                        });
            }
        }
开发者ID:hjgraca,项目名称:PartsUnlimited,代码行数:17,代码来源:Startup.cs


注:本文中的Microsoft.Framework.ConfigurationModel.Configuration.Get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。