Пример #1
0
        public void Configure(IApplicationBuilder app)
        {
            var config = new Configuration();
            config.AddEnvironmentVariables();
            config.AddJsonFile("config.json");
            config.AddJsonFile("config.dev.json", true);
            config.AddUserSecrets();

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

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


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

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

            app.UseFileServer();
        }
        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;
        }
Пример #3
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);
        }
Пример #4
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;
        }
        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;
        }
        /// <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"));
            }
        }
Пример #7
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     var config = new Configuration()
         .AddJsonFile("config.json");
     var constr = config.Get("Data:DefaultConnection:ConnectionString");
     options.UseSqlServer(constr);
 }
Пример #8
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>();
        }
Пример #9
0
        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();
        }
Пример #10
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"));
        }
        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?}");
            });
        }
Пример #12
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);
            }
        }
Пример #13
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();
                }
            }
        }
Пример #14
0
        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"));
            }
        }
Пример #15
0
        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();
        }
Пример #16
0
        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;
        }
Пример #17
0
        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);
                        });
            }
        }
Пример #18
0
        public void Main(string[] args)
        {
            var configuration = new Configuration();
            Console.WriteLine("Initial Config Sources: " + configuration.Sources.Count());

            var defaultSettings = new MemoryConfigurationSource();
            defaultSettings.Set("username", "Guest");
            configuration.Add(defaultSettings);
            Console.WriteLine("Added Memory Source. Sources: " + configuration.Sources.Count());

            configuration.AddCommandLine(args);
            Console.WriteLine("Added Command Line Source. Sources: " + configuration.Sources.Count());

            string username = configuration.Get("username");

            Console.WriteLine($"Hello, {username}!");
        }
Пример #19
0
        public void Configure(IApplicationBuilder app)
        {
            app.Use(async (ctx, next) =>
            {
                Console.WriteLine("Hello pipeline, {0}", ctx.Request.Path);
                await next();
            });

            var configuration = new Configuration();
            configuration.AddEnvironmentVariables().AddJsonFile("Config.Json");
            var title = configuration.Get("AppSettings:Title");

            app.UseMvc();
            app.Run(async (context) =>
            {
                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync("Hello Conf!");
            });
        }
Пример #20
0
        public void Configure(IApplicationBuilder app)
        {
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

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

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

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

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

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

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

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });
        }
        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);
        }
Пример #22
0
        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;
        }
Пример #23
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();

            // 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>();
        }
Пример #24
0
		public void Configure(IApplicationBuilder app)
        {
			// For more information on how to configure your application, 
			// visit http://go.microsoft.com/fwlink/?LinkID=398940

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

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

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

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

			return;
		}
Пример #25
0
        public async static Task UpdateProductProcessTaskAsync([QueueTrigger("product")] ProductMessage message)
        {
            var config = new Configuration().AddJsonFile("config.json");
            var connectionString = config.Get("Data:DefaultConnection:ConnectionString");

            using (var context = new PartsUnlimitedContext(connectionString))
            {
                var dbProductList = await context.Products.ToListAsync();
                foreach (var queueProduct in message.ProductList)
                {
                    var dbProduct = dbProductList.SingleOrDefault(x => x.SkuNumber == queueProduct.SkuNumber);

                    if (dbProduct != null)
                    {
                        dbProduct.Inventory = queueProduct.Inventory;
                        dbProduct.LeadTime = queueProduct.LeadTime;
                    }
                }
                await context.SaveChangesAsync(CancellationToken.None);
            }
        }
Пример #26
0
    public void Configure(IBuilder app)
    {
        var config = new Configuration();
        config.AddIniFile("Config.Sources.ini");
        config.AddEnvironmentVariables();

        app.Run(async ctx =>
        {
            ctx.Response.ContentType = "text/plain";

            Func<String, String> formatKeyValue = key => "[" + key + "] " + config.Get(key) + "\r\n\r\n";
            await ctx.Response.WriteAsync(formatKeyValue("Services:One.Two"));
            await ctx.Response.WriteAsync(formatKeyValue("Services:One.Two:Six"));
            await ctx.Response.WriteAsync(formatKeyValue("Data:DefaultConnecection:ConnectionString"));
            await ctx.Response.WriteAsync(formatKeyValue("Data:DefaultConnecection:Provider"));
            await ctx.Response.WriteAsync(formatKeyValue("Data:Inventory:ConnectionString"));
            await ctx.Response.WriteAsync(formatKeyValue("Data:Inventory:Provider"));
            await ctx.Response.WriteAsync(formatKeyValue("PATH"));
            await ctx.Response.WriteAsync(formatKeyValue("COMPUTERNAME"));
        });
    }
Пример #27
0
        public void Configure(IBuilder app)
        {
            var configuration = new Configuration();
            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                services.Add(OptionsServices.GetDefaultServices());
                services.SetupOptions<BlobStorageOptions>(options =>
                {
                    options.ConnectionString = configuration.Get("ReversePackageSearch:BlobStorageConnection");
                });
                // Add MVC services to the services container
                services.AddMvc();
            });

            // Add static files
            app.UseStaticFiles(new StaticFileOptions { FileSystem = new PhysicalFileSystem("content") });
            // Add MVC to the request pipeline
            app.UseMvc();
        }
Пример #28
0
        public void CanSetValuesAndReloadValues()
        {
            // Arrange
            var config = new Configuration();

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

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

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

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

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

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

            // Recover values by reloading
            config.Reload();
            Assert.Equal("XmlValue6", config["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
        }
        public void NewConfigurationSourceOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem1" }
            };
            var dic2 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem2" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);

            var config = new Configuration();

            // Act
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);

            // Assert
            Assert.Equal(2, CountAllEntries(config));
            Assert.Equal("ValueInMem2", config.Get("Key1:Key2"));
        }
        public void AddCommandLineTest()
        {
            var configuration = new Microsoft.Framework.ConfigurationModel.Configuration();
            configuration.Add(new MemoryConfigurationSource());
            var configurationService = new ConfigurationService(configuration);

            IEnumerable<string> args = new List<string>()
            {
              "build", "/param1=1", "/param2=2 2", "/param3", "3", "posarg1", "--switch1", "true", "/param4", "4 4"
            };

            configurationService.AddCommandLine(configuration, args);

            Assert.AreEqual("build", configuration.Get("arg0"));
            Assert.AreEqual("posarg1", configuration.Get("arg1"));

            Assert.AreEqual("1", configuration.Get("param1"));
            Assert.AreEqual("2 2", configuration.Get("param2"));
            Assert.AreEqual("3", configuration.Get("param3"));
            Assert.AreEqual("4 4", configuration.Get("param4"));

            Assert.AreEqual("true", configuration.Get("switch1"));
        }
Пример #31
0
        public void NewConfigurationSourceOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);

            var config = new Configuration();

            // Act
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);

            // Assert
            Assert.Equal("ValueInMem2", config.Get("Key1:Key2"));
        }
Пример #32
0
        public void Configure(IBuilder app)
        {
            /* Adding IConfiguration as a service in the IoC to avoid instantiating Configuration again.
                 * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
                 * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            */
            var configuration = new Configuration();
            configuration.AddJsonFile("LocalConfig.json");
            configuration.AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.

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

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

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

                services.AddScoped<MusicStoreContext>();

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

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

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

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

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

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

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

            //Populates the MusicStore sample data
            SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
        }
Пример #33
0
        public void Configure(IBuilder app)
        {
            /* Adding IConfiguration as a service in the IoC to avoid instantiating Configuration again.
                 * Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
                 * then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            */
            var configuration = new Configuration();
            configuration.AddJsonFile("LocalConfig.json");
            configuration.AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.

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

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

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

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

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

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

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

            app.UseTwoFactorSignInCookies();

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

            //Populates the MusicStore sample data
            SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait();
        }
Пример #34
0
        public void SettingValueUpdatesAllConfigurationSources()
        {
            // Arrange
            var dict = new Dictionary<string, string>()
                {
                    {"Key1", "Value1"},
                    {"Key2", "Value2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

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

            // Act
            config.Set("Key1", "NewValue1");
            config["Key2"] = "NewValue2";

            // Assert
            Assert.Equal("NewValue1", config.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc1.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc2.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc3.Get("Key1"));
            Assert.Equal("NewValue2", config["Key2"]);
            Assert.Equal("NewValue2", memConfigSrc1.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc2.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc3.Get("Key2"));
        }
Пример #35
0
        public void LoadAndCombineKeyValuePairsFromDifferentConfigurationSources()
        {
            // Arrange
            var config = new Configuration();

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

            config.Add(memConfigSrc);

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

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

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

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

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

            Assert.Equal("MemValue6", config["CommonKey1:CommonKey2:CommonKey3:CommonKey4"]);
        }
Пример #36
0
        public void Configure(IBuilder app)
        {
            var configuration = new Configuration()
                .AddJsonFile("Config.json")
                .AddEnvironmentVariables();

            app.UseServices(services =>
            {
                // Add options accessors to the service container
                services.SetupOptions<IdentityDbContextOptions>(options =>
                {
                    options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername");
                    options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword");
                    options.UseSqlServer(configuration.Get("Data:IdentityConnection:ConnectionString"));
                });

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

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

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

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

                // Add application services to the service container
                services.AddScoped<MusicStoreContext>();
                services.AddTransient(typeof(IHtmlHelper<>), typeof(AngularHtmlHelper<>));
            });

            // Initialize the sample data
            SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
            SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait();

            // Configure the HTTP request pipeline

            // Add cookie auth
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login")
            });

            // Add static files
            app.UseStaticFiles(new StaticFileOptions { FileSystem = new PhysicalFileSystem("wwwroot") });

            // Add MVC
            app.UseMvc(routes =>
            {
                // TODO: Move these back to attribute routes when they're available
                routes.MapRoute(null, "api/genres/menu", new { controller = "GenresApi", action = "GenreMenuList" });
                routes.MapRoute(null, "api/genres", new { controller = "GenresApi", action = "GenreList" });
                routes.MapRoute(null, "api/genres/{genreId}/albums", new { controller = "GenresApi", action = "GenreAlbums" });
                routes.MapRoute(null, "api/albums/mostPopular", new { controller = "AlbumsApi", action = "MostPopular" });
                routes.MapRoute(null, "api/albums/all", new { controller = "AlbumsApi", action = "All" });
                routes.MapRoute(null, "api/albums/{albumId}", new { controller = "AlbumsApi", action = "Details" });
                routes.MapRoute(null, "{controller}/{action}/{id?}", new { controller = "Home", action = "Index" });
            });
        }