Esempio n. 1
19
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCaching();
            services.AddSession();

            services.AddMvc();
            services.AddSingleton<PassThroughAttribute>();
            services.AddSingleton<UserNameService>();
            services.AddTransient<ITestService, TestService>();

            services.ConfigureMvc(options =>
            {
                options.Filters.Add(typeof(PassThroughAttribute), order: 17);
                options.AddXmlDataContractSerializerFormatter();
                options.Filters.Add(new FormatFilterAttribute());
            });

#if DNX451
            // Fully-qualify configuration path to avoid issues in functional tests. Just "config.json" would be fine
            // but Configuration uses CallContextServiceLocator.Locator.ServiceProvider to get IApplicationEnvironment.
            // Functional tests update that service but not in the static provider.
            var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>();
            var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json");

            // Set up configuration sources.
            var configuration = new Configuration()
                .AddJsonFile(configurationPath)
                .AddEnvironmentVariables();
            string diSystem;
            if (configuration.TryGet("DependencyInjection", out diSystem) &&
                diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase))
            {
                _autoFac = true;
                services.ConfigureRazorViewEngine(options =>
                {
                    var expander = new LanguageViewLocationExpander(
                        context => context.HttpContext.Request.Query["language"]);
                    options.ViewLocationExpanders.Insert(0, expander);
                });

                // Create the autofac container
                var builder = new ContainerBuilder();

                // Create the container and use the default application services as a fallback
                AutofacRegistration.Populate(
                    builder,
                    services);

                builder.RegisterModule<MonitoringModule>();

                var container = builder.Build();

                return container.Resolve<IServiceProvider>();
            }
            else
#endif
            {
                return services.BuildServiceProvider();
            }
        }
Esempio n. 2
0
        /// <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>();
        }
        public static IConfigurationSourceRoot RegisterConfiguration([NotNull] this Startup startup, [NotNull] string toolsDirectory, [NotNull] string projectDirectory, ConfigurationOptions options)
        {
            var configuration = new Microsoft.Framework.ConfigurationModel.Configuration();
            configuration.Add(new MemoryConfigurationSource());

            configuration.Set(Constants.Configuration.ToolsDirectory, toolsDirectory);
            configuration.Set(Constants.Configuration.ProjectDirectory, projectDirectory);
            configuration.Set(Constants.Configuration.SystemConfigFileName, "scconfig.json");

            var configurationService = new ConfigurationService(configuration);

            if ((options & ConfigurationOptions.DoNotLoadConfig) != ConfigurationOptions.DoNotLoadConfig)
            {
                try
                {                       
                    configurationService.Load(options);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    return null;
                }
            }

            return configuration;
        }
 public Startup(IApplicationEnvironment env)
 {
     // Setup configuration sources.
     Configuration = new Configuration(env.ApplicationBasePath)
         .AddJsonFile("config.json")
         .AddEnvironmentVariables();
 }
Esempio n. 5
0
        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)
            {
                IConfigurationSourceContainer 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"),
                        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);
        }
Esempio n. 6
0
        public void CanGetSubKey()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"DataSource:DB2:Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Data", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var config = new Configuration();
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            string memVal1, memVal2, memVal3, memVal4, memVal5;
            bool memRet1, memRet2, memRet3, memRet4, memRet5;

            // Act
            var configFocus = config.GetSubKey("Data");

            memRet1 = configFocus.TryGet("DB1:Connection1", out memVal1);
            memRet2 = configFocus.TryGet("DB1:Connection2", out memVal2);
            memRet3 = configFocus.TryGet("DB2:Connection", out memVal3);
            memRet4 = configFocus.TryGet("Source:DB2:Connection", out memVal4);
            memRet5 = configFocus.TryGet(null, out memVal5);

            // Assert
            Assert.True(memRet1);
            Assert.True(memRet2);
            Assert.False(memRet3);
            Assert.False(memRet4);
            Assert.True(memRet5);

            Assert.Equal("MemVal1", memVal1);
            Assert.Equal("MemVal2", memVal2);
            Assert.Equal("MemVal4", memVal5);

            Assert.Equal("MemVal1", configFocus.Get("DB1:Connection1"));
            Assert.Equal("MemVal2", configFocus.Get("DB1:Connection2"));
            Assert.Null(configFocus.Get("DB2:Connection"));
            Assert.Null(configFocus.Get("Source:DB2:Connection"));
            Assert.Equal("MemVal4", configFocus.Get(null));

            Assert.Equal("MemVal1", configFocus["DB1:Connection1"]);
            Assert.Equal("MemVal2", configFocus["DB1:Connection2"]);
            Assert.Null(configFocus["DB2:Connection"]);
            Assert.Null(configFocus["Source:DB2:Connection"]);
            Assert.Equal("MemVal4", configFocus[null]);
        }
Esempio n. 7
0
        public void Configure(IBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddEnvironmentVariables();

            app.UseOwin();

            // Set up application services
            app.UseServices(services =>
            {                // Add MVC services to the services container
                services.AddMvc();
                services.SetupOptions<MvcOptions>(options => {
                    System.Diagnostics.Debug.WriteLine(options.OutputFormatters.Select(item => item.GetType().Name));

                    options.OutputFormatters.RemoveAt(0);
                });
            });

            // 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?}");
            });
        }
        private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
                {
                    new MemoryConfigurationSource(
                        new Dictionary<string, string>
                            {
                                { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                            })
                };

            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddInstance<IConfiguration>(configuration)
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
Esempio n. 9
0
        internal Settings(string projectDirectory, string settingsFile)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile(Path.Combine(projectDirectory, settingsFile));

            _configuration = configuration;
        }
Esempio n. 10
0
        public void CommitConfiguration_with_default_config_file()
        {
            var toolMock = new Mock<MyMigrationTool>() { CallBase = true };
            var args
                = new[]
                      {
                          "--ContextAssembly=EntityFramework.Design.Tests.dll",
                      };
            var configSourceMock = new Mock<IniFileConfigurationSource>("Foo") { CallBase = true };
            var tool = toolMock.Object;
            var configuration = new Configuration();

            configSourceMock.Setup(m => m.Load());
            configSourceMock.Setup(m => m.Commit());

            toolMock.Protected()
                .Setup<IniFileConfigurationSource>("CreateIniFileConfigurationSource", ItExpr.IsAny<string>())
                .Callback<string>(AssertConfigFileCallback2)
                .Returns(configSourceMock.Object);

            configuration.AddCommandLine(args);

            tool.CommitConfiguration(configuration);

            toolMock.Protected().Verify<IniFileConfigurationSource>("CreateIniFileConfigurationSource", Times.Once(), ItExpr.IsAny<string>());
        }
Esempio n. 11
0
        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
Esempio n. 12
0
 /// <summary>
 /// Constructor - load the configuration files and store in the
 /// static area.
 /// </summary>
 public Startup()
 {
     Configuration = new Configuration()
         .AddJsonFile("config.json", optional: true)
         .AddJsonFile("config-local.json", optional: true)
         .AddEnvironmentVariables();
 }
Esempio n. 13
0
        public void Configure(IBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            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" });
            });
        }
Esempio n. 14
0
        public void EnvDefaultsToDevelopmentConfigValueIfSpecified()
        {
            var vals = new Dictionary<string, string>
            {
                { "ASPNET_ENV", "Staging" }
            };

            var config = new Configuration()
                .Add(new MemoryConfigurationSource(vals));

            var context = new HostingContext
            {
                ServerFactory = this,
                Configuration = config
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                Assert.Equal("Staging", context.EnvironmentName);
                var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
                Assert.Equal("Staging", env.EnvironmentName);
            }
        }
Esempio n. 15
0
 public Startup(IHostingEnvironment env)
 {
     // Setup configuration sources.
     var configuration = new Configuration();
     configuration.AddEnvironmentVariables();
     Configuration = configuration;
 }
Esempio n. 16
0
 public Startup(IHostingEnvironment env)
 {
     // Setup configuration sources.
     Configuration = new Configuration()
         .AddJsonFile("config.json")
         .AddEnvironmentVariables();
 }
Esempio n. 17
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();
        }
Esempio n. 18
0
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            var configPath = Path.Combine(appEnv.ApplicationBasePath, "..", "..");

            Configuration = new Configuration(configPath).AddJsonFile("config.json").
                AddEnvironmentVariables("SmsPrize_");
        }
Esempio n. 19
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     var config = new Configuration()
         .AddJsonFile("config.json");
     var constr = config.Get("Data:DefaultConnection:ConnectionString");
     options.UseSqlServer(constr);
 }
Esempio n. 20
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);
        }
Esempio n. 21
0
        protected override void OnConfiguring(DbContextOptions options)
        {
            var xConfiguration = new Microsoft.Framework.ConfigurationModel.Configuration()
                                 .AddJsonFile("config.json")
                                 .AddEnvironmentVariables();

            options.UseSqlServer(xConfiguration.Get("Data:DefaultConnection:ConnectionString"));
        }
Esempio n. 22
0
        public Startup(IHostingEnvironment env)
        {
            var configuration = new Configuration()
                  .AddJsonFile("config.json");

            configuration.AddEnvironmentVariables();
            Configuration = configuration;
        }
Esempio n. 23
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 StartupNtlmAuthentication()
 {
     //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.
     Configuration = new Configuration()
                 .AddJsonFile("config.json")
                 .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.
 }
Esempio n. 25
0
        public IActionResult About()
        {
            var config =  new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            return View(config);
        }
        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?}");
            });
        }
Esempio n. 27
0
        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;
        }
Esempio n. 28
0
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            // Setup configuration sources.

            var builder = new Configuration()
                .AddJsonFile("config.json");

            builder.AddEnvironmentVariables();
            Configuration = builder;
        }
Esempio n. 29
0
        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);
            }
        }
Esempio n. 30
0
        public IActionResult Index()
        {
            var config = new Configuration();
            config.Add(new EfSettingConfigurationSource(_dbContext));

            ViewBag.TwitterApiKey = config["TwitterApiKey"];
            ViewBag.FacebookApiKey = config["FacebookApiKey"];
            ViewBag.GoogleAnalyticsKey = config["GoogleAnalyticsKey"];

            return View();
        }
Esempio n. 31
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();
        }
        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;
        }
Esempio n. 33
0
        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();
                }
            }
        }
Esempio n. 34
0
        internal DocConfiguration(Project project)
        {
            this.config = new Microsoft.Framework.ConfigurationModel.Configuration();
            var configurationItems = project.Items.Where(o => o.ItemType == "DocNetConfiguration");

            //var configurationItems = project.Items.Where(o => o.EvaluatedInclude == @"Documentation\docconf.ini");
            //var test = configurationItems.First();

            foreach (var configItem in configurationItems)
            {
                this.config.Add(new IniFileConfigurationSource(Path.Combine(project.DirectoryPath, configItem.EvaluatedInclude)));
            }
        }
        IEnumerable <ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var tenantPaths = _appDataFolder
                              .ListDirectories("Sites")
                              .Select(path => _appDataFolder.MapPath(path));

            var shellSettings = new List <ShellSettings>();

            foreach (var tenantPath in tenantPaths)
            {
                Logger.Information("ShellSettings found in '{0}', attempting to load.", tenantPath);

                IConfigurationSourceRoot configurationContainer =
                    new Microsoft.Framework.ConfigurationModel.Configuration()
                    .AddJsonFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "json")),
                                 true)
                    .AddXmlFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "xml")),
                                true)
                    .AddIniFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "ini")),
                                true)
                    .Add(
                        new DefaultFileConfigurationSource(
                            _appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "txt")), false));

                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);

                Logger.Information("Loaded ShellSettings for tenant '{0}'", shellSetting.Name);
            }

            return(shellSettings);
        }