Exemplo n.º 1
9
    public static void Main(string[] args = null)
    {
        ConfigurationBuilder configurationBuilder = 
                new ConfigurationBuilder();
            

        if (args == null)
        {
            // Add defaultConfigurationStrings
            configurationBuilder.AddInMemoryCollection(
                DefaultConfigurationStrings);
        }
        else
        {
            configurationBuilder
                .AddInMemoryCollection(DefaultConfigurationStrings)
                .AddJsonFile("Config.json", 
                    true) // bool indicates file is optional
                // "EssentialDotNetConfiguration" is an optional prefix for all 
                // environment configuration keys  
                .AddEnvironmentVariables("EssentialDotNetConfiguration")
                .AddCommandLine(
                    args, GetSwitchMappings(DefaultConfigurationStrings));
        }
        Configuration = configurationBuilder.Build();

        Console.WriteLine($"Hello {Configuration["Profile:UserName"]}");

        ConsoleWindow consoleWindow = 
                Configuration.Get<ConsoleWindow>("AppConfiguration:MainWindow");
        ConsoleWindow.SetConsoleWindow(consoleWindow);
    }
Exemplo n.º 2
3
        public void IdentityOptionsFromConfig()
        {
            const string roleClaimType = "rolez";
            const string usernameClaimType = "namez";
            const string useridClaimType = "idz";
            const string securityStampClaimType = "stampz";

            var dic = new Dictionary<string, string>
            {
                {"identity:claimsidentity:roleclaimtype", roleClaimType},
                {"identity:claimsidentity:usernameclaimtype", usernameClaimType},
                {"identity:claimsidentity:useridclaimtype", useridClaimType},
                {"identity:claimsidentity:securitystampclaimtype", securityStampClaimType},
                {"identity:user:requireUniqueEmail", "true"},
                {"identity:password:RequiredLength", "10"},
                {"identity:password:RequireNonAlphanumeric", "false"},
                {"identity:password:RequireUpperCase", "false"},
                {"identity:password:RequireDigit", "false"},
                {"identity:password:RequireLowerCase", "false"},
                {"identity:lockout:AllowedForNewUsers", "FALSe"},
                {"identity:lockout:MaxFailedAccessAttempts", "1000"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dic);
            var config = builder.Build();
            Assert.Equal(roleClaimType, config["identity:claimsidentity:roleclaimtype"]);

            var services = new ServiceCollection();
            services.AddIdentity<TestUser,TestRole>();
            services.Configure<IdentityOptions>(config.GetSection("identity"));
            var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
            Assert.NotNull(accessor);
            var options = accessor.Value;
            Assert.Equal(roleClaimType, options.ClaimsIdentity.RoleClaimType);
            Assert.Equal(useridClaimType, options.ClaimsIdentity.UserIdClaimType);
            Assert.Equal(usernameClaimType, options.ClaimsIdentity.UserNameClaimType);
            Assert.Equal(securityStampClaimType, options.ClaimsIdentity.SecurityStampClaimType);
            Assert.True(options.User.RequireUniqueEmail);
            Assert.Equal("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+", options.User.AllowedUserNameCharacters);
            Assert.False(options.Password.RequireDigit);
            Assert.False(options.Password.RequireLowercase);
            Assert.False(options.Password.RequireNonAlphanumeric);
            Assert.False(options.Password.RequireUppercase);
            Assert.Equal(10, options.Password.RequiredLength);
            Assert.False(options.Lockout.AllowedForNewUsers);
            Assert.Equal(1000, options.Lockout.MaxFailedAccessAttempts);
        }
        public IHostingEngine Build()
        {
            var configBuider = new ConfigurationBuilder();

            configBuider.AddInMemoryCollection(new Dictionary<string, string> {{"server.urls", uri}});

            var builder = new WebHostBuilder(configBuider.Build());

            builder.UseStartup(app => { new Startup().ConfigureApplication(app); }, services => { new ServiceConfigurer(documentStore).ConfigureServices(services); });
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");

            return builder.Build();
        }
        private static IConfigurationRoot CreateConfiguration(IEnumerable <KeyValuePair <string, string> > configurationData, IDotNetCliService dotNetCliService)
        {
            var info            = dotNetCliService.GetInfo();
            var msbuildSdksPath = Path.Combine(info.BasePath, "Sdks");

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);

            // We need to set the "UseLegacySdkResolver" for tests because
            // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs
            // that we install locally in the ".dotnet" directory.
            // This property will cause the MSBuild project loader to set the
            // MSBuildSDKsPath environment variable to the correct path "Sdks" folder
            // within the appropriate .NET Core SDK.
            var msbuildProperties = new Dictionary <string, string>()
            {
                [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true",
                [$"MSBuild:{nameof(MSBuildOptions.MSBuildSDKsPath)}"]      = msbuildSdksPath
            };

            builder.AddInMemoryCollection(msbuildProperties);

            return(builder.Build());
        }
Exemplo n.º 5
0
        public static OmniSharpTestHost Create(
            string path = null,
            ITestOutputHelper testOutput = null,
            IEnumerable <KeyValuePair <string, string> > configurationData = null,
            DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current,
            IEnumerable <ExportDescriptorProvider> additionalExports = null)
        {
            var environment      = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace);
            var loggerFactory    = new LoggerFactory().AddXunit(testOutput);
            var logger           = loggerFactory.CreateLogger <OmniSharpTestHost>();
            var sharedTextWriter = new TestSharedTextWriter(testOutput);

            var dotNetCliService = CreateTestDotNetCliService(dotNetCliVersion, loggerFactory);

            var info = dotNetCliService.GetInfo();

            logger.LogInformation($"Using .NET CLI: {info.Version}");

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);

            // We need to set the "UseLegacySdkResolver" for tests because
            // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs
            // that we install locally in the ".dotnet" and ".dotnet-legacy" directories.
            // This property will cause the MSBuild project loader to set the
            // MSBuildSDKsPath environment variable to the correct path "Sdks" folder
            // within the appropriate .NET Core SDK.
            var msbuildProperties = new Dictionary <string, string>()
            {
                [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true",
                [$"MSBuild:{nameof(MSBuildOptions.MSBuildSDKsPath)}"]      = Path.Combine(info.BasePath, "Sdks")
            };

            builder.AddInMemoryCollection(msbuildProperties);

            var configuration = builder.Build();

            var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration, NullEventEmitter.Instance, dotNetCliService);

            var compositionHost = new CompositionHostBuilder(serviceProvider, s_lazyAssemblies.Value, additionalExports)
                                  .Build();

            var workspace = compositionHost.GetExport <OmniSharpWorkspace>();

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger);

            var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
        private static IConfigurationRoot GetConfiguration(IDictionary <string, string> data)
        {
            var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(data);
            return(configurationBuilder.Build());
        }
        public static OmniSharpTestHost Create(string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current)
        {
            var dotNetPath = Path.Combine(
                TestAssets.Instance.RootFolder,
                GetDotNetCliFolderName(dotNetCliVersion),
                "dotnet");

            if (!File.Exists(dotNetPath))
            {
                dotNetPath = Path.ChangeExtension(dotNetPath, ".exe");
            }

            if (!File.Exists(dotNetPath))
            {
                throw new InvalidOperationException($"Local .NET CLI path does not exist. Did you run build.(ps1|sh) from the command line?");
            }

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);
            var configuration = builder.Build();

            var environment      = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace);
            var loggerFactory    = new LoggerFactory().AddXunit(testOutput);
            var sharedTextWriter = new TestSharedTextWriter(testOutput);

            var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration);

            var compositionHost = new CompositionHostBuilder(serviceProvider, environment, NullEventEmitter.Instance)
                                  .WithAssemblies(s_lazyAssemblies.Value)
                                  .Build();

            var workspace = compositionHost.GetExport <OmniSharpWorkspace>();
            var logger    = loggerFactory.CreateLogger <OmniSharpTestHost>();

            var dotNetCli = compositionHost.GetExport <DotNetCliService>();

            dotNetCli.SetDotNetPath(dotNetPath);
            var version = dotNetCli.GetVersion();

            logger.LogInformation($"Using .NET CLI: {version}");

            var oldMSBuildSdksPath = SetMSBuildSdksPath(dotNetCli);

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger);

            var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost, oldMSBuildSdksPath);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
        public void Given_The_system_has_version_P0(String P0)
        {
            var config = new Dictionary <string, string>()
            {
                ["version"] = P0
            };
            var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(config);
            _config = configurationBuilder.Build();
        }
Exemplo n.º 9
0
 /// <summary>Creates a default configuration builder with some defaults.</summary>
 public static ConfigurationBuilder DefaultConfigurationBuilder()
 {
     var builder = new ConfigurationBuilder();
     builder.AddInMemoryCollection(new Dictionary<string, string>
     {
         { nameof(DataConnectionString), "UseDevelopmentStorage=true" },
         { nameof(LogsFolder), "logs" },
         { nameof(TraceToConsole), "true" },
         { nameof(InitialSilosCount), "2" },
     });
     return builder;
 }
Exemplo n.º 10
0
        static BaseTest()
        {
            ConfigurationBuilder builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(DefaultConfigurationStrings);
            Configuration = builder.Build();

            //LogManager.Adapter = new ConsoleOutLoggerFA(new NameValueCollection());

            ScriptDirectory = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(TestContext.CurrentContext.TestDirectory, ".."), ".."), ".."), "Scripts"),
                                           Configuration["database"]) + Path.DirectorySeparatorChar;
        }
Exemplo n.º 11
0
 public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null)
 {
     var configurationBuilder = new ConfigurationBuilder();
     configurationBuilder.AddInMemoryCollection(new []
     {
         new KeyValuePair<string, string>("webroot", ".")
     });
     var builder = new WebApplicationBuilder()
         .UseConfiguration(configurationBuilder.Build())
         .Configure(configureApp)
         .ConfigureServices(configureServices);
     return new TestServer(builder);
 }
Exemplo n.º 12
0
        public ConfigSummarySnippet()
        {
            // Everything between SNIPPET-START and SNIPPET-END will be inlined in the doc!
            // SNIPPET-START
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection();
            var config = builder.Build();
            config["somekey"] = "somevalue";

            // do some other work

            var setting = config["somekey"]; // also returns "somevalue"
            // SNIPPET-END
        }
Exemplo n.º 13
0
        public static StartupServer Create(Uri baseAddress = null)
        {
            var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();

            var config = new ConfigurationBuilder();
            var configDict = new Dictionary<string, string>();
            configDict["Hosting:Environment"] = "Test";
            config.AddInMemoryCollection(configDict.AsEnumerable());
            var conf = config.Build();

            var env = new HostingEnvironment();
            env.Initialize($"{appEnv.ApplicationBasePath}/../../src/Accounting", conf);
            var startup = new Accounting.Startup(appEnv, env);

            var setup = new SetupObject();

            Action<IApplicationBuilder> buildApp = (app) =>
            {
                app.Use(async (context, next) =>
                {
                    var req = context.Request;
                        
                    if (req.Path == testSetupPathString && setup.Setup != null)
                    {
                        await setup.Setup(context);
                    }
                    else
                    {
                        await next();
                    }
                });
                startup.Configure(app);
            };

            Action<IServiceCollection> buildServices = (services) =>
            {
                startup.ConfigureServices(services);
                services.Remove(services.Where(sp => sp.ServiceType == typeof(IConfigureOptions<AntiforgeryOptions>)).First());
                services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<AntiforgeryOptions>, TestAntiforgeryOptionsSetup>());
                services.AddSingleton<IAntiforgeryTokenSerializer, TestAntiforgeryTokenSerializer>();
                services.AddSingleton<IAntiforgeryTokenGenerator, TestAntiforgeryTokenGenerator>();
            };

            StartupServer server = new StartupServer(CreateBuilder(conf, app => buildApp(app), services => buildServices(services)));
            server.setupObject = setup;
            server.BaseAddress = baseAddress;
            return server;
        }
        public void ResolvePlaceholders_ResolvesSinglePlaceholder()
        {

            // Arrange
            string text = "foo=${foo}";
            ConfigurationBuilder builder = new ConfigurationBuilder();
            var dic1 = new Dictionary<string, string>()
                {
                    {"foo", "bar"}
                };
            builder.AddInMemoryCollection(dic1);
            var config = builder.Build();

            // Act and Assert
            string result = PropertyPlaceholderHelper.ResovlePlaceholders(text, config);
            Assert.Equal("foo=bar", result);
        }
Exemplo n.º 15
0
        private IWebHost StartWebSocketServer(Func<HttpContext, Task> app)
        {
            Action<IApplicationBuilder> startup = builder =>
            {
                builder.Use(async (ct, next) =>
                {
                    try
                    {
                        // Kestrel does not return proper error responses:
                        // https://github.com/aspnet/KestrelHttpServer/issues/43
                        await next();
                    }
                    catch (Exception ex)
                    {
                        if (ct.Response.HasStarted)
                        {
                            throw;
                        }

                        ct.Response.StatusCode = 500;
                        ct.Response.Headers.Clear();
                        await ct.Response.WriteAsync(ex.ToString());
                    }
                });

                builder.UseWebSockets();
                builder.Run(c => app(c));
            };

            var configBuilder = new ConfigurationBuilder();
            configBuilder.AddInMemoryCollection();
            var config = configBuilder.Build();
            config["server.urls"] = "http://localhost:54321";

            var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .Configure(startup)
                .Build();

            host.Start();

            return host;
        }
Exemplo n.º 16
0
 public void IdentityOptionsActionOverridesConfig()
 {
     var dic = new Dictionary<string, string>
     {
         {"identity:user:requireUniqueEmail", "true"},
         {"identity:lockout:MaxFailedAccessAttempts", "1000"}
     };
     var builder = new ConfigurationBuilder();
     builder.AddInMemoryCollection(dic);
     var config = builder.Build();
     var services = new ServiceCollection();
     services.Configure<IdentityOptions>(config.GetSection("identity"));
     services.AddIdentity<TestUser, TestRole>(o => { o.User.RequireUniqueEmail = false; o.Lockout.MaxFailedAccessAttempts++; });
     var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
     Assert.NotNull(accessor);
     var options = accessor.Value;
     Assert.False(options.User.RequireUniqueEmail);
     Assert.Equal(1001, options.Lockout.MaxFailedAccessAttempts);
 }
Exemplo n.º 17
0
        public static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder();
            Console.WriteLine("Initial Config Sources: " + builder.Sources.Count());

            builder.AddInMemoryCollection(new Dictionary<string, string>
            {
                { "username", "Guest" }
            });

            Console.WriteLine("Added Memory Source. Sources: " + builder.Sources.Count());

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

            var config = builder.Build();
            string username = config["username"];

            Console.WriteLine($"Hello, {username}!");
        }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            /* configure specifying settings */
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection()
                .AddEnvironmentVariables();

            var config = builder.Build();
            config["ConnectionStringDefault"] = 
                "Server=(localdb)\\MSSQLLocalDB;Database=BooksDB;Trusted_Connection=true;MultipleActiveResultSets=true";
            var paths = config["BookWebPictures"];
            config["PicturesFolderProd"] = Path.Combine(paths, "Prod");
            config["PicturesFolderSeed"] = Path.Combine(paths, "Seed");

            /* configure providing settings */
            services.AddOptions();
            services.Configure<ConnectionString>(config);
            services.Configure<PicturesFolder>(config);


            services.AddMvc(conf =>
            {
#if !DEBUG
                conf.Filters.Add(new RequireHttpsAttribute());
#endif
            });

            services.AddIdentity<BookWebUser, IdentityRole>(conf =>
            {
                // TODO configure
            }).AddEntityFrameworkStores<BookWebContext>()
            .AddDefaultTokenProviders();

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<BookWebContext>(/*options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]*/);

            services.AddScoped<BookWebContext>();
            services.AddTransient<DataSeeder>();
        }
Exemplo n.º 19
0
        private static IConfigurationRoot CreateConfiguration(IConfiguration configurationData)
        {
            var builder = new ConfigurationBuilder();

            if (configurationData != null)
            {
                builder.AddConfiguration(configurationData);
            }

            // We need to set the "UseLegacySdkResolver" for tests because
            // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs
            // that we install locally in the ".dotnet" directory.
            // This property will cause the MSBuild project loader to set the
            // MSBuildSDKsPath environment variable to the correct path "Sdks" folder
            // within the appropriate .NET Core SDK.
            var msbuildProperties = new Dictionary <string, string>()
            {
                [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true"
            };

            builder.AddInMemoryCollection(msbuildProperties);

            return(builder.Build());
        }
Exemplo n.º 20
0
 private static void SetConfigurationDefaults(ConfigurationBuilder builder)
 {
     var defaults = new Dictionary<string, string>
     {
         {"configuration:ChromeDriverLocation", "C:\\Selenium\\chromedriver_win32"},
         {"configuration:IEDriverLocation", "C:\\Selenium\\iedriver_win32"}
     };
     builder.AddInMemoryCollection(defaults);
 }
        public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders()
        {

            // Arrange
            string text1 = "foo=${b${inner}}";
            ConfigurationBuilder builder1 = new ConfigurationBuilder();
            var dic1 = new Dictionary<string, string>()
                {
                    {"bar", "bar"},
                    {"inner", "ar"}

                };
            builder1.AddInMemoryCollection(dic1);
            var config1 = builder1.Build();

            string text2 = "${top}";
            ConfigurationBuilder builder2 = new ConfigurationBuilder();
            var dic2 = new Dictionary<string, string>()
                {
                    {"top", "${child}+${child}"},
                    {"child", "${${differentiator}.grandchild}" },
                    {"differentiator", "first" },
                    {"first.grandchild", "actualValue" }
                };
            builder2.AddInMemoryCollection(dic2);
            var config2 = builder2.Build();


            // Act and Assert
            string result1 = PropertyPlaceholderHelper.ResovlePlaceholders(text1, config1);
            Assert.Equal("foo=bar", result1);
            string result2 = PropertyPlaceholderHelper.ResovlePlaceholders(text2, config2);
            Assert.Equal("actualValue+actualValue", result2);

        }
 private static IConfigurationRoot GetConfiguration(IDictionary<string, string> data)
 {
     var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
     configurationBuilder.AddInMemoryCollection(data);
     return configurationBuilder.Build();
 }