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));
        }
Esempio n. 2
0
 private void ParseProperties(Control target, IConfigurationSection propertiesConfigSection)
 {
     foreach (IConfigurationElement element in propertiesConfigSection.Elements.Values)
     {
         ReflectionServices.SetValue(target, element.GetAttributeReference("name").Value.ToString(), element.GetAttributeReference("value").Value);
     }
 }
Esempio n. 3
0
        // Composition root
        private IServiceProvider BuildServiceProvider(Options options, IConfigurationSection queueConfig)
        {
            var services = new ServiceCollection().AddLogging();

            services.AddSingleton<IMessageHandlerFactory, MessageHandlerFactory>();

            switch (options.QueueType)
            {
                case "zeromq":
                    services.AddZeroMq(queueConfig);
                    break;
                case "msmq":
                    services.AddMsmq(queueConfig);
                    break;
                case "azure":
                    services.AddAzure(queueConfig);
                    break;
                default:
                    throw new Exception($"Could not resolve queue type {options.QueueType}");
            }

            if (!string.IsNullOrWhiteSpace(options.Handler))
            {
                services.AddTransient(typeof(IMessageHandler), Type.GetType(options.Handler));
            }

            var provider = services.BuildServiceProvider();

            // configure
            var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(loggerFactory.MinimumLevel);

            return provider;
        }
		public DependenciesSectionWidget (IConfigurationSection section) 
		{
			this.section = section;

			widget = new VBox ();

			if (this.section.Service.Dependencies.Length == 0) {
				widget.PackStart (new Label { Text = GettextCatalog.GetString ("This service has no dependencies") });
				return;
			}

			bool firstCategory = true;

			foreach (var category in this.section.Service.Dependencies.Select (d => d.Category).Distinct ()) {
				var categoryIcon = new ImageView (category.Icon.WithSize (IconSize.Small));
				var categoryLabel = new Label (category.Name);
				var categoryBox = new HBox ();

				if (!firstCategory)
					categoryBox.MarginTop += 5;

				categoryBox.PackStart (categoryIcon);
				categoryBox.PackStart (categoryLabel);
				widget.PackStart (categoryBox);

				foreach (var dependency in this.section.Service.Dependencies.Where (d => d.Category == category)) {
					widget.PackStart (new DependencyWidget (section.Service, dependency) {
						MarginLeft = category.Icon.Size.Width / 2
					});
				}

				if (firstCategory)
					firstCategory = false;
			}
		}
        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()));
        }
 /// <summary>
 /// Registers dependencies for the code runner service.
 /// </summary>
 public static void RegisterRemoteBuildService(
     this ContainerBuilder builder,
     IConfigurationSection buildServiceSettings)
 {
     builder.RegisterInstance(GetBuildServiceSettings(buildServiceSettings)).As<BuildServiceSettings>();
     builder.RegisterType<CodeRunnerClient>().As<ICodeRunnerService>().InstancePerLifetimeScope();
 }
		private static void PrintConfigurationSection(string root, IConfigurationSection parent)
		{
			Console.WriteLine($"{root}:{parent.Key} - {parent.Value}");
			foreach (var child in parent.GetChildren())
			{
				PrintConfigurationSection(string.Concat(root, Constants.KeyDelimiter, parent.Key), child);
			}
		}
 private void AddSection(IConfigurationSection section, int pathStart)
 {
     Data.Add(section.Path.Substring(pathStart), section.Value);
     foreach (var child in section.GetChildren())
     {
         AddSection(child, pathStart);
     }
 }
 private void BuildInsertCommand(SqlDataSource sqlDataSource, IConfigurationSection section)
 {
     sqlDataSource.InsertCommand = section.GetAttributeReference("Command", "text").Value.ToString();
     sqlDataSource.InsertCommandType = (SqlDataSourceCommandType)ReflectionServices.StrongTypeValue(section.GetAttributeReference("Command", "type").Value.ToString(), typeof(SqlDataSourceCommandType));
     if (section.Elements.Keys.Contains("Parameters"))
     {
         this.BuildCommand(section.GetElementReference("Parameters"), sqlDataSource.InsertParameters);
     }
 }
 /// <summary>
 /// Reads the Docker host configuration.
 /// </summary>
 private static DockerHostConfig ReadDockerHostSettings(
     IConfigurationSection hostSettings)
 {
     return new DockerHostConfig
     (
         hostSettings["DockerLibraryPath"],
         hostSettings["HostTempFolderPath"],
         hostSettings["ContainerTempFolderPath"]
     );
 }
 /// <summary>
 /// Registers dependencies for the build service.
 /// </summary>
 public static void RegisterBuildService(
     this ContainerBuilder builder,
     IConfigurationSection projectRunnerSettings)
 {
     builder.RegisterType<CodeRunnerService>().As<ICodeRunnerService>();
     builder.RegisterType<ProjectJobResultNotifier>().As<IProjectJobResultNotifier>();
     builder.RegisterType<ProjectRunnerService>().As<IProjectRunnerService>();
     builder.RegisterInstance(ReadProjectRunnerConfiguration(projectRunnerSettings))
         .As<IProjectRunnerServiceConfig>();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DirectorySearcherArgs"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        public DirectorySearcherArgs(
            IConfigurationSection configurationSection,
            IConfiguration configuration,
            IDictionary<string, IConfiguration> dictionary)
        {
            this.configuration = configuration;
            this.configurationSection = configurationSection;

            // lets protect our dictionary
            this.dictionary = new ReadOnlyDictionary<string, IConfiguration>(dictionary);
        }
 private static bool GetEnabled(IConfigurationSection configServerSection, ConfigurationRoot root, bool def)
 {
     var enabled = configServerSection["enabled"];
     if (!string.IsNullOrEmpty(enabled))
     {
         bool result;
         string resolved = ResovlePlaceholders(enabled, root);
         if (Boolean.TryParse(resolved, out result))
             return result;
     }
     return def;
 }
Esempio n. 14
0
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {

            var builder = new ConfigurationBuilder()
                .SetBasePath(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json")
                .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            this.Configuration = builder.Build();
            this.DataSection = this.Configuration.GetSection("Data");
        }
        private static string GetEnvironment(IConfigurationSection section, IHostingEnvironment environment)
        {
            // if spring:cloud:config:env present, use it
            var env = section["env"];
            if (!string.IsNullOrEmpty(env))
            {
                return env;
            }

            // Otherwise use ASP.NET 5 defined value (i.e. ASPNET_ENV or Hosting:Environment) (its default is 'Production')
            return environment.EnvironmentName;
        }
 private static bool GetCertificateValidation(IConfigurationSection configServerSection, ConfigurationRoot root, bool def)
 {
     var accept = configServerSection["validate_certificates"];
     if (!string.IsNullOrEmpty(accept))
     {
         bool result;
         string resolved = ResovlePlaceholders(accept, root);
         if (Boolean.TryParse(resolved, out result))
             return result;
     }
     return def;
 }
 /// <summary>
 /// Registers GitHub clients.
 /// </summary>
 public static void RegisterGitHubClients(
     this ContainerBuilder builder,
     IConfigurationSection gitHubSettings)
 {
     builder.RegisterInstance(CreateGitHubClient(gitHubSettings)).As<GitHubClient>();
     builder.RegisterInstance(GetGitHubWebhookSecret(gitHubSettings)).As<GitHubWebhookSecret>();
     builder.RegisterType<GitHubUserClient>().As<IGitHubUserClient>().InstancePerLifetimeScope();
     builder.RegisterType<GitHubOrganizationClient>().As<IGitHubOrganizationClient>().InstancePerLifetimeScope();
     builder.RegisterType<GitHubTeamClient>().As<IGitHubTeamClient>().InstancePerLifetimeScope();
     builder.RegisterType<GitHubRepositoryClient>().As<IGitHubRepositoryClient>().InstancePerLifetimeScope();
     builder.RegisterType<GitHubWebhookValidator>().As<IGitHubWebhookValidator>().InstancePerLifetimeScope();
 }
 /// <summary>
 /// Reads the Docker container configuration.
 /// </summary>
 private static DockerContainerConfig ReadDockerContainerSettings(
     IConfigurationSection containerSettings)
 {
     return new DockerContainerConfig
     (
         containerSettings["Id"],
         containerSettings["ImageName"],
         containerSettings["RequestResponseMountPoint"],
         containerSettings["RequestFileName"],
         containerSettings["ResponseFileName"],
         TimeSpan.Parse(containerSettings["MaxLifetime"])
     );
 }
        /// <summary>
        /// Registers dependencies for a docker host.
        /// </summary>
        /// <param name="builder">The IOC container builder.</param>
        /// <param name="dockerHostSettings">The settings for the docker host.</param>
        /// <param name="dockerContainerSettings">The settings for containers that
        /// will be launched on the docker host.</param>
        public static void RegisterDockerHostFactory(
            this ContainerBuilder builder,
            IConfigurationSection dockerHostSettings,
            IConfigurationSection dockerContainerSettings)
        {
            var hostSettings = ReadDockerHostSettings(dockerHostSettings);
            var containerSettings = dockerContainerSettings
                .GetChildren()
                .Select(ReadDockerContainerSettings)
                .ToList();

            builder.RegisterInstance(hostSettings).As<DockerHostConfig>();
            builder.RegisterType<DockerHostFactory>().As<IDockerHostFactory>().SingleInstance();
            builder.RegisterInstance(containerSettings).As<IList<DockerContainerConfig>>();
        }
Esempio n. 20
0
 /// <summary>
 ///   Converts the given <see cref = "IConfigurationSection" /> to an XML representation.
 /// </summary>
 /// <param name = "section">
 ///   The section to convert to XML.
 /// </param>
 /// <returns>
 ///   A XML representation of the <see cref = "IConfigurationSection" />.
 /// </returns>
 public static new XElement ToXml( IConfigurationSection section )
 {
     if ( section == null )
     {
         throw new ArgumentNullException( "section" );
     }
     var xml = new XElement( section.Name,
                             from setting in section
                             select new XElement( "add",
                                                  new XAttribute( "key", setting.Key ),
                                                  new XAttribute( "value", setting.Value )
                                     )
             );
     return xml;
 }
 /// <summary>
 /// Registers dependencies for the CSClassroom webapp.
 /// </summary>
 public static void RegisterCSClassroomWebApp(
     this ContainerBuilder builder,
     IConfigurationSection webAppSettings,
     IConfigurationSection githubSettings)
 {
     builder.RegisterInstance(GetHostName(webAppSettings)).As<WebAppHost>();
     builder.RegisterInstance(GetEmailAddress(webAppSettings)).As<WebAppEmail>();
     builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
     builder.RegisterType<ActionContextAccessor>().As<IActionContextAccessor>();
     builder.RegisterType<IdentityProvider>().As<IIdentityProvider>().InstancePerLifetimeScope();
     builder.RegisterType<TimeZoneProvider>().As<ITimeZoneProvider>().InstancePerLifetimeScope();
     builder.RegisterType<RandomNumberProvider>().As<IRandomNumberProvider>().InstancePerLifetimeScope();
     builder.RegisterType<BaseControllerArgs>().As<BaseControllerArgs>().InstancePerLifetimeScope();
     builder.RegisterType<LogContext>().As<ILogContext>().InstancePerLifetimeScope();
 }
Esempio n. 22
0
        public DataServerConfigSet(IConfigurationSection section)
        {
            MaxPoolSize = int.Parse(section["maxPoolSize"]);
            MinPoolSize = int.Parse(section["minPoolSize"]);
            Masters = from s in section.GetSection("masters").GetChildren()
                      select new DataServerConfig
                      {
                          serverUrl = s["url"]
                      };

            Slavers = from s in section.GetSection("slaves").GetChildren()
                      select new DataServerConfig
                      {
                          serverUrl = s["url"]
                      };
        }
        private void AddConfigurationSection(IConfigurationSection section)
        {
            if (this.tabControl.TabPages.ContainsKey(section.SectionName))
                return;

            Control control = (Control) section;
            TabPage configurationPage = new TabPage(section.SectionName);
            configurationPage.Controls.Add(control);
            this.tabControl.Selected += (s, e) =>
            {
                if (this.tabControl.SelectedTab.Text == section.SectionName)
                    section.Activated(s, e);
            };
            this.tabControl.TabPages.Add(configurationPage);
            control.Dock = DockStyle.Fill;
            section.LoadConfiguration(this, EventArgs.Empty);
            this.FormClosing += (s, e) => section.SaveConfiguration(s, e);
            this.FormClosed += (s,e) => Runtime.Instance.Settings.Save();
        }
Esempio n. 24
0
 public void Build(FormView form, IConfigurationSection section, IBinder binder, IDictionary<string, object> boundControls, IDictionary<string, object> dataSources)
 {
     if (null == form)
     {
         throw new ArgumentNullException("form");
     }
     if (null == section)
     {
         throw new ArgumentNullException("section");
     }
     if (null == binder)
     {
         throw new ArgumentNullException("binder");
     }
     this._boundControls = boundControls;
     this._boundControls.Clear();
     this._dataSources = dataSources;
     this._dataSources.Clear();
     form.EditItemTemplate = new TemplateHelper(this.BuildItemTemplate(section, binder, FormViewMode.Edit), section);
 }
        /// <summary>
        /// Registers dependencies for CSClassroom services.
        /// </summary>
        public static void RegisterCSClassroomService(
            this ContainerBuilder builder,
            IConfigurationSection serviceSettings)
        {
            builder.RegisterSource
            (
                new AnyConcreteTypeNotAlreadyRegisteredSource
                (
                    type => type.GetTypeInfo().Assembly.Equals
                    (
                        typeof(ContainerBuilderExtensions).GetTypeInfo().Assembly
                    )
                )
            );

            builder.RegisterInstance(GetActivationToken(serviceSettings)).As<ActivationToken>();
            builder.RegisterType<UserProvider>().As<IUserProvider>();

            builder.RegisterType<UserService>().As<IUserService>();
            builder.RegisterType<ClassroomService>().As<IClassroomService>();
            builder.RegisterType<SectionService>().As<ISectionService>();
            builder.RegisterType<QuestionCategoryService>().As<IQuestionCategoryService>();
            builder.RegisterType<QuestionService>().As<IQuestionService>();
            builder.RegisterType<AssignmentService>().As<IAssignmentService>();
            builder.RegisterType<ProjectService>().As<IProjectService>();
            builder.RegisterType<CheckpointService>().As<ICheckpointService>();
            builder.RegisterType<SubmissionService>().As<ISubmissionService>();
            builder.RegisterType<Projects.BuildService>().As<IBuildService>();
            builder.RegisterType<QuestionGenerator>().As<IQuestionGenerator>();
            builder.RegisterType<JavaCodeGenerationFactory>().As<IJavaCodeGenerationFactory>();
            builder.RegisterType<QuestionModelFactory>().As<IQuestionModelFactory>();
            builder.RegisterType<AssignmentScoreCalculator>().As<IAssignmentScoreCalculator>();
            builder.RegisterType<PushEventRetriever>().As<IPushEventRetriever>();
            builder.RegisterType<RepositoryMetadataRetriever>().As<IRepositoryMetadataRetriever>();
            builder.RegisterType<RepositoryPopulator>().As<IRepositoryPopulator>();
            builder.RegisterType<PushEventProcessor>().As<IPushEventProcessor>();
            builder.RegisterType<SubmissionCreator>().As<ISubmissionCreator>();
            builder.RegisterType<SubmissionDownloader>().As<ISubmissionDownloader>();
            builder.RegisterType<SubmissionArchiveBuilder>().As<ISubmissionArchiveBuilder>();
            builder.RegisterType<SubmissionFileTransformer>().As<ISubmissionFileTransformer>();
        }
Esempio n. 26
0
 public void Build(GridView grid, IConfigurationSection section, IDictionary<string, object> boundControls, IDictionary<string, object> dataSources)
 {
     this._boundControls = boundControls;
     this._dataSources = dataSources;
     if (null == grid)
     {
         throw new ArgumentNullException("grid");
     }
     if (null == section)
     {
         throw new ArgumentNullException("section");
     }
     foreach (IConfigurationElement element in section.Elements.Values)
     {
         if ("keys" == element.ConfigKey)
         {
             grid.DataKeyNames = element.GetAttributeReference("names").Value.ToString().Split(new char[]
             {
                 ','
             });
         }
         else
         {
             BoundField field = this.GetField(element);
             if (null != field)
             {
                 grid.Columns.Add(field);
             }
             this.ParseProperties(field, element);
             if (field is DropDownListField && !string.IsNullOrEmpty(field.DataField))
             {
                 this._boundControls.Add(field.DataField, field);
                 if (!this._dataSources.ContainsKey(field.DataField))
                 {
                     this._dataSources.Add(field.DataField, null);
                 }
             }
         }
     }
 }
Esempio n. 27
0
 private static int GetTokenTtl(IConfigurationSection configServerSection)
 {
     return(configServerSection.GetValue("tokenTtl", ConfigServerClientSettings.DEFAULT_VAULT_TOKEN_TTL));
 }
Esempio n. 28
0
 public static void Load(IConfigurationSection section)
 {
     Default = new Settings(section);
 }
        ///<inheritdoc/>
        public IPluginCatalog Convert(IConfigurationSection section)
        {
            var path = section.GetValue <string>("Path");

            return(new AssemblyPluginCatalog(path));
        }
        public static void AddGmailService(this IServiceCollection services, IConfigurationSection gmailSection)
        {
            ISmtpClient smtpClient = new GmailSmtpService(gmailSection["Email"], gmailSection["Password"]);

            services.AddSingleton(smtpClient);
        }
 private void RegisterConfiguredSecretStore(IConfigurationSection section, IServiceCollection services)
 => services.AddScoped <ISecretConfigValueProvider, ConfiguredSecretStore>(_logger);
Esempio n. 32
0
 /// <summary>
 ///     Registers a configuration instance which TOptions will bind against.
 /// </summary>
 /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
 /// <param name="name">The name of the options instance.</param>
 /// <param name="config">The configuration being bound.</param>
 public static IServiceCollection Configure <TOptions>(this IServiceCollection services, string name, IConfigurationSection config)
     where TOptions : class => services
 .AddOptions <TOptions>(name)
 .Bind(config)
 .ValidateDataAnnotations()
 .Services;
Esempio n. 33
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DrinkAppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity <AppUser>(options =>
            {
                options.SignIn.RequireConfirmedAccount  = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <DrinkAppContext>();

            services.AddLocalization();
            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.SetDefaultCulture("en-GB");
                options.AddSupportedCultures("en-GB", "pl-PL");
                options.AddSupportedUICultures("en-GB", "pl-PL");
                options.FallBackToParentUICultures = true;

                options
                .RequestCultureProviders
                .Remove(typeof(AcceptLanguageHeaderRequestCultureProvider));
            });

            services.AddAuthentication()
            .AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId     = Configuration["Authentication:Facebook:AppId"];
                facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            })
            .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                    Configuration.GetSection("Authentication:Google");

                options.ClientId     = googleAuthNSection["ClientId"];
                options.ClientSecret = googleAuthNSection["ClientSecret"];
            });

            services.AddScoped <IDrinkRepository, DrinkRepository>();
            services.AddScoped <IDrinkSearchService, DrinkSearchService>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <IReportingModuleService, ReportingModuleService>();
            services.AddScoped <IFavouriteRepository, FavouriteRepository>();
            services.AddScoped <ISettingRepository, SettingRepository>();

            services.AddScoped <IReviewRepository, ReviewRepository>();
            services.AddSingleton <BackgroundJobScheduler>();
            services.AddHostedService(provider => provider.GetService <BackgroundJobScheduler>());

            services
            .AddRazorPages()
            .AddViewLocalization();

            services.AddScoped <RequestLocalizationCookiesMiddleware>();
            services.AddControllersWithViews().
            AddRazorRuntimeCompilation().
            AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                                                          factory.Create(typeof(SharedResource));
            });

            services.AddHttpContextAccessor();
        }
Esempio n. 34
0
 private static string GetLabel(IConfigurationSection clientConfigsection)
 {
     return(clientConfigsection.GetValue <string>("label"));
 }
Esempio n. 35
0
 private static string GetUsername(IConfigurationSection clientConfigsection)
 {
     return(clientConfigsection.GetValue <string>("username"));
 }
Esempio n. 36
0
 private static bool GetHealthEnabled(IConfigurationSection clientConfigsection, bool def)
 {
     return(clientConfigsection.GetValue("health:enabled", def));
 }
Esempio n. 37
0
 private static string GetEnvironment(IConfigurationSection section, string def)
 {
     return(section.GetValue("env", string.IsNullOrEmpty(def) ? ConfigServerClientSettings.DEFAULT_ENVIRONMENT : def));
 }
Esempio n. 38
0
 private static bool GetCertificateValidation(IConfigurationSection clientConfigsection, bool def)
 {
     return(clientConfigsection.GetValue("validateCertificates", def) && clientConfigsection.GetValue("validate_certificates", def));
 }
Esempio n. 39
0
 private void MergeSectionIntoSource( IConfigurationSection section )
 {
     if ( _sections.ContainsKey( section.Name ) )
     {
         IConfigurationSection existingConfig = _sections[section.Name];
         foreach ( KeyValuePair<string, string> keyValuePair in section )
         {
             existingConfig.Set( keyValuePair.Key, keyValuePair.Value );
         }
     }
     else
     {
         section.PropertyChanged +=
                 ( s, e ) => OnPropertyChanged( ( (IConfigurationSection) s ).Name, e.PropertyName );
         _sections.Add( section.Name, section );
     }
 }
Esempio n. 40
0
        private string Expand( IConfigurationSection section, string key )
        {
            string result = section.Get( key, string.Empty );

            while ( true )
            {
                int startIndex = result.IndexOf( "${", 0, StringComparison.OrdinalIgnoreCase );
                if ( startIndex == -1 )
                {
                    break;
                }

                int endIndex = result.IndexOf( "}", startIndex + 2, StringComparison.OrdinalIgnoreCase );
                if ( endIndex == -1 )
                {
                    break;
                }

                string search = result.Substring( startIndex + 2, endIndex - ( startIndex + 2 ) );

                if ( string.Equals( search, key, StringComparison.OrdinalIgnoreCase ) )
                {
                    // Prevent infinite recursion
                    throw new ArgumentException( string.Format( Text.Culture, Text.KeyCannotExpandOnSelf0, key ) );
                }

                string replace = ExpandValue( section, search );

                result = result.Replace( "${" + search + "}", replace );
            }

            return result;
        }
Esempio n. 41
0
 public ApiBasicAuthClientProvider(IConfigurationSection apiConfiguration, HttpClient httpClient) : base(apiConfiguration, httpClient)
 {
 }
Esempio n. 42
0
 private static string GetPassword(IConfigurationSection clientConfigsection)
 {
     return(clientConfigsection.GetValue <string>("password"));
 }
Esempio n. 43
0
 public ApiBasicAuthClientProvider(IConfigurationSection apiConfiguration) : base(apiConfiguration)
 {
 }
Esempio n. 44
0
 private static string GetUri(IConfigurationSection clientConfigsection, string def)
 {
     return(clientConfigsection.GetValue("uri", def));
 }
Esempio n. 45
0
 /// <summary>
 ///     Registers a configuration instance which TOptions will bind against.
 /// </summary>
 /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
 /// <param name="config">The configuration being bound.</param>
 public static IServiceCollection Configure <TOptions>(this IServiceCollection services, IConfigurationSection config)
     where TOptions : class => services
 .Configure <TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config);
Esempio n. 46
0
 private static int GetTimeout(IConfigurationSection clientConfigsection, int def)
 {
     return(clientConfigsection.GetValue("timeout", def));
 }
        /// <summary>
        /// Adds a Memory logger named 'MemoryLogger' to the service collection.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to use.</param>
        /// <param name="configurationSection">The configuration section that maps to <see cref="MemoryLoggerSettings"/></param>
        public static IServiceCollection AddMemoryLogger(this IServiceCollection services, IConfigurationSection configurationSection)
        {
            MemoryLoggerSettings mLogSettings = configurationSection != null?configurationSection.Get <MemoryLoggerSettings>() : new MemoryLoggerSettings();

            var provider = new MemoryLoggerProvider(mLogSettings);

            services.AddSingleton(provider);
            return(services);
        }
Esempio n. 48
0
 private static string GetToken(IConfigurationSection clientConfigsection)
 {
     return(clientConfigsection.GetValue <string>("token"));
 }
        private FeatureSettings ReadFeatureSettings(IConfigurationSection configurationSection)
        {
            /*
             *
             * We support
             *
             * myFeature: {
             * enabledFor: [ "myFeatureFilter1", "myFeatureFilter2" ]
             * },
             * myDisabledFeature: {
             * enabledFor: [  ]
             * },
             * myFeature2: {
             * enabledFor: "myFeatureFilter1;myFeatureFilter2"
             * },
             * myDisabledFeature2: {
             * enabledFor: ""
             * },
             * myFeature3: "myFeatureFilter1;myFeatureFilter2",
             * myDisabledFeature3: "",
             * myAlwaysEnabledFeature: true,
             * myAlwaysDisabledFeature: false // removing this line would be the same as setting it to false
             * myAlwaysEnabledFeature2: {
             * enabledFor: true
             * },
             * myAlwaysDisabledFeature2: {
             * enabledFor: false
             * }
             *
             */

            var enabledFor = new List <FeatureFilterSettings>();

            string val = configurationSection.Value; // configuration[$"{featureName}"];

            if (string.IsNullOrEmpty(val))
            {
                val = configurationSection[FeatureFiltersSectionName];
            }

            if (!string.IsNullOrEmpty(val) && bool.TryParse(val, out bool result) && result)
            {
                //
                //myAlwaysEnabledFeature: true
                // OR
                //myAlwaysEnabledFeature: {
                //  enabledFor: true
                //}
                enabledFor.Add(new FeatureFilterSettings
                {
                    Name = "AlwaysOn"
                });
            }
            else
            {
                IEnumerable <IConfigurationSection> filterSections = configurationSection.GetSection(FeatureFiltersSectionName).GetChildren();

                foreach (IConfigurationSection section in filterSections)
                {
                    //
                    // Arrays in json such as "myKey": [ "some", "values" ]
                    // Are accessed through the configuration system by using the array index as the property name, e.g. "myKey": { "0": "some", "1": "values" }
                    if (int.TryParse(section.Key, out int i) && !string.IsNullOrEmpty(section[nameof(FeatureFilterSettings.Name)]))
                    {
                        enabledFor.Add(new FeatureFilterSettings()
                        {
                            Name       = section[nameof(FeatureFilterSettings.Name)],
                            Parameters = section.GetSection(nameof(FeatureFilterSettings.Parameters))
                        });
                    }
                }
            }

            return(new FeatureSettings()
            {
                Name = configurationSection.Key,
                EnabledFor = enabledFor
            });
        }
Esempio n. 50
0
 private static bool GetFailFast(IConfigurationSection clientConfigsection, bool def)
 {
     return(clientConfigsection.GetValue("failFast", def));
 }
Esempio n. 51
0
 public Settings(IConfigurationSection section)
 {
     this.CacheCount = GetValueOrDefault(section.GetSection("CacheCount"), 500, p => int.Parse(p));
     this.Backend    = section.GetSection("Backend").Value;
 }
Esempio n. 52
0
 private static bool GetRetryEnabled(IConfigurationSection clientConfigsection, bool def)
 {
     return(clientConfigsection.GetValue("retry:enabled", def));
 }
Esempio n. 53
0
 private Settings(IConfigurationSection section)
 {
     Path      = string.Format(section.GetValue("Path", "Data_MPT_{0}"), ProtocolSettings.Default.Magic.ToString("X8"));
     FullState = section.GetValue("FullState", false);
 }
Esempio n. 54
0
 private static int GetRetryInitialInterval(IConfigurationSection clientConfigsection, int def)
 {
     return(clientConfigsection.GetValue("retry:initialInterval", def));
 }
Esempio n. 55
0
 private static string GetClientId(IConfigurationSection configServerSection, IConfiguration config)
 {
     return(GetSetting("credentials:client_id", config.GetSection(VCAP_SERVICES_CONFIGSERVER_PREFIX), configServerSection, ConfigServerClientSettings.DEFAULT_CLIENT_ID));
 }
Esempio n. 56
0
 private static int GetTokenRenewRate(IConfigurationSection configServerSection)
 {
     return(configServerSection.GetValue("tokenRenewRate", ConfigServerClientSettings.DEFAULT_VAULT_TOKEN_RENEW_RATE));
 }
Esempio n. 57
0
        private string ExpandValue( IConfigurationSection section, string search )
        {
            string[] lookup = search.Split( '|' );

            string result = ( lookup.Length > 1 )
                                    ? GetResultFromExternalSection( lookup[0], lookup[1] )
                                    : GetResultFromCurrentSection( search, section );

            return result;
        }
Esempio n. 58
0
 private static string GetAccessTokenUri(IConfigurationSection configServerSection, IConfiguration config)
 {
     return(GetSetting("credentials:access_token_uri", config.GetSection(VCAP_SERVICES_CONFIGSERVER_PREFIX), configServerSection, ConfigServerClientSettings.DEFAULT_ACCESS_TOKEN_URI));
 }
Esempio n. 59
0
 private string GetSection( IConfigurationSection section )
 {
     var sectionBuilder = new StringBuilder();
     sectionBuilder.AppendLine( string.Format( Text.Culture, "[{0}]", section.Name ) );
     foreach ( KeyValuePair<string, string> pair in section )
     {
         sectionBuilder.AppendLine( string.Format( Text.Culture, "{0}{1}{2}", pair.Key, Delimiter, pair.Value ) );
     }
     return sectionBuilder.ToString();
 }
Esempio n. 60
0
 private static string GetApplicationName(IConfigurationSection primary, IConfiguration config, string defName)
 {
     return(GetSetting("name", primary, config.GetSection(SPRING_APPLICATION_PREFIX), defName));
 }