public void Configuration_values_are_read_from_a_series_of_json_files() { if (File.Exists("global.json")) File.Delete("global.json"); if (File.Exists("local.json")) File.Delete("local.json"); if (File.Exists("config.json")) File.Delete("config.json"); const string globalConf = @"{ key1: ""global-value-1"", key2: ""global-value-2""}"; const string localConf = @"{ key1: ""local-value-1""}"; const string configConf = @"{ key3: ""config-value-3""}"; File.AppendAllText("global.json", globalConf); File.AppendAllText("local.json", localConf); File.AppendAllText("config.json", configConf); _binder = ConfigurationBinderFactory.New(x => { // least specific to most specific // I assume that is reasonable x.AddJsonFile("global.json"); x.AddJsonFile("local.json"); x.AddJsonFile("config.json"); }); }
public void A_configuration_object_is_bound() { const string json = @"{ Inner: { Value: 47 } }"; _binder = ConfigurationBinderFactory.New(x => { x.AddJson(json); }); _configuration = _binder.Bind<OuterLevel>(); }
public void A_configuration_object_is_bound() { const string json = @"{ Value: [47,22] }"; _binder = ConfigurationBinderFactory.New(x => { x.AddJson(json); }); _configuration = _binder.Bind<ClassWithArray>(); }
public void A_single_json_configuration_file_is_loaded() { if (File.Exists("bob.json")) File.Delete("bob.json"); const string conf = @"{""my-key"": ""my-value""}"; File.AppendAllText("bob.json", conf); _binder = ConfigurationBinderFactory.New(x => { // a single json file x.AddJsonFile("bob.json"); }); }
public void A_configuration_object_is_bound() { const string json = @"{ Name: ""phatboyg"", Password: ""default""}"; var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); string commandLineText = "-password:really_long_one --secure"; _binder = ConfigurationBinderFactory.New(x => { // least specific to most specific // I assume that is reasonable x.AddJson(jsonStream); x.AddCommandLine(commandLineText); }); _configuration = _binder.Bind<IMyConfiguration>(); }
public static T Get <T>(this IConfiguration configuration) { return(ConfigurationBinder.Get <T>(configuration)); }
public DocumentDbFixture() { var appConfig = new AppConfiguration(); var path = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName; var configBuilder = new ConfigurationBuilder() .SetBasePath(path) .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); configuration = configBuilder; ConfigurationBinder.Bind(configuration, appConfig); var azureMediaServicesClient = AzureMediaServiceClient .CreateMediaServicesClientAsync(appConfig.AzureMediaServices).Result; var builder = new ContainerBuilder(); builder.Register <IAppConfiguration>(c => appConfig) .AsImplementedInterfaces() .AsSelf() .SingleInstance(); builder.Register(c => new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, DateFormatHandling = DateFormatHandling.IsoDateFormat, Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }).As <JsonSerializer>(); builder.Register <TelemetryClient>(c => new TelemetryClient()); //builder.Register<IAppConfiguration>(c => this.appConfig); //builder.Register<IdentityHelper>(c => new IdentityHelper(c.Resolve<IAppConfiguration>())) // .SingleInstance(); #region database builder.Register <DocumentDbUtil>(c => new DocumentDbUtil( endpointUrl: appConfig.AppSettings.CosmosdbEndpointUrl, primaryKey: appConfig.AppSettings.CosmosdbPrimaryKey, databaseName: appConfig.AppSettings.CosmosdbDatabaseName)); #endregion database #region cloudApis builder.Register <StorageCredentials>(c => new StorageCredentials( appConfig.AppSettings.StorageKeyName, appConfig.AppSettings.StorageKeyValue )).SingleInstance(); builder.Register <HttpClient>(c => { var client = new HttpClient(); client.DefaultRequestHeaders.Add( appConfig.AppSettings.ThumbnailServiceApiKeyName, appConfig.AppSettings.ThumbnailServiceApiKeyValue); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); return(client); }).Named <HttpClient>("ThumbnailCognitiveApiClient").SingleInstance(); builder.Register <StreamClient>(c => new StreamClient(appConfig.AppSettings.StreamAccessKey, appConfig.AppSettings.StreamSecret)); builder.Register <HttpClient>(c => { var client = new HttpClient { BaseAddress = new Uri(appConfig.AppSettings.FCMUrl) }; client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={appConfig.AppSettings.FCMApplicationId}"); client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={appConfig.AppSettings.FCMSenderId}"); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); return(client); }).Named <HttpClient>("FCMClient").SingleInstance(); // todo: Make this work with local storage builder.Register <BlobHelper>(c => new BlobHelper(appConfig.AppSettings.ImageUploadStorageFolder) ).SingleInstance(); #endregion cloudApis builder.Register <MapperConfiguration>(c => new MapperConfiguration(cfg => { cfg.AddProfile <FeedItemProfile>(); cfg.AddProfile <JunaUserProfile>(); cfg.AddProfile <ActivityProfile>(); })).SingleInstance().AutoActivate().AsSelf(); builder.Register(c => { var ctx = c.Resolve <IComponentContext>(); var config = ctx.Resolve <MapperConfiguration>(); return(config.CreateMapper(t => ctx.Resolve(t))); }).As <IMapper>(); #region Repository builder.Register <FeedItemRepository>(c => new FeedItemRepository( documentDbUtil: c.Resolve <DocumentDbUtil>(), collectionName: appConfig.AppSettings.SocialDataCollectionName, mapper: c.Resolve <IMapper>())); builder.Register <JunaUserRepository>(c => new JunaUserRepository( documentDbUtil: c.Resolve <DocumentDbUtil>(), collectionName: appConfig.AppSettings.SocialDataCollectionName, mapper: c.Resolve <IMapper>())); builder.Register <ActivityRepository>(c => new ActivityRepository( documentDbUtil: c.Resolve <DocumentDbUtil>(), collectionName: appConfig.AppSettings.SocialDataCollectionName, mapper: c.Resolve <IMapper>())); builder.Register <CommentsRepository>(c => new CommentsRepository( documentDbUtil: c.Resolve <DocumentDbUtil>(), collectionName: appConfig.AppSettings.SocialDataCollectionName, mapper: c.Resolve <IMapper>())); builder.Register <BoardRepository>(c => new BoardRepository( documentDbUtil: c.Resolve <DocumentDbUtil>(), collectionName: appConfig.AppSettings.SocialDataCollectionName, mapper: c.Resolve <IMapper>())); #endregion Repository #region Service builder.Register <JunaUserService>(c => new JunaUserService( c.Resolve <JunaUserRepository>(), c.Resolve <Stream.StreamClient>(), c.Resolve <ActivityRepository>())); builder.Register <FeedManagementService>(c => new FeedManagementService( c.Resolve <FeedItemRepository>(), c.Resolve <BoardRepository>(), c.Resolve <ActivityRepository>(), c.Resolve <JunaUserRepository>(), c.Resolve <ActivityManagementService>(), c.Resolve <FCMSenderService>(), c.Resolve <TelemetryClient>(), c.ResolveOptional <Stream.StreamClient>() )); builder.Register <ActivityManagementService>(c => new ActivityManagementService( c.Resolve <ActivityRepository>(), c.Resolve <BoardRepository>(), c.Resolve <FeedItemRepository>(), c.Resolve <JunaUserRepository>(), c.ResolveOptional <Stream.StreamClient>())); builder.Register <CommentsManagementService>(c => new CommentsManagementService( c.Resolve <CommentsRepository>(), c.Resolve <FeedItemRepository>(), c.ResolveOptional <Stream.StreamClient>() )); builder.Register <BoardManagementService>(c => new BoardManagementService( c.Resolve <BoardRepository>(), c.Resolve <ActivityRepository>(), c.Resolve <FeedItemRepository>(), c.Resolve <JunaUserRepository>(), c.ResolveOptional <Stream.StreamClient>() ) ); builder.Register <ModerationManagementService>( c => new ModerationManagementService( c.Resolve <ActivityRepository>(), c.Resolve <JunaUserRepository>(), c.Resolve <ActivityManagementService>(), c.ResolveOptional <Stream.StreamClient>() )); builder.Register <ContentUploadService>(c => new ContentUploadService( c.Resolve <FeedItemRepository>(), c.Resolve <ThumbnailService>(), c.Resolve <FCMSenderService>(), c.Resolve <StorageCredentials>(), c.Resolve <ActivityManagementService>(), c.Resolve <BoardRepository>(), c.Resolve <BlobHelper>(), c.ResolveOptional <Stream.StreamClient>() )); builder.Register <ThumbnailService>(c => new ThumbnailService( c.ResolveNamed <HttpClient>("ThumbnailCognitiveApiClient"), appConfig.AppSettings.ThumbnailServiceApiUrl, appConfig.AppSettings.ThumbnailWidth, appConfig.AppSettings.ThumbnailHeight, c.Resolve <StorageCredentials>(), c.Resolve <BlobHelper>(), appConfig.AzureMediaServices.ResourceGroup, appConfig.AzureMediaServices.AccountName, azureMediaServicesClient ) ); builder.Register <FCMSenderService>(c => new FCMSenderService( c.ResolveNamed <HttpClient>("FCMClient"), c.Resolve <TelemetryClient>() )); #endregion Service Container = builder.Build(); }
public void ConfigureServices(IServiceCollection services) { var provider = services.BuildServiceProvider(); // Options services.AddOptions(); // Settings var globalSettings = new GlobalSettings(); ConfigurationBinder.Bind(Configuration.GetSection("GlobalSettings"), globalSettings); services.AddSingleton(s => globalSettings); services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions")); services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); // Data Protection if (Environment.IsProduction()) { var dataProtectionCert = CoreHelpers.GetCertificate(globalSettings.DataProtection.CertificateThumbprint); var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString); services.AddDataProtection() .PersistKeysToAzureBlobStorage(storageAccount, "aspnet-dataprotection/keys.xml") .ProtectKeysWithCertificate(dataProtectionCert); } // Stripe Billing StripeConfiguration.SetApiKey(globalSettings.StripeApiKey); // Repositories services.AddSqlServerRepositories(); // Context services.AddScoped <CurrentContext>(); // Caching services.AddMemoryCache(); // Rate limiting services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); // IdentityServer var identityServerBuilder = services.AddIdentityServer(options => { options.Endpoints.EnableAuthorizeEndpoint = false; options.Endpoints.EnableIntrospectionEndpoint = false; options.Endpoints.EnableEndSessionEndpoint = false; options.Endpoints.EnableUserInfoEndpoint = false; options.Endpoints.EnableCheckSessionEndpoint = false; options.Endpoints.EnableTokenRevocationEndpoint = false; }) .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddInMemoryClients(Clients.GetClients()); services.AddTransient <ICorsPolicyService, AllowAllCorsPolicyService>(); if (Environment.IsProduction()) { var identityServerCert = CoreHelpers.GetCertificate(globalSettings.IdentityServer.CertificateThumbprint); identityServerBuilder.AddSigningCredential(identityServerCert); } else { identityServerBuilder.AddTemporarySigningCredential(); } services.AddScoped <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>(); services.AddScoped <IProfileService, ProfileService>(); services.AddSingleton <IPersistedGrantStore, PersistedGrantStore>(); // Identity services.AddTransient <ILookupNormalizer, LowerInvariantLookupNormalizer>(); services.AddJwtBearerIdentity(options => { options.User = new UserOptions { RequireUniqueEmail = true, AllowedUserNameCharacters = null // all }; options.Password = new PasswordOptions { RequireDigit = false, RequireLowercase = false, RequiredLength = 8, RequireNonAlphanumeric = false, RequireUppercase = false }; options.ClaimsIdentity = new ClaimsIdentityOptions { SecurityStampClaimType = "securitystamp", UserNameClaimType = ClaimTypes.Email }; options.Tokens.ChangeEmailTokenProvider = TokenOptions.DefaultEmailProvider; }, jwtBearerOptions => { jwtBearerOptions.Audience = "bitwarden"; jwtBearerOptions.Issuer = "bitwarden"; jwtBearerOptions.TokenLifetime = TimeSpan.FromDays(10 * 365); jwtBearerOptions.TwoFactorTokenLifetime = TimeSpan.FromMinutes(10); var keyBytes = Encoding.ASCII.GetBytes(globalSettings.JwtSigningKey); jwtBearerOptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256); }) .AddUserStore <UserStore>() .AddRoleStore <RoleStore>() .AddTokenProvider <AuthenticatorTokenProvider>(TwoFactorProviderType.Authenticator.ToString()) .AddTokenProvider <EmailTokenProvider <User> >(TokenOptions.DefaultEmailProvider); var jwtIdentityOptions = provider.GetRequiredService <IOptions <JwtBearerIdentityOptions> >().Value; services.AddAuthorization(config => { config.AddPolicy("Application", policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, "Bearer2"); policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.AuthenticationMethod); }); config.AddPolicy("TwoFactor", policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, "Bearer2"); policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.TwoFactorAuthenticationMethod); }); }); services.AddScoped <AuthenticatorTokenProvider>(); // Services services.AddBaseServices(); services.AddDefaultServices(); // Cors services.AddCors(config => { config.AddPolicy("All", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().SetPreflightMaxAge(TimeSpan.FromDays(1))); }); // MVC services.AddMvc(config => { config.Filters.Add(new ExceptionHandlerFilterAttribute()); config.Filters.Add(new ModelStateValidationFilterAttribute()); // Allow JSON of content type "text/plain" to avoid cors preflight var textPlainMediaType = MediaTypeHeaderValue.Parse("text/plain"); foreach (var jsonFormatter in config.InputFormatters.OfType <JsonInputFormatter>()) { jsonFormatter.SupportedMediaTypes.Add(textPlainMediaType); } }).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); }
public void Using_the_configuration_command_line_value_provider() { _binder = ConfigurationBinderFactory.New(x => { x.AddCommandLine("-name:dru"); }); }
protected Orchestrator() { var configProvider = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); _config = new OrchestratorConfiguration(); ConfigurationBinder.Bind(configProvider, _config); if (_config.Databases?.Length == 0) { throw new InvalidOperationException("Must be at least one database configured!"); } foreach (var serverInfo in _config.LocalRavenServers ?? Enumerable.Empty <ServerInfo>()) { RaiseServer(serverInfo); } EmbeddedServer.Instance.StartServer(new ServerOptions { ServerUrl = "http://0.0.0.0:8091", CommandLineArgs = new List <string> { " --Security.UnsecuredAccessAllowed=PublicNetwork ", " --Setup.Mode=None ", " --PublicServerUrl=http://10.0.0.69:8091 " } }); _reportingDocumentStore = EmbeddedServer.Instance.GetDocumentStore(new DatabaseOptions(OrchestratorDatabaseName)); _reportingDocumentStore.Initialize(); new LatestTestByName().Execute(_reportingDocumentStore); if (_config.Clusters == null || _config.Clusters.Length == 0) { throw new InvalidOperationException("Must be at least one RavenDB cluster info configured!"); } _container.Register(Classes.FromAssembly(typeof(Orchestrator).Assembly) .BasedOn <ITestConfigSelectorStrategy>() .WithServiceAllInterfaces() .LifestyleSingleton()); _configSelectorStrategies = _container.ResolveAll <ITestConfigSelectorStrategy>(); if (_configSelectorStrategies.Length == 0) { throw new InvalidOperationException("Something really bad happened... there is no config selector strategies implemented!"); } foreach (var strategy in _configSelectorStrategies) { strategy.Initialize(_config); } //TODO: make this choice persistent? (via the embedded RavenDB instance) _currentConfigSelectorStrategy = _configSelectorStrategies[0]; foreach (var clusterInfo in _config.Clusters ?? Enumerable.Empty <ClusterInfo>()) { clusterInfo.Urls = clusterInfo.Urls.Select(PrepareUrlForDocumentStore).ToArray(); var store = new DocumentStore { Database = _config.Databases?[0], Urls = clusterInfo.Urls, //Certificate = TODO: finish this }; store.Initialize(); _clusterDocumentStores.Add(clusterInfo, store); foreach (var database in _config.Databases ?? Enumerable.Empty <string>()) { EnsureDatabaseExists(database, store); } } }
public void Initalize(IConfiguration configuration) { _scriptOptions = new ScriptOptions(); ConfigurationBinder.Bind(configuration, _scriptOptions); _logger.LogInformation($"Detecting CSX files in '{_env.TargetDirectory}'."); // Nothing to do if there are no CSX files var allCsxFiles = _fileSystemHelper.GetFiles("**/*.csx").ToArray(); if (allCsxFiles.Length == 0) { _logger.LogInformation("Could not find any CSX files"); return; } _logger.LogInformation($"Found {allCsxFiles.Length} CSX files."); var currentDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies(); // explicitly inherit scripting library references to all global script object (CommandLineScriptGlobals) to be recognized var inheritedCompileLibraries = currentDomainAssemblies.Where(x => x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase)).ToList(); // explicitly include System.ValueTuple inheritedCompileLibraries.AddRange(currentDomainAssemblies.Where(x => x.FullName.StartsWith("system.valuetuple", StringComparison.OrdinalIgnoreCase))); _compilationDependencies = TryGetCompilationDependencies(); var isDesktopClr = true; // if we have no compilation dependencies // we will assume desktop framework // and add default CLR references // same applies for having a context that is not a .NET Core app if (!_compilationDependencies.Any()) { _logger.LogInformation("Unable to find dependency context for CSX files. Will default to non-context usage (Desktop CLR scripts)."); AddDefaultClrMetadataReferences(_commonReferences); } else { isDesktopClr = false; HashSet <string> loadedFiles = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var compilationAssembly in _compilationDependencies.SelectMany(cd => cd.AssemblyPaths).Distinct()) { if (loadedFiles.Add(Path.GetFileName(compilationAssembly))) { _logger.LogDebug("Discovered script compilation assembly reference: " + compilationAssembly); AddMetadataReference(_commonReferences, compilationAssembly); } } } // inject all inherited assemblies foreach (var inheritedCompileLib in inheritedCompileLibraries) { _logger.LogDebug("Adding implicit reference: " + inheritedCompileLib); AddMetadataReference(_commonReferences, inheritedCompileLib.Location); } _scriptHelper = new ScriptHelper(_scriptOptions, _env, _loggerFactory, isDesktopClr); // Each .CSX file becomes an entry point for it's own project // Every #loaded file will be part of the project too foreach (var csxPath in allCsxFiles) { AddToWorkspace(csxPath); } // Watch CSX files in order to add/remove them in workspace _fileSystemWatcher.Watch(CsxExtension, OnCsxFileChanged); }
/// <summary> /// 获取Json配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileDir">文件目录(格式:D:\JsonConfigs)</param> /// <param name="fileName">文件名称(格式:xxx.json)</param> /// <param name="key">配置文件的Key(格式:xxx:yyy,注意中间使用':'分割)</param> /// <returns></returns> public static T GetValue <T>(string fileDir, string fileName, string key) { IConfiguration configuration = GetJsonConfiguration(fileDir, fileName); return(ConfigurationBinder.GetValue <T>(configuration, key)); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "BasicRedisChat", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); ConnectionMultiplexer redis = null; string redisConnectionUrl = null; { var redisSettings = new RedisSettings(); ConfigurationBinder.Bind(Configuration.GetSection("RedisSettings"), redisSettings); if (redisSettings != null) { redisConnectionUrl = $"{redisSettings.Url}:{redisSettings.Port},password={redisSettings.Password}"; } else { var redisEndpointUrl = (Environment.GetEnvironmentVariable("REDIS_ENDPOINT_URL") ?? "127.0.0.1:6379").Split(':'); var redisHost = redisEndpointUrl[0]; var redisPort = redisEndpointUrl[1]; var redisPassword = Environment.GetEnvironmentVariable("REDIS_PASSWORD"); if (redisPassword != null) { redisConnectionUrl = $"{redisHost},password={redisPassword}"; } else { redisConnectionUrl = $"{redisHost}:{redisPort}"; } } redis = ConnectionMultiplexer.Connect(redisConnectionUrl); services.AddSingleton <IConnectionMultiplexer>(redis); } services .AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "DataProtectionKeys"); services.AddStackExchangeRedisCache(option => { option.Configuration = redisConnectionUrl; option.InstanceName = "RedisInstance"; }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.Name = "AppTest"; }); Assembly.Load("BasicRedisChat.BLL"); ServiceAutoConfig.Configure(services); services.AddAutoMapper(typeof(Startup)); services.AddHttpContextAccessor(); services.AddSingleton <IFileProvider>(new PhysicalFileProvider(Directory.GetCurrentDirectory())); services.AddSignalR(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddCors(); //services.AddControllers(); //services.AddDbContext<ApplicationDbContext>(options => //{ // options.UseLazyLoadingProxies(); // options.UseSqlServer( // Configuration.GetConnectionString("DefaultConnection")); //}); //services.AddIdentity<User, IdentityRole>(options => // { // options.Password.RequireDigit = false; // options.Password.RequireLowercase = false; // options.Password.RequireNonAlphanumeric = false; // options.Password.RequireUppercase = false; // options.Password.RequiredLength = 1; // }) // .AddDefaultTokenProviders() // .AddEntityFrameworkStores<ApplicationDbContext>(); //var mappingConfig = new MapperConfiguration(mc => // mc.AddProfile(new MappingProfile()) //); //// configure strongly typed settings objects //var appSettingsSection = Configuration.GetSection("AppSettings"); ////services.Configure<AppSettings>(appSettingsSection); //// configure jwt authentication //var appSettings = appSettingsSection.Get<AppSettings>(); //var key = Encoding.ASCII.GetBytes(appSettings.Secret); //services.AddAuthentication(x => // { // x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; // }) // .AddJwtBearer(x => // { // x.RequireHttpsMetadata = false; // x.SaveToken = true; // x.TokenValidationParameters = new TokenValidationParameters // { // ValidateIssuerSigningKey = true, // IssuerSigningKey = new SymmetricSecurityKey(key), // ValidateIssuer = false, // ValidateAudience = false // }; // }); var appSettings = Configuration.GetSection("AppSettings"); AppSettings parsedSettings = new AppSettings(); ConfigurationBinder.Bind(appSettings, parsedSettings); services.Configure <AppSettings>(appSettings); services.AddMemoryCache(); DataServicesConfig.ConfigureDataServices(services, Configuration, parsedSettings); WebServicesConfig.ConfigureWebServices(services); AuthServiceConfig.ConfigJwtAuthentication(services, parsedSettings, Configuration["JWTKey"]); services.AddScoped <IPageService, PageService>(); }
private void Reload() { _logger.LogInformation("Reloading settings since they changed"); ConfigurationBinder.Bind(_config, this.Site); _config.GetReloadToken().RegisterChangeCallback(x => this.Reload(), null); }
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration); var provider = services.BuildServiceProvider(); // Options services.AddOptions(); // Settings var globalSettings = new GlobalSettings(); ConfigurationBinder.Bind(Configuration.GetSection("GlobalSettings"), globalSettings); services.AddSingleton(s => globalSettings); services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions")); services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); // Repositories services.AddSingleton <IUserRepository, Repos.UserRepository>(); services.AddSingleton <ICipherRepository, Repos.CipherRepository>(); services.AddSingleton <IDeviceRepository, Repos.DeviceRepository>(); // Context services.AddScoped <CurrentContext>(); // Caching services.AddMemoryCache(); // Rate limiting services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); // Identity services.AddTransient <ILookupNormalizer, LowerInvariantLookupNormalizer>(); services.AddJwtBearerIdentity(options => { options.User = new UserOptions { RequireUniqueEmail = true, AllowedUserNameCharacters = null // all }; options.Password = new PasswordOptions { RequireDigit = false, RequireLowercase = false, RequiredLength = 8, RequireNonAlphanumeric = false, RequireUppercase = false }; options.ClaimsIdentity = new ClaimsIdentityOptions { SecurityStampClaimType = "securitystamp", UserNameClaimType = ClaimTypes.Email }; options.Tokens.ChangeEmailTokenProvider = TokenOptions.DefaultEmailProvider; }, jwtBearerOptions => { jwtBearerOptions.Audience = "bitwarden"; jwtBearerOptions.Issuer = "bitwarden"; jwtBearerOptions.TokenLifetime = TimeSpan.FromDays(10 * 365); jwtBearerOptions.TwoFactorTokenLifetime = TimeSpan.FromMinutes(10); var keyBytes = Encoding.ASCII.GetBytes(globalSettings.JwtSigningKey); jwtBearerOptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256); }) .AddUserStore <UserStore>() .AddRoleStore <RoleStore>() .AddTokenProvider <AuthenticatorTokenProvider>("Authenticator") .AddTokenProvider <EmailTokenProvider <User> >(TokenOptions.DefaultEmailProvider); var jwtIdentityOptions = provider.GetRequiredService <IOptions <JwtBearerIdentityOptions> >().Value; services.AddAuthorization(config => { config.AddPolicy("Application", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.AuthenticationMethod).Build()); config.AddPolicy("TwoFactor", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.TwoFactorAuthenticationMethod).Build()); }); services.AddScoped <AuthenticatorTokenProvider>(); // Services services.AddSingleton <IMailService, MailService>(); services.AddSingleton <ICipherService, CipherService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IPushService, PushService>(); services.AddScoped <IDeviceService, DeviceService>(); // Cors services.AddCors(config => { config.AddPolicy("All", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().SetPreflightMaxAge(TimeSpan.FromDays(1))); }); // MVC services.AddMvc(config => { config.Filters.Add(new ExceptionHandlerFilterAttribute()); config.Filters.Add(new ModelStateValidationFilterAttribute()); // Allow JSON of content type "text/plain" to avoid cors preflight var textPlainMediaType = MediaTypeHeaderValue.Parse("text/plain"); foreach (var jsonFormatter in config.InputFormatters.OfType <JsonInputFormatter>()) { jsonFormatter.SupportedMediaTypes.Add(textPlainMediaType); } }).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());; }
public static ILoggingBuilder AddSerilog( this ILoggingBuilder builder, WebHostBuilderContext context, Func <LogEvent, bool> filter = null) { if (context.HostingEnvironment.IsDevelopment()) { return(builder); } bool inclusionPredicate(LogEvent e) { if (filter == null) { return(true); } var eventId = e.Properties.ContainsKey("EventId") ? e.Properties["EventId"].ToString() : null; if (eventId?.Contains(Constants.BypassFiltersEventId.ToString()) ?? false) { return(true); } return(filter(e)); } var globalSettings = new GlobalSettings(); ConfigurationBinder.Bind(context.Configuration.GetSection("GlobalSettings"), globalSettings); var config = new LoggerConfiguration() .Enrich.FromLogContext() .Filter.ByIncludingOnly(inclusionPredicate); if (CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Uri) && CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Key)) { config.WriteTo.AzureDocumentDB(new Uri(globalSettings.DocumentDb.Uri), globalSettings.DocumentDb.Key, timeToLive: TimeSpan.FromDays(7)) .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } else if (CoreHelpers.SettingHasValue(globalSettings?.Sentry.Dsn)) { config.WriteTo.Sentry(globalSettings.Sentry.Dsn) .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName) .Destructure.With <HttpContextDestructingPolicy>() .Filter.ByExcluding(e => e.Exception?.CheckIfCaptured() == true); } else if (CoreHelpers.SettingHasValue(globalSettings.LogDirectory)) { if (globalSettings.LogRollBySizeLimit.HasValue) { config.WriteTo.File($"{globalSettings.LogDirectory}/{globalSettings.ProjectName}/log.txt", rollOnFileSizeLimit: true, fileSizeLimitBytes: globalSettings.LogRollBySizeLimit); } else { config.WriteTo .RollingFile($"{globalSettings.LogDirectory}/{globalSettings.ProjectName}/{{Date}}.txt"); } config .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } var serilog = config.CreateLogger(); builder.AddSerilog(serilog); return(builder); }
// http://stackoverflow.com/questions/16658915/reactive-extensions-concurrency-within-the-subscriber // https://social.msdn.microsoft.com/Forums/en-US/6ef0caba-709d-450a-830d-8fc80f0a815d/the-rx-serialization-guarantee?forum=rx private static async Task RabbitMqObserver(ILogger logger, CancellationToken cancellationToken = default(CancellationToken)) { logger.LogInformation("ConcurrencyLevel: {concurrencyLevel}", ConcurrencyLevel); Sleep(logger, TimeSpan.FromSeconds(10), "to let RabbitMQ start up"); var config = ConfigBuilder.Build(); var settings = new MessageQueueSettings(); ConfigurationBinder.Bind(config.GetSection("MessageQueue"), settings); using (var context = new RabbitContext(settings, logger)) { var publisher = Task.Run(async() => { do { context.Publish(new Bogus.Faker().Lorem.Sentence(20)); await Task.Delay(TimeSpan.FromMilliseconds(100)); } while (cancellationToken.IsCancellationRequested == false); }); var subscriber = Task.Run(async() => { Action <IMessage <string> > onNextImpl = message => { logger.LogDebug("Started handling {messageId}", message.Id); try { Thread.Sleep(3000); Console.WriteLine(message.GetContent()); message.CompleteAsync().Wait(); } catch (Exception ex) { logger.LogError(0, ex, "Error while handling {messageId}", message.Id); message.AbandonAsync().Wait(); } }; // Action to invoke for each element in the observable sequence. Action <IMessage <string> > onNext = message => Task.Run(() => onNextImpl(message)); // Action to invoke upon exceptional termination of the observable sequence Action <Exception> onError = ex => { logger.LogError(0, ex, "Exceptional termination of the observable sequence"); }; // Action to invoke upon graceful termination of the observable sequence. Action onCompleted = () => { logger.LogDebug("Graceful termination of the observable sequence"); }; using (var subscription = context.CreateSubscription()) using (subscription.Observable.ObserveOn(NewThreadScheduler.Default).Subscribe(onNext, onError, onCompleted)) { await SleepTillCancelledAsync(cancellationToken); } }); await Task.WhenAll(publisher, subscriber); } }
public void Initalize(IConfiguration configuration) { _options = new DnxOptions(); ConfigurationBinder.Bind(configuration, _options); _dnxPaths = new DnxPaths(_env, _options, _loggerFactory); _packagesRestoreTool = new PackagesRestoreTool(_options, _emitter, _context, _dnxPaths);; _designTimeHostManager = new DesignTimeHostManager(_loggerFactory, _dnxPaths); var runtimePath = _dnxPaths.RuntimePath; _context.RuntimePath = runtimePath.Value; _context.Options = _options; if (!ScanForProjects()) { // No DNX projects found so do nothing _logger.LogInformation("No project.json based projects found"); return; } if (_context.RuntimePath == null) { // There is no default dnx found so do nothing _logger.LogInformation("No default runtime found"); _emitter.Emit(EventTypes.Error, runtimePath.Error); return; } var wh = new ManualResetEventSlim(); _designTimeHostManager.Start(_context.HostId, port => { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Loopback, port)); var networkStream = new NetworkStream(socket); _logger.LogInformation("Connected"); _context.DesignTimeHostPort = port; _context.Connection = new ProcessingQueue(networkStream, _logger); _context.Connection.OnReceive += m => { var project = _context.Projects[m.ContextId]; if (m.MessageType == "ProjectInformation") { var val = m.Payload.ToObject <ProjectMessage>(); project.Name = val.Name; project.GlobalJsonPath = val.GlobalJsonPath; project.Configurations = val.Configurations; project.Commands = val.Commands; project.ProjectSearchPaths = val.ProjectSearchPaths; this._emitter.Emit(EventTypes.ProjectChanged, new ProjectInformationResponse() { { nameof(DnxProject), new DnxProject(project) } }); var unprocessed = project.ProjectsByFramework.Keys.ToList(); foreach (var frameworkData in val.Frameworks) { unprocessed.Remove(frameworkData.FrameworkName); var frameworkProject = project.ProjectsByFramework.GetOrAdd(frameworkData.FrameworkName, framework => { return(new FrameworkProject(project, frameworkData)); }); var id = frameworkProject.ProjectId; if (_workspace.CurrentSolution.ContainsProject(id)) { continue; } else { var projectInfo = ProjectInfo.Create( id, VersionStamp.Create(), val.Name + "+" + frameworkData.ShortName, val.Name, LanguageNames.CSharp, project.Path); _workspace.AddProject(projectInfo); _context.WorkspaceMapping[id] = frameworkProject; } lock (frameworkProject.PendingProjectReferences) { var reference = new Microsoft.CodeAnalysis.ProjectReference(id); foreach (var referenceId in frameworkProject.PendingProjectReferences) { _workspace.AddProjectReference(referenceId, reference); } frameworkProject.PendingProjectReferences.Clear(); } } // Remove old projects foreach (var frameworkName in unprocessed) { FrameworkProject frameworkProject; project.ProjectsByFramework.TryRemove(frameworkName, out frameworkProject); _workspace.RemoveProject(frameworkProject.ProjectId); } } // This is where we can handle messages and update the // language service else if (m.MessageType == "References") { // References as well as the dependency graph information var val = m.Payload.ToObject <ReferencesMessage>(); var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName]; var projectId = frameworkProject.ProjectId; var metadataReferences = new List <MetadataReference>(); var projectReferences = new List <Microsoft.CodeAnalysis.ProjectReference>(); var removedFileReferences = frameworkProject.FileReferences.ToDictionary(p => p.Key, p => p.Value); var removedRawReferences = frameworkProject.RawReferences.ToDictionary(p => p.Key, p => p.Value); var removedProjectReferences = frameworkProject.ProjectReferences.ToDictionary(p => p.Key, p => p.Value); foreach (var file in val.FileReferences) { if (removedFileReferences.Remove(file)) { continue; } var metadataReference = _metadataFileReferenceCache.GetMetadataReference(file); frameworkProject.FileReferences[file] = metadataReference; metadataReferences.Add(metadataReference); } foreach (var rawReference in val.RawReferences) { if (removedRawReferences.Remove(rawReference.Key)) { continue; } var metadataReference = MetadataReference.CreateFromImage(rawReference.Value); frameworkProject.RawReferences[rawReference.Key] = metadataReference; metadataReferences.Add(metadataReference); } foreach (var projectReference in val.ProjectReferences) { if (removedProjectReferences.Remove(projectReference.Path)) { continue; } int projectReferenceContextId; if (!_context.ProjectContextMapping.TryGetValue(projectReference.Path, out projectReferenceContextId)) { projectReferenceContextId = AddProject(projectReference.Path); } var referencedProject = _context.Projects[projectReferenceContextId]; var referencedFrameworkProject = referencedProject.ProjectsByFramework.GetOrAdd(projectReference.Framework.FrameworkName, framework => { return(new FrameworkProject(referencedProject, projectReference.Framework)); }); var projectReferenceId = referencedFrameworkProject.ProjectId; if (_workspace.CurrentSolution.ContainsProject(projectReferenceId)) { projectReferences.Add(new Microsoft.CodeAnalysis.ProjectReference(projectReferenceId)); } else { lock (referencedFrameworkProject.PendingProjectReferences) { referencedFrameworkProject.PendingProjectReferences.Add(projectId); } } referencedFrameworkProject.ProjectDependeees[project.Path] = projectId; frameworkProject.ProjectReferences[projectReference.Path] = projectReferenceId; } foreach (var reference in metadataReferences) { _workspace.AddMetadataReference(projectId, reference); } foreach (var projectReference in projectReferences) { _workspace.AddProjectReference(projectId, projectReference); } foreach (var pair in removedProjectReferences) { _workspace.RemoveProjectReference(projectId, new Microsoft.CodeAnalysis.ProjectReference(pair.Value)); frameworkProject.ProjectReferences.Remove(pair.Key); // TODO: Update the dependee's list } foreach (var pair in removedFileReferences) { _workspace.RemoveMetadataReference(projectId, pair.Value); frameworkProject.FileReferences.Remove(pair.Key); } foreach (var pair in removedRawReferences) { _workspace.RemoveMetadataReference(projectId, pair.Value); frameworkProject.RawReferences.Remove(pair.Key); } } else if (m.MessageType == "Dependencies") { var val = m.Payload.ToObject <DependenciesMessage>(); var unresolvedDependencies = val.Dependencies.Values .Where(dep => dep.Type == "Unresolved"); if (unresolvedDependencies.Any()) { _logger.LogInformation("Project {0} has these unresolved references: {1}", project.Path, string.Join(", ", unresolvedDependencies.Select(d => d.Name))); _emitter.Emit(EventTypes.UnresolvedDependencies, new UnresolvedDependenciesMessage() { FileName = project.Path, UnresolvedDependencies = unresolvedDependencies.Select(d => new PackageDependency() { Name = d.Name, Version = d.Version }) }); _packagesRestoreTool.Run(project); } } else if (m.MessageType == "CompilerOptions") { // Configuration and compiler options var val = m.Payload.ToObject <CompilationOptionsMessage>(); var projectId = project.ProjectsByFramework[val.Framework.FrameworkName].ProjectId; var options = val.CompilationOptions.CompilationOptions; var specificDiagnosticOptions = options.SpecificDiagnosticOptions .ToDictionary(p => p.Key, p => (ReportDiagnostic)p.Value); var csharpOptions = new CSharpCompilationOptions( outputKind: (OutputKind)options.OutputKind, optimizationLevel: (OptimizationLevel)options.OptimizationLevel, platform: (Platform)options.Platform, generalDiagnosticOption: (ReportDiagnostic)options.GeneralDiagnosticOption, warningLevel: options.WarningLevel, allowUnsafe: options.AllowUnsafe, concurrentBuild: options.ConcurrentBuild, specificDiagnosticOptions: specificDiagnosticOptions ); var parseOptions = new CSharpParseOptions(val.CompilationOptions.LanguageVersion, preprocessorSymbols: val.CompilationOptions.Defines); _workspace.SetCompilationOptions(projectId, csharpOptions); _workspace.SetParseOptions(projectId, parseOptions); } else if (m.MessageType == "Sources") { // The sources to feed to the language service var val = m.Payload.ToObject <SourcesMessage>(); project.SourceFiles = val.Files .Where(fileName => Path.GetExtension(fileName) == ".cs") .ToList(); var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName]; var projectId = frameworkProject.ProjectId; var unprocessed = new HashSet <string>(frameworkProject.Documents.Keys); foreach (var file in project.SourceFiles) { if (unprocessed.Remove(file)) { continue; } using (var stream = File.OpenRead(file)) { var sourceText = SourceText.From(stream, encoding: Encoding.UTF8); var id = DocumentId.CreateNewId(projectId); var version = VersionStamp.Create(); frameworkProject.Documents[file] = id; var loader = TextLoader.From(TextAndVersion.Create(sourceText, version)); _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader)); } } foreach (var file in unprocessed) { var docId = frameworkProject.Documents[file]; frameworkProject.Documents.Remove(file); _workspace.RemoveDocument(docId); } frameworkProject.Loaded = true; } else if (m.MessageType == "Error") { var val = m.Payload.ToObject <Microsoft.Framework.DesignTimeHost.Models.OutgoingMessages.ErrorMessage>(); _logger.LogError(val.Message); } if (project.ProjectsByFramework.Values.All(p => p.Loaded)) { wh.Set(); } }; // Start the message channel _context.Connection.Start(); // Initialize the DNX projects Initialize(); }); wh.Wait(); }
public static T GetSection <T>(this IConfiguration configuration, string key) { return(ConfigurationBinder.Get <T>(configuration.GetSection(key))); }
/// <summary> /// (internal for tests only) /// Creates an instance. /// </summary> internal static object CreateInstanceInternal(Type type, IDictionary <string, string> stringArgs, params object[] paramArgs) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (paramArgs == null) { throw new ArgumentNullException(nameof(paramArgs)); } // fast: use the empty ctor if no args (will throw if it does not exist) if ((stringArgs == null || stringArgs.Count == 0) && paramArgs.Length == 0) { return(Activator.CreateInstance(type)); } var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public) .OrderByDescending(x => x.GetParameters().Length); List <object> args = null; foreach (var ctor in ctors) { var parameters = ctor.GetParameters(); if (parameters.Length == 0) { return(Activator.CreateInstance(type)); } args ??= new List <object>(); args.Clear(); var match = true; foreach (var parameter in parameters) { // ReSharper disable once UseMethodIsInstanceOfType var objectArg = paramArgs.FirstOrDefault(x => parameter.ParameterType.IsAssignableFrom(x.GetType())); if (objectArg != null) { args.Add(objectArg); continue; } if (stringArgs != null && stringArgs.TryGetValue(parameter.Name, out var stringArg) && ConfigurationBinder.TryConvertValue(parameter.ParameterType, stringArg, "", out var value, out _)) { args.Add(value); continue; } match = false; break; } if (match) { return(ctor.Invoke(args.ToArray())); } } // we know this throw - but then the exceptions are consistent return(Activator.CreateInstance(type)); }
/// <summary> /// ConfigureServices is where you register dependencies. This gets called by the runtime /// before the Configure method, below. /// </summary> /// <param name="services">Specifies the contract for a collection of service descriptors.</param> /// <returns>Un IServiceProvider.</returns> public IServiceProvider ConfigureServices(IServiceCollection services) { // Add services to the collection. IMvcBuilder mvcBuilder = services.AddMvc(); // Configura el manejador global de excepciones. services.AddSingleton <GlobalExceptionFilter>(); // Setup global exception filters. mvcBuilder.AddMvcOptions( options => { FilterCollection filters = options.Filters; ServiceFilterAttribute exceptionFilter = new ServiceFilterAttribute(typeof(GlobalExceptionFilter)); filters.Add(exceptionFilter); // ServiceFilterAttribute validationFilter = new ServiceFilterAttribute(typeof(ValidateModelFilter)); filters.Add(typeof(ValidateModelFilter)); }); // Doc: https://github.com/domaindrivendev/Swashbuckle.AspNetCore services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Training.Persona.Api", Version = "v1" }); c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Training.Persona.Api.xml")); c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Training.Persona.Entities.xml")); c.DescribeAllEnumsAsStrings(); c.IgnoreObsoleteActions(); c.OperationFilter <SwaggerGenResponseFilter>(); }); // Create the container builder. ContainerBuilder builder = new ContainerBuilder(); // Register dependencies, populate the services from the collection, and build the container. builder.Populate(services); // Registra la configuración (appsettings.json). builder.RegisterInstance(this.Configuration).AsImplementedInterfaces().SingleInstance(); builder.RegisterModule <Persona.Ioc.PersonaModule>(); // Registra y mapea los Settings (ConnectionStrings). builder.Register( c => { // Resuelve el ConfigurationRoot. IConfigurationRoot configurationRoot = c.Resolve <IConfigurationRoot>(); // Obtiene la sección del .json de settings. IConfigurationSection section = configurationRoot.GetSection("ConnectionStrings"); // Mapea la sección del .json a la clase. Apollo.NetCore.Core.Settings.ConnectionStrings connStr = new Apollo.NetCore.Core.Settings.ConnectionStrings(); ConfigurationBinder.Bind(section, connStr); return(connStr); }).As <Apollo.NetCore.Core.Settings.ConnectionStrings>() .SingleInstance(); this.ApplicationContainer = builder.Build(); // Create the IServiceProvider based on the container. return(new AutofacServiceProvider(this.ApplicationContainer)); }
/// <summary> /// Initializes a new instance of the <see cref="ControllerBase"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public ControllerBase(IConfigurationRoot configuration) { m_Settings = new AppSettings(); ConfigurationBinder.Bind(configuration.GetSection(AppSettingsSectionName), m_Settings); m_Configuration = configuration; }
public void Initalize(IConfiguration configuration) { _options = new MSBuildOptions(); ConfigurationBinder.Bind(configuration, _options); if (_options.WaitForDebugger) { Console.WriteLine($"Attach to process {System.Diagnostics.Process.GetCurrentProcess().Id}"); while (!System.Diagnostics.Debugger.IsAttached) { System.Threading.Thread.Sleep(100); } } var solutionFilePath = _env.SolutionFilePath; if (string.IsNullOrEmpty(solutionFilePath)) { var solutions = Directory.GetFiles(_env.Path, "*.sln"); var result = SolutionPicker.ChooseSolution(_env.Path, solutions); if (result.Message != null) { _logger.LogInformation(result.Message); } if (result.Solution == null) { return; } solutionFilePath = result.Solution; } SolutionFile solutionFile = null; _context.SolutionPath = solutionFilePath; using (var stream = File.OpenRead(solutionFilePath)) { using (var reader = new StreamReader(stream)) { solutionFile = SolutionFile.Parse(reader); } } _logger.LogInformation($"Detecting projects in '{solutionFilePath}'."); foreach (var block in solutionFile.ProjectBlocks) { if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid)) { if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid) { _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath); continue; } } if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid)) { continue; } var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar)))); _logger.LogInformation($"Loading project from '{projectFilePath}'."); var projectFileInfo = CreateProject(projectFilePath); if (projectFileInfo == null) { continue; } var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind); compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (projectFileInfo.AllowUnsafe) { compilationOptions = compilationOptions.WithAllowUnsafe(true); } if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile)) { var keyFile = Path.Combine(projectFileInfo.ProjectDirectory, projectFileInfo.AssemblyOriginatorKeyFile); compilationOptions = compilationOptions.WithStrongNameProvider(new DesktopStrongNameProvider()) .WithCryptoKeyFile(keyFile); } if (projectFileInfo.GenerateXmlDocumentation) { compilationOptions = compilationOptions.WithXmlReferenceResolver(XmlFileResolver.Default); } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name), VersionStamp.Create(), projectFileInfo.Name, projectFileInfo.AssemblyName, LanguageNames.CSharp, projectFileInfo.ProjectFilePath, compilationOptions: compilationOptions); _workspace.AddProject(projectInfo); projectFileInfo.WorkspaceId = projectInfo.Id; _context.Projects[projectFileInfo.ProjectFilePath] = projectFileInfo; _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id; _watcher.Watch(projectFilePath, OnProjectChanged); } foreach (var projectFileInfo in _context.Projects.Values) { UpdateProject(projectFileInfo); } }
public static IHostBuilder Create(IConfiguration configuration, bool runAsWindowsService, ILogger logger) { var builder = new HostBuilder(); var serverOptions = new OakproxyServerOptions(); serverOptions.Configure(configuration.GetSection("Server")); var proxyOptions = ConfigurationBinder.Get <ProxyOptions>(configuration); if (!OptionsAreValid(serverOptions, logger, "Server") || !OptionsAreValid(proxyOptions, logger)) { return(null); } var subsystemConfiguration = ConfigurationBinder.Get <HostingSubsystemConfiguration>(configuration.GetSection("Configuration"), binderOptions => binderOptions.BindNonPublicProperties = true) ?? HostingSubsystemConfiguration.Empty(); builder .UseContentRoot(Program.GetExecutableDirectory()) .ConfigureHostConfiguration(builder => builder.AddConfiguration(subsystemConfiguration.Host)); if (runAsWindowsService) { builder.UseWindowsService(); } builder .ConfigureAppConfiguration(builder => builder.AddConfiguration(configuration)) .ConfigureLogging((hostBuilderContext, loggingBuilder) => { if (subsystemConfiguration.Logging.Exists()) { loggingBuilder.AddConfiguration(subsystemConfiguration.Logging); } else { loggingBuilder.AddFilter(null, serverOptions.LogLevelInternal); } if (runAsWindowsService) { loggingBuilder.AddProvider(new DeferringLoggerProvider(new EventLogLoggerProvider(new EventLogSettings { SourceName = "OAKProxy" }))); } else { loggingBuilder.AddConsole(); } }) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .ConfigureServices((context, services) => { services.AddOptions <ProxyOptions>() .Bind(configuration) .ValidateDataAnnotations(); services.AddSingleton(Options.Create(serverOptions)); if (!String.IsNullOrWhiteSpace(serverOptions.ApplicationInsightsKey)) { services.AddApplicationInsightsTelemetry(options => { options.InstrumentationKey = serverOptions.ApplicationInsightsKey; subsystemConfiguration.ApplicationInsights.Bind(options); }); services.AddApplicationInsightsTelemetryProcessor <OakproxyTelemetryProcessor>(); } services.AddTransient <IStartupFilter, HostingPipelineStartup>(); if (serverOptions.UseForwardedHeaders || serverOptions.UseAzureApplicationGateway) { services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); subsystemConfiguration.ForwardedHeaders.Bind(options); if (serverOptions.UseAzureApplicationGateway) { options.ForwardedHostHeaderName = "X-Original-Host"; } }); } if (serverOptions.KeyManagement != null) { var dataProtectionBuilder = services.AddDataProtection(); var kmOptions = serverOptions.KeyManagement; kmOptions.LoadCertificates(configuration.GetSection(ConfigurationPath.Combine("Server", "KeyManagement"))); if (!String.IsNullOrEmpty(kmOptions.StoreToFilePath)) { var directoryInfo = new DirectoryInfo(kmOptions.StoreToFilePath); if (!directoryInfo.Exists) { throw new DirectoryNotFoundException("The specified key storage directory does not exist."); } dataProtectionBuilder.PersistKeysToFileSystem(directoryInfo); } else if (!String.IsNullOrEmpty(kmOptions.StoreToBlobContainer)) { var blobUri = new Uri(kmOptions.StoreToBlobContainer); if (String.IsNullOrEmpty(blobUri.Query)) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var tokenAndFrequency = StorageTokenRenewerAsync(azureServiceTokenProvider, CancellationToken.None) .GetAwaiter().GetResult(); TokenCredential tokenCredential = new TokenCredential(tokenAndFrequency.Token, StorageTokenRenewerAsync, azureServiceTokenProvider, tokenAndFrequency.Frequency.Value); var storageCredentials = new StorageCredentials(tokenCredential); var cloudBlockBlob = new CloudBlockBlob(blobUri, storageCredentials); dataProtectionBuilder.PersistKeysToAzureBlobStorage(cloudBlockBlob); } else { dataProtectionBuilder.PersistKeysToAzureBlobStorage(blobUri); } } if (!String.IsNullOrEmpty(kmOptions.ProtectWithKeyVaultKey)) { var keyVaultSection = configuration.GetSection(ConfigurationPath.Combine("Server", "KeyVault")); var kvOptions = new KeyVaultOptions(keyVaultSection); var keyIdBuilder = new UriBuilder(kvOptions.VaultUri) { Path = $"/keys/${kmOptions.ProtectWithKeyVaultKey}" }; var keyId = keyIdBuilder.Uri.ToString(); if (kvOptions.ClientId == null) { // Use Managed Identity var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); dataProtectionBuilder.ProtectKeysWithAzureKeyVault(new KeyVaultClient(authenticationCallback), keyId); } else { if (kvOptions.ClientSecret != null) { dataProtectionBuilder.ProtectKeysWithAzureKeyVault(keyId, kvOptions.ClientId, kvOptions.ClientSecret); } else if (kvOptions.Certificate != null) { dataProtectionBuilder.ProtectKeysWithAzureKeyVault(keyId, kvOptions.ClientId, kvOptions.Certificate); } } } else if (kmOptions.ProtectWithCertificate != null) { dataProtectionBuilder.ProtectKeysWithCertificate(kmOptions.ProtectWithCertificate); if (kmOptions.UnprotectWithCertificates != null) { dataProtectionBuilder.UnprotectKeysWithAnyCertificate(kmOptions.UnprotectWithCertificates); } } else if (kmOptions.ProtectWithDpapiNg != null) { if (kmOptions.ProtectWithDpapiNg.UseSelfRule) { dataProtectionBuilder.ProtectKeysWithDpapiNG(); } else { dataProtectionBuilder.ProtectKeysWithDpapiNG(kmOptions.ProtectWithDpapiNg.DescriptorRule, kmOptions.ProtectWithDpapiNg.DescriptorFlags); } } else { throw new Exception("Unvalidated options would have allowed for unprotected key storage."); } } services.AddHttpContextAccessor(); services.AddHealthChecks(); services.AddOakproxy(proxyOptions); }) .ConfigureWebHost(configure => { configure.UseUrls(serverOptions.Urls); configure.UseKestrel((builderContext, options) => { options.Configure(subsystemConfiguration.Kestrel); if (serverOptions.HttpsCertificate != null) { options.ConfigureHttpsDefaults(configureHttps => configureHttps.ServerCertificate = serverOptions.HttpsCertificate); } }); configure.Configure(builder => builder.UseOakproxy()); }); return(builder); }
public CorsConfiguration(IConfiguration configuration) { Rules = new List <Rule>(); ConfigurationBinder.Bind(configuration.GetSection("cors:rules"), Rules); }
public static ILoggingBuilder AddSerilog( this ILoggingBuilder builder, WebHostBuilderContext context, Func <LogEvent, bool> filter = null) { if (context.HostingEnvironment.IsDevelopment()) { return(builder); } bool inclusionPredicate(LogEvent e) { if (filter == null) { return(true); } var eventId = e.Properties.ContainsKey("EventId") ? e.Properties["EventId"].ToString() : null; if (eventId?.Contains(Constants.BypassFiltersEventId.ToString()) ?? false) { return(true); } return(filter(e)); } var globalSettings = new GlobalSettings(); ConfigurationBinder.Bind(context.Configuration.GetSection("GlobalSettings"), globalSettings); var config = new LoggerConfiguration() .Enrich.FromLogContext() .Filter.ByIncludingOnly(inclusionPredicate); if (CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Uri) && CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Key)) { config.WriteTo.AzureDocumentDB(new Uri(globalSettings.DocumentDb.Uri), globalSettings.DocumentDb.Key, timeToLive: TimeSpan.FromDays(7)) .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } else if (CoreHelpers.SettingHasValue(globalSettings?.Sentry.Dsn)) { config.WriteTo.Sentry(globalSettings.Sentry.Dsn) .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } else if (CoreHelpers.SettingHasValue(globalSettings?.Syslog.Destination)) { // appending sitename to project name to allow eaiser identification in syslog. var appName = $"{globalSettings.SiteName}-{globalSettings.ProjectName}"; if (globalSettings.Syslog.Destination.Equals("local", StringComparison.OrdinalIgnoreCase)) { config.WriteTo.LocalSyslog(appName); } else if (Uri.TryCreate(globalSettings.Syslog.Destination, UriKind.Absolute, out var syslogAddress)) { // Syslog's standard port is 514 (both UDP and TCP). TLS does not have a standard port, so assume 514. int port = syslogAddress.Port >= 0 ? syslogAddress.Port : 514; if (syslogAddress.Scheme.Equals("udp")) { config.WriteTo.UdpSyslog(syslogAddress.Host, port, appName); } else if (syslogAddress.Scheme.Equals("tcp")) { config.WriteTo.TcpSyslog(syslogAddress.Host, port, appName); } else if (syslogAddress.Scheme.Equals("tls")) { // TLS v1.1, v1.2 and v1.3 are explicitly selected (leaving out TLS v1.0) const SslProtocols protocols = SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13; if (CoreHelpers.SettingHasValue(globalSettings.Syslog.CertificateThumbprint)) { config.WriteTo.TcpSyslog(syslogAddress.Host, port, appName, secureProtocols: protocols, certProvider: new CertificateStoreProvider(StoreName.My, StoreLocation.CurrentUser, globalSettings.Syslog.CertificateThumbprint)); } else { config.WriteTo.TcpSyslog(syslogAddress.Host, port, appName, secureProtocols: protocols, certProvider: new CertificateFileProvider(globalSettings.Syslog.CertificatePath, globalSettings.Syslog?.CertificatePassword ?? string.Empty)); } } } } else if (CoreHelpers.SettingHasValue(globalSettings.LogDirectory)) { if (globalSettings.LogRollBySizeLimit.HasValue) { config.WriteTo.File($"{globalSettings.LogDirectory}/{globalSettings.ProjectName}/log.txt", rollOnFileSizeLimit: true, fileSizeLimitBytes: globalSettings.LogRollBySizeLimit); } else { config.WriteTo .RollingFile($"{globalSettings.LogDirectory}/{globalSettings.ProjectName}/{{Date}}.txt"); } config .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } var serilog = config.CreateLogger(); builder.AddSerilog(serilog); return(builder); }
private static string GetSettingValue(string settingName) { EnsureConfigInitialized(); return(ConfigurationBinder.GetValue(Config, settingName, "default")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ExecutionContext context) { ILogger log = null; config = new FunctionConfig(); if (File.Exists(String.Format($"{context.FunctionAppDirectory}/secrets.json"))) { //secrets.json exists use it and environment variables var builder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("secrets.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables("FUNC_"); IConfigurationRoot root = builder.Build(); ConfigurationBinder.Bind(root, config); } else if (File.Exists(String.Format("{0}/{1}", context.FunctionAppDirectory, "local.settings.json"))) { //use for local testing...do not use in production //remember to add the storage connection string var builder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables("FUNC_"); IConfigurationRoot root = builder.Build(); ConfigurationBinder.Bind(root, config); config.StorageConnectionString = root.GetConnectionString("StorageConnectionString"); } else { //no secrets or local.settings.json files...use only environment variables var builder = new ConfigurationBuilder() .AddEnvironmentVariables("FUNC_"); IConfigurationRoot root = builder.Build(); ConfigurationBinder.Bind(root, config); } string luss = req.Query["luss"]; try { if (string.IsNullOrEmpty(luss)) { throw new InvalidOperationException("No LUSS provided."); } ProvisionModel model = new ProvisionModel(luss, config, log); ModuleConfig moduleConfig = await model.ProvisionAsync(); foreach (var slave in moduleConfig.Slaves) { slave.RemoveConstraints(); } return((ActionResult) new OkObjectResult(moduleConfig)); } catch (Exception ex) { return(new BadRequestObjectResult(ex.Message)); } }
public ConfigureFromConfigurationOptions([NotNull] IConfiguration config) : base(options => ConfigurationBinder.Bind(options, config)) { }
private static void BindFromOptions(TOptions options, IConfiguration config) => ConfigurationBinder.Bind(config, options);
public void OneTimeSetUp() { var environment = Environment.GetEnvironmentVariable("TYPEDSQL_ENVIRONMENT"); var config = new ConfigurationBuilder() .SetBasePath(TestContext.CurrentContext.TestDirectory) .AddJsonFile("appSettings.json") .AddJsonFile("appSettings." + environment + ".json", true) .Build(); var mycsb = new MySqlConnectionStringBuilder() { Server = ConfigurationBinder.GetValue <string>(config, "MySql:Server"), Port = ConfigurationBinder.GetValue <uint>(config, "MySql:Port"), UserID = ConfigurationBinder.GetValue <string>(config, "MySql:UserID"), Password = ConfigurationBinder.GetValue <string>(config, "MySql:Password"), Database = ConfigurationBinder.GetValue <string>(config, "MySql:Database"), AllowUserVariables = ConfigurationBinder.GetValue <bool>(config, "MySql:AllowUserVariables"), }; var mscsb = new SqlConnectionStringBuilder() { DataSource = ConfigurationBinder.GetValue <string>(config, "SqlServer:DataSource"), InitialCatalog = ConfigurationBinder.GetValue <string>(config, "SqlServer:InitialCatalog"), IntegratedSecurity = ConfigurationBinder.GetValue <bool>(config, "SqlServer:IntegratedSecurity"), }; if (!mscsb.IntegratedSecurity) { mscsb.UserID = ConfigurationBinder.GetValue <string>(config, "SqlServer:UserID"); mscsb.Password = ConfigurationBinder.GetValue <string>(config, "SqlServer:Password"); } var pgcsb = new NpgsqlConnectionStringBuilder() { Host = ConfigurationBinder.GetValue <string>(config, "PostgreSql:Host"), Port = ConfigurationBinder.GetValue <int>(config, "PostgreSql:Port"), Username = ConfigurationBinder.GetValue <string>(config, "PostgreSql:Username"), Password = ConfigurationBinder.GetValue <string>(config, "PostgreSql:Password"), Database = ConfigurationBinder.GetValue <string>(config, "PostgreSql:Database"), }; var services = new ServiceCollection(); services.AddScoped(provider => { var connection = new MySqlConnection(mycsb.ConnectionString); connection.Open(); return(connection); }); services.AddScoped(provider => { return(new MySqlQueryRunner(provider.GetRequiredService <MySqlConnection>())); }); services.AddScoped(provider => { return(new InMemoryQueryRunner()); }); services.AddScoped(provider => { var connection = new SqlConnection(mscsb.ConnectionString); connection.Open(); return(connection); }); services.AddScoped(provider => { return(new SqlServerQueryRunner(provider.GetRequiredService <SqlConnection>())); }); services.AddScoped(provider => { var connection = new NpgsqlConnection(pgcsb.ConnectionString); connection.Open(); return(connection); }); services.AddScoped(provider => { return(new PostgreSqlQueryRunner(provider.GetRequiredService <NpgsqlConnection>())); }); RootProvider = services.BuildServiceProvider(); }