/// <summary>
        /// Protects the web API with Microsoft identity platform (formerly Azure AD v2.0).
        /// This method expects the configuration file will have a section, named "AzureAd" as default, with the necessary settings to initialize authentication options.
        /// </summary>
        /// <param name="builder">The <see cref="AuthenticationBuilder"/> to which to add this configuration.</param>
        /// <param name="configurationSection">The configuration second from which to fill-in the options.</param>
        /// <param name="jwtBearerScheme">The JWT bearer scheme name to be used. By default it uses "Bearer".</param>
        /// <param name="subscribeToJwtBearerMiddlewareDiagnosticsEvents">
        /// Set to true if you want to debug, or just understand the JWT bearer events.
        /// </param>
        /// <returns>The authentication builder to chain.</returns>
        public static MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration AddMicrosoftIdentityWebApi(
            this AuthenticationBuilder builder,
            IConfigurationSection configurationSection,
            string jwtBearerScheme = JwtBearerDefaults.AuthenticationScheme,
            bool subscribeToJwtBearerMiddlewareDiagnosticsEvents = false)
        {
            if (configurationSection == null)
            {
                throw new ArgumentNullException(nameof(configurationSection));
            }

            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            AddMicrosoftIdentityWebApiImplementation(
                builder,
                options => configurationSection.Bind(options),
                options => configurationSection.Bind(options),
                jwtBearerScheme,
                subscribeToJwtBearerMiddlewareDiagnosticsEvents);

            return(new MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration(
                       builder.Services,
                       jwtBearerScheme,
                       options => configurationSection.Bind(options),
                       options => configurationSection.Bind(options),
                       configurationSection));
        }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddStorage(this IServiceCollection services, IConfiguration configuration)
        {
            StorageOptions        options = new StorageOptions();
            IConfigurationSection section = configuration.GetSection("Storage");

            section.Bind(options);

            services.Configure <StorageOptions>(settings => section.Bind(settings));

            switch (options.Adapter)
            {
            case "filesystem":
                services.AddScoped <IStorageService, FileSystemStorageService>();
                break;

            case "azure":
                services.AddScoped <IStorageService, BlobStorageService>();
                break;

            case "aws":
                services.AddScoped <IStorageService, AwsStorageService>();
                break;

            case "minio":
                services.AddScoped <IStorageService, MinioStorageService>();
                break;

            default:
                services.AddScoped <IStorageService, MinioStorageService>();
                break;
            }

            return(services);
        }
Beispiel #3
0
        public static void Configure <TConfig>(this IServiceCollection services, string name, IConfigurationSection section) where TConfig : class
        {
            var config = (TConfig)Activator.CreateInstance(typeof(TConfig));

            section.Bind(config);
            services.Configure <TConfig>(name, options =>
            {
                section.Bind(options);
            });
        }
Beispiel #4
0
        private IOutputPlugin CreateOutputPlugin(string pluginType, string systemName, IConfigurationSection configurationSection)
        {
            _logger.SLT00013_Debug_Create_Output_pluginType_plugin_SystemName_systemName(pluginType, systemName);
            _logger.SLT00019_Trace_Main_buffer_settings_config_bufferSettingsConfig(_bufferSettingsConfig);

            if (pluginType == "Clickhouse")
            {
                var clickHousePluginConfig = new ClickhouseOutputConfig();

                configurationSection.Bind(clickHousePluginConfig);
                _logger.SLT00022_Trace_Plugin_output_config_clickHousePluginConfig(clickHousePluginConfig);

                if (clickHousePluginConfig.BufferSettings == null)
                {
                    clickHousePluginConfig.BufferSettings = _bufferSettingsConfig;
                    _logger.SLT00020_Debug_Child_settings_empty_Parent_config_is_applied();
                }
                else
                {
                    clickHousePluginConfig.BufferSettings.JoinWithParentBufferConfig(_bufferSettingsConfig);
                    _logger.SLT00021_Debug_Child_and_parent_settings_merged();
                }

                return(new ClickhouseOutputPlugin(clickHousePluginConfig, _metrics, _loggerFactory));
            }

            if (pluginType == "Forward")
            {
                var forwardOutputConfig = new ForwardOutputConfig();

                configurationSection.Bind(forwardOutputConfig);
                _logger.SLT00023_Trace_Plugin_output_config_forwardOutputConfig(forwardOutputConfig);

                if (forwardOutputConfig.BufferSettings == null)
                {
                    forwardOutputConfig.BufferSettings = _bufferSettingsConfig;
                    _logger.SLT00024_Debug_Child_settings_empty_Parent_config_is_applied();
                }
                else
                {
                    forwardOutputConfig.BufferSettings.JoinWithParentBufferConfig(_bufferSettingsConfig);
                    _logger.SLT00025_Debug_Child_and_parent_settings_merged();
                }

                return(new ForwardOutputPlugin(forwardOutputConfig, _loggerFactory));
            }

            return(null);
        }
        public static void AddSyslog(this ILoggerFactory loggerFactory, IConfigurationSection configuration, string hostName = "localhost", LogLevel logLevel = LogLevel.Debug)
        {
            var settings = new SyslogLoggerSettings();

            configuration.Bind(settings);
            loggerFactory.AddProvider(new SyslogLoggerProvider(settings, hostName, logLevel));
        }
Beispiel #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            IConfigurationSection lFileSettingsSection = this.Configuration.GetSection("FileSettings");
            var lFileSettings = new FileSettings();

            lFileSettingsSection.Bind(lFileSettings);
            services.Configure <FileSettings>(lFileSettingsSection);

            services.AddScoped <IAccreditationRepository, AccreditationRepository>();
            services.AddScoped <IAwardLevelRepository, AwardLevelRepository>();
            services.AddScoped <ICompetitionEntryRepository, CompetitionEntryRepository>();
            services.AddScoped <ICountryRepository, CountryRepository>();
            services.AddScoped <IPersonRepository, PersonRepository>();
            services.AddScoped <IPhotoOrganisationRepository, PhotoOrganisationRepository>();
            services.AddScoped <ISalonRepository, SalonRepository>();
            services.AddScoped <ISalonYearRepository, SalonYearRepository>();
            services.AddScoped <ISectionRepository, SectionRepository>();
            services.AddScoped <ISectionTypeRepository, SectionTypeRepository>();
            services.AddScoped <ISubmissionRepository, SubmissionRepository>();
            services.AddScoped <ICircuitRepository, CircuitRepository>();

            services.AddScoped <ISalonYearService, SalonYearService>();
            services.AddScoped <ISubmissionService, SubmissionService>();
            services.AddScoped <IReferenceServices, ReferenceServices>();
            services.AddScoped <IPersonAwardService, PersonAwardService>();
            services.AddScoped <IImageService, ImageService>();
            services.AddScoped <IDbTransaction, SalonDbContext>();
            services.AddScoped <ISalonDbContext, SalonDbContext>();
        }
Beispiel #7
0
        public ServiceBusConsumer(ILogger logger, IConfigurationSection config, MessageHandler handler)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            _logger = logger;

            logger.LogInformation("Starting consumer");

            var sboptions = new ServiceBusConsumerConfig();

            config.Bind(sboptions);

            var connectionString = new ServiceBusConnectionStringBuilder(sboptions.EndpointAddress, sboptions.Topic,
                                                                         sboptions.AuthKeyName,
                                                                         sboptions.AuthKey);

            topicClient = new TopicClient(connectionString);

            var messageProcessorHostName = Guid.NewGuid().ToString();
            var processor = new ServiceBusMessageProcessor(topicClient, logger, handler);

            var handlerOptpions = new MessageHandlerOptions(processor.LogException);

            handlerOptpions.AutoComplete = true;
            subscriptionClient           = new SubscriptionClient(connectionString, sboptions.Subscription);
            subscriptionClient.RegisterMessageHandler(processor.Process, handlerOptpions);
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            StartupConfig.Setup();

            ISecretsManager      secretsManager;
            IServiceInjector     serviceInjector;
            IKeyedServiceManager keyedServiceManager;

            services.AddDefaultSecretsManager(_env, Configuration,
                                              ConfigConsts.CommandLine.WindowsCmd, out secretsManager)
            .AddKeyedServiceManager(out keyedServiceManager)
            .AddAppDbContext(secretsManager)
            .AddServiceInjector(StartupConfig.TempAssemblyList, out serviceInjector)
            .AddHttpContextAccessor()
            .AddHttpBusinessContextProvider()
            .AddDefaultDbMigrator()
            .AddRequestFeatureMiddleware()
            .AddAppCaching()
            .AddDefaultValidationResultProvider()
            .AddSmtpService(opt =>
            {
                _smtpOptionSection.Bind(opt);
                opt.Password = secretsManager.Get(ConfigConsts.Mail.PasswordKey);
            })
            .AddJsonConfigurationManager(Program.DefaultJsonFile, Program.EnvJsonFile)
            .AddAppAuthentication()
            .AddAppAuthorization()
            .AddWebFrameworks()
            .AddAppSwagger()
            .ScanServices(StartupConfig.TempAssemblyList, serviceInjector)
            .ConfigureAppOptions(Configuration);
        }
        /// <summary>
        /// Use client certificate for authenticating against the BankID API from Azure Key Vault.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configurationSection">Configuration section to bind the Key Vault options from.</param>
        /// <returns></returns>
        public static IBankIdBuilder UseClientCertificateFromAzureKeyVault(this IBankIdBuilder builder, IConfigurationSection configurationSection)
        {
            var options = new ClientCertificateFromAzureKeyVaultOptions();

            configurationSection.Bind(options);
            return(UseClientCertificateFromAzureKeyVault(builder, options));
        }
    private static EndpointConfiguration ElementSelector(IConfigurationSection iConfigurationSection)
    {
        var endpoint = new EndpointConfiguration();

        iConfigurationSection.Bind(endpoint);
        return(endpoint);
    }
        public static IServiceCollection AddZeroMq(this IServiceCollection services, IConfigurationSection queueConfig)
        {
            var options = new Options();
            queueConfig.Bind(options);

            return services.AddSingleton<IMessageQueueFactory>(sp => ActivatorUtilities.CreateInstance<ZeroMqQueueFactory>(sp, options.Queues.OfType<IMessageQueueConnection>().ToList()));
        }
Beispiel #12
0
        /// <summary>
        /// Binds, validates and normalizes WebDAV logger options.
        /// </summary>
        /// <param name="configurationSection">Instance of <see cref="IConfigurationSection"/>.</param>
        /// <param name="options">WebDAV Logger configuration options.</param>
        public static async Task ReadOptionsAsync(this IConfigurationSection configurationSection, DavLoggerOptions options, IHostingEnvironment env)
        {
            if (configurationSection == null)
            {
                throw new ArgumentNullException("configurationSection");
            }

            configurationSection.Bind(options);

            if (string.IsNullOrEmpty(options.LogFile))
            {
                throw new ArgumentNullException("LoggerOptions.LogFile");
            }

            if (!Path.IsPathRooted(options.LogFile))
            {
                options.LogFile = Path.GetFullPath(Path.Combine(env.ContentRootPath, options.LogFile));
            }

            // Create log folder and log file if does not exists.
            FileInfo logInfo = new FileInfo(options.LogFile);

            if (!logInfo.Exists)
            {
                if (!logInfo.Directory.Exists)
                {
                    logInfo.Directory.Create();
                }

                using (FileStream stream = logInfo.Create()) { }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Binds, validates and normalizes WebDAV Context configuration.
        /// </summary>
        /// <param name="configurationSection">Instance of <see cref="IConfigurationSection"/>.</param>
        /// <param name="config">WebDAV Context configuration.</param>
        /// <param name="env">Instance of <see cref="IWebHostEnvironment"/>.</param>
        public static async Task ReadConfigurationAsync(this IConfigurationSection configurationSection, DavContextConfig config, IWebHostEnvironment env)
        {
            if (configurationSection == null)
            {
                throw new ArgumentNullException("configurationSection");
            }

            configurationSection.Bind(config);
            if (string.IsNullOrEmpty(config.RepositoryPath))
            {
                throw new ArgumentNullException("DavContext.RepositoryPath");
            }

            if (!Path.IsPathRooted(config.RepositoryPath))
            {
                config.RepositoryPath = Path.GetFullPath(Path.Combine(env.ContentRootPath, config.RepositoryPath));
            }

            if (!(string.IsNullOrEmpty(config.AttrStoragePath) || Path.IsPathRooted(config.AttrStoragePath)))
            {
                config.AttrStoragePath = Path.GetFullPath(Path.Combine(env.ContentRootPath, config.AttrStoragePath));
            }

            if (!string.IsNullOrEmpty(config.AttrStoragePath))
            {
                FileSystemInfoExtension.UseFileSystemAttribute(new FileSystemExtendedAttribute(config.AttrStoragePath, config.RepositoryPath));
            }
            else if (!await new DirectoryInfo(config.RepositoryPath).IsExtendedAttributesSupportedAsync())
            {
                var tempPath = Path.Combine(Path.GetTempPath(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                FileSystemInfoExtension.UseFileSystemAttribute(new FileSystemExtendedAttribute(tempPath, config.RepositoryPath));
            }
        }
Beispiel #14
0
        /// <summary>
        /// 启动服务注册与发现
        /// </summary>
        public static IServiceCollection AddNacosNaming(this IServiceCollection services, IConfigurationSection section)
        {
            var mainCfg = new NamingConfig();

            section.Bind(mainCfg);
            return(AddNacosNaming(services, mainCfg));
        }
        public static LoggerConfiguration BigQuery(this LoggerSinkConfiguration sinkConfiguration, IConfigurationSection configuration, LogEventLevel logLevel = LogEventLevel.Warning)
        {
            var sinkOptions = new BigQuerySinkOptions();

            configuration.Bind(sinkOptions);
            return(sinkConfiguration.BigQuery(sinkOptions, logLevel));
        }
        private void AddRabbitMqService(IServiceCollection services, IConfigurationSection configuration)
        {
            var options = new RawRabbitConfiguration();

            configuration.Bind(options);
            services.AddSingleton <IBusClient>(_ => BusClientFactory.CreateDefault(options));
        }
Beispiel #17
0
 /// <summary>
 /// Add support to call Microsoft Graph. From a named option and a configuration section.
 /// </summary>
 /// <param name="builder">Builder.</param>
 /// <param name="configurationSection">Configuration section.</param>
 /// <returns>The builder to chain.</returns>
 public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddMicrosoftGraph(
     this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder,
     IConfigurationSection configurationSection)
 {
     return(builder.AddMicrosoftGraph(
                options => configurationSection.Bind(options)));
 }
Beispiel #18
0
        private void InitializeConfig(IApplicationEnvironment appEnv)
        {
            _configuration = ConfigurationFactory.CreateConfig(appEnv);
            IConfigurationSection appSettingsConfig = _configuration.GetSection("AppSettings");

            appSettingsConfig.Bind(_appSettings);
        }
Beispiel #19
0
        public static List <ApiResource> LoadApiResourcesFromSettings(this IConfiguration configuration)
        {
            IConfigurationSection section = configuration.GetSection("apiResources");
            var apiResourceRecords        = new List <ApiResourceRecord>();

            section.Bind(apiResourceRecords);
            List <ApiResource> apiResources = new List <ApiResource>();

            foreach (var apiResourceRecord in apiResourceRecords)
            {
                // no matter what add the api resource as a scope
                List <Scope> scopes = new List <Scope> {
                    new Scope(apiResourceRecord.Name)
                };
                if (apiResourceRecord.Scopes != null)
                {
                    var prePend = string.IsNullOrWhiteSpace(apiResourceRecord.ScopeNameSpace)
                        ? $"{apiResourceRecord.Name}."
                        : $"{apiResourceRecord.ScopeNameSpace}.";
                    foreach (var scopeRecord in apiResourceRecord.Scopes)
                    {
                        scopes.Add(new Scope($"{prePend}{scopeRecord.Name}", scopeRecord.DisplayName));
                    }
                }

                apiResources.Add(new ApiResource(apiResourceRecord.Name)
                {
                    Scopes = scopes
                });
            }

            return(apiResources);
        }
        private static CacheManagerConfiguration GetFromConfiguration(IConfigurationSection configuration)
        {
            var managerConfiguration = new CacheManagerConfiguration();

            configuration.Bind(managerConfiguration);

            var handlesConfiguration = configuration.GetSection(HandlesSection);

            if (handlesConfiguration.GetChildren().Count() == 0)
            {
                throw new InvalidOperationException(
                          $"No cache handles defined in '{configuration.Path}'.");
            }

            foreach (var handleConfiguration in handlesConfiguration.GetChildren())
            {
                var cacheHandleConfiguration = GetHandleFromConfiguration(handleConfiguration);
                managerConfiguration.CacheHandleConfigurations.Add(cacheHandleConfiguration);
            }

            GetBackplaneConfiguration(managerConfiguration, configuration);
            GetLoggerFactoryConfiguration(managerConfiguration, configuration);
            GetSerializerConfiguration(managerConfiguration, configuration);

            return(managerConfiguration);
        }
Beispiel #21
0
        protected internal ConfigSection(IConfiguration configuration, IConfigurationSection section)
        {
            if (section != null)
            {
                // bind appsettings.json
                section.Bind(this);

                // overwrite with environment variables (loaded into configuration in Program.cs by calling config.AddEnvironmentVariables())
                // Azure Application Settings / Connection strings goes to GetSection("ConnectionStrings")["..."], overwriting values coming from appsettings.json
                // Azure Application Settings / Application settings goes to root config (configuration["..."]) and therefore expected to be specified as sectionName.propertyName
                var properties = this.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);

                foreach (var property in properties)
                {
                    var key = $"{section.Key}.{property.Name}";

                    try
                    {
                        property.SetValue(this, configuration.GetValue(property.PropertyType, key, property.GetValue(this)));
                    }
                    catch
                    {
                        throw new InvalidCastException($"Value of environment variable '{key}' cannot be set into {property.PropertyType}.");
                    }
                }
            }
        }
Beispiel #22
0
        public static IContainer IocContainerFactory(IServiceCollection services, IConfigurationRoot configuration)
        {
            var builder = new ContainerBuilder();
            IConfigurationSection sectionData = configuration.GetSection("AppSetting");
            var section = new AppSetting();

            sectionData.Bind(section);
            List <Assembly> assemblyList = new List <Assembly>();

            if (section.AssemblyNames != null && section.AssemblyNames.Count > 0)
            {
                section.AssemblyNames.ForEach(x =>
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, x)));
                    //assemblyList.Add(Assembly.Load(new AssemblyName(x)));
                });
                builder.RegisterAssemblyModules(assemblyList.ToArray());
            }

            //builder.RegisterInstance<string>(configuration.GetConnectionString("DefaultConnection")).Named<string>("DefaultConnection");
            builder.RegisterType <DataContext>()
            .WithParameter("connectionString", configuration.GetConnectionString("DefaultConnection"));

            builder.Populate(services);
            return(builder.Build());
        }
Beispiel #23
0
        public static void AddRetryPolicy(this IServiceCollection services, IConfigurationSection configurationSection)
        {
            var retryPolicyOptions = new RetryPolicyOptions();

            configurationSection?.Bind(retryPolicyOptions);
            services.AddSingleton <IRetryPolicyOptions>(retryPolicyOptions);
        }
        /// <summary>
        /// Maps a ConfigSection to a List&lt;XmlTranslationsConfig&gt; object
        /// </summary>
        public static List <XmlTranslationsConfig> GetXmlTranslationsConfigs(this IConfigurationSection config)
        {
            var conf = new List <XmlTranslationsConfig>();

            config.Bind(conf);
            return(conf);
        }
Beispiel #25
0
        private void SetDbContextOptionses(OSharpOptions options)
        {
            IConfigurationSection section = _configuration.GetSection("OSharp:DbContexts");

            if (section == null)
            {
                string connectionString = _configuration["ConnectionStrings:DefaultDbContext"];
                if (connectionString == null)
                {
                    return;
                }
                OSharpDbContextOptions dbContextOptions = new OSharpDbContextOptions()
                {
                    DbContextTypeName = "OSharp.Entity.DefaultDbContext,OSharp.EntityFrameworkCore",
                    ConnectionString  = connectionString,
                    DatabaseType      = DatabaseType.SqlServer
                };
                options.DbContextOptionses.Add("DefaultDbContext", dbContextOptions);
                return;
            }
            IDictionary <string, OSharpDbContextOptions> dict = new Dictionary <string, OSharpDbContextOptions>();

            section.Bind(dict);
            foreach (KeyValuePair <string, OSharpDbContextOptions> pair in dict)
            {
                options.DbContextOptionses.Add(pair.Key, pair.Value);
            }
        }
        /// <summary>
        /// Maps a ConfigSection to a XmlTranslationsConfig object
        /// </summary>
        public static XmlTranslationsConfig GetXmlTranslationsConfig(this IConfigurationSection config)
        {
            var conf = new XmlTranslationsConfig();

            config.Bind(conf);
            return(conf);
        }
Beispiel #27
0
        public static IServiceCollection AddBigQuerySchemaHelper(this IServiceCollection services, IConfigurationSection configurationSection, string optionsName)
        {
            var helperOptions = new BigQuerySchemaHelperOptions();

            configurationSection.Bind(helperOptions);
            return(services.AddBigQuerySchemaHelper(helperOptions, optionsName));
        }
        public static IServiceCollection AddAzure(this IServiceCollection services, IConfigurationSection queueConfig)
        {
            var options = new Options();
            queueConfig.Bind(options);

            return services.AddSingleton<IMessageQueueFactory>(sp => ActivatorUtilities.CreateInstance<AzureQueueFactory>(sp, options.Queues));
        }
Beispiel #29
0
        /// <summary>
        /// Add authentication with Microsoft identity platform.
        /// This method expects the configuration file will have a section, named "AzureAd" as default, with the necessary settings to initialize authentication options.
        /// </summary>
        /// <param name="builder">The <see cref="AuthenticationBuilder"/> to which to add this configuration.</param>
        /// <param name="configurationSection">The configuration section from which to get the options.</param>
        /// <param name="openIdConnectScheme">The OpenID Connect scheme name to be used. By default it uses "OpenIdConnect".</param>
        /// <param name="cookieScheme">The cookie-based scheme name to be used. By default it uses "Cookies".</param>
        /// <param name="subscribeToOpenIdConnectMiddlewareDiagnosticsEvents">
        /// Set to true if you want to debug, or just understand the OpenID Connect events.
        /// </param>
        /// <returns>The authentication builder for chaining.</returns>
        public static MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration AddMicrosoftIdentityWebApp(
            this AuthenticationBuilder builder,
            IConfigurationSection configurationSection,
            string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
            string?cookieScheme        = CookieAuthenticationDefaults.AuthenticationScheme,
            bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (configurationSection == null)
            {
                throw new ArgumentException(nameof(configurationSection));
            }

            return(builder.AddMicrosoftIdentityWebAppWithConfiguration(
                       options => configurationSection.Bind(options),
                       null,
                       openIdConnectScheme,
                       cookieScheme,
                       subscribeToOpenIdConnectMiddlewareDiagnosticsEvents,
                       configurationSection));
        }
Beispiel #30
0
        private static DkpBotConfiguration GetBotConfiguration(IConfigurationSection configuration)
        {
            DkpBotConfiguration botConfig = new DkpBotConfiguration();

            configuration.Bind(botConfig);
            return(botConfig);
        }
Beispiel #31
0
        /// <summary>
        /// Define trusted Client client
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <Client> GetClients(IConfigurationSection section)
        {
            List <Client> clients = new List <Client>();

            if (section != null)
            {
                List <ClientConfig> configs = new List <ClientConfig>();
                section.Bind("Clients", configs);
                foreach (var config in configs)
                {
                    Client client = new Client();
                    client.ClientId = config.ClientId;
                    List <Secret> clientSecrets = new List <Secret>();
                    foreach (var secret in config.ClientSecrets)
                    {
                        clientSecrets.Add(new Secret(secret.Sha256()));
                    }
                    client.ClientSecrets = clientSecrets.ToArray();

                    GrantTypes grantTypes        = new GrantTypes();
                    var        allowedGrantTypes = grantTypes.GetType().GetProperty(config.AllowedGrantTypes);
                    client.AllowedGrantTypes = allowedGrantTypes == null ?
                                               GrantTypes.ClientCredentials : (ICollection <string>)allowedGrantTypes.GetValue(grantTypes, null);

                    client.AllowedScopes = config.AllowedScopes.ToArray();

                    clients.Add(client);
                }
            }
            return(clients.ToArray());
        }
        public static IServiceCollection BindAndConfigure <TConfig>(this IServiceCollection services, IConfigurationSection section, TConfig config) where TConfig : class, new()
        {
            section.Bind(config);
            services.AddSingleton(config);

            return(services);
        }
        private static CacheHandleConfiguration GetHandleFromConfiguration(IConfigurationSection handleConfiguration)
        {
            var type = handleConfiguration[ConfigurationType];
            var knownType = handleConfiguration[ConfigurationKnownType];
            var key = handleConfiguration[ConfigurationKey] ?? handleConfiguration[ConfigurationName];    // name fallback for key
            var name = handleConfiguration[ConfigurationName];

            var cacheHandleConfiguration = new CacheHandleConfiguration();
            handleConfiguration.Bind(cacheHandleConfiguration);
            cacheHandleConfiguration.Key = key;
            cacheHandleConfiguration.Name = name ?? cacheHandleConfiguration.Name;

            if (string.IsNullOrEmpty(type) && string.IsNullOrEmpty(knownType))
            {
                throw new InvalidOperationException(
                    $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in cache handle configuration '{handleConfiguration.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                var keyRequired = false;
                cacheHandleConfiguration.HandleType = GetKnownHandleType(knownType, handleConfiguration.Path, out keyRequired);

                // some handles require name or key to be set to link to other parts of the configuration
                // lets check if that condition is satisfied
                if (keyRequired && string.IsNullOrWhiteSpace(key) && string.IsNullOrWhiteSpace(name))
                {
                    throw new InvalidOperationException(
                        $@"Known handle of type '{knownType}' requires '{ConfigurationKey}' or '{ConfigurationName}' to be defined.
                            Check configuration at '{handleConfiguration.Path}'.");
                }
            }
            else
            {
                cacheHandleConfiguration.HandleType = Type.GetType(type, true);
            }

            return cacheHandleConfiguration;
        }
        private static CacheManagerConfiguration GetFromConfiguration(IConfigurationSection configuration)
        {
            var managerConfiguration = new CacheManagerConfiguration();
            configuration.Bind(managerConfiguration);

            var handlesConfiguration = configuration.GetSection(HandlesSection);

            if (handlesConfiguration.GetChildren().Count() == 0)
            {
                throw new InvalidOperationException(
                    $"No cache handles defined in '{configuration.Path}'.");
            }

            foreach (var handleConfiguration in handlesConfiguration.GetChildren())
            {
                var cacheHandleConfiguration = GetHandleFromConfiguration(handleConfiguration);
                managerConfiguration.CacheHandleConfigurations.Add(cacheHandleConfiguration);
            }

            GetBackplaneConfiguration(managerConfiguration, configuration);
            GetLoggerFactoryConfiguration(managerConfiguration, configuration);
            GetSerializerConfiguration(managerConfiguration, configuration);

            return managerConfiguration;
        }