Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add options
            services
            .Configure <CacheOptions>(Configuration.GetSection("Cache"))
            .Configure <NbuClientOptions>(Configuration.GetSection("Client"))
            .Configure <RatesOptions>(Configuration.GetSection("Rates"));

            services.AddAuthentication(CustomAuthSchema.Name)
            .AddScheme <CustomAuthSchemaOptions, CustomAuthSchemaHandler>(
                CustomAuthSchema.Name, CustomAuthSchema.Name, null);

            // Add application services
            services.AddScoped <IRatesService, RatesService>();
            services.AddTransient <IUserStorageService, UserStorageService>();

            // Add NbuClient as Transient
            services.AddHttpClient <IRatesProviderClient, NbuClient>()
            .ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(10));

            services.AddDbContext <UserStorageContext>(options =>
                                                       options.UseNpgsql(Configuration.GetConnectionString("UserStorageContext")), ServiceLifetime.Transient);

            // Add CacheHostedService as Singleton
            services.AddHostedService <CacheHostedService>();
            services.AddSingleton <RegistrationExceptions>();
            services.AddSingleton <RecyclableMemoryStreamManager>();
            // Add batch of Swashbuckle Swagger services
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "DI Demo App API", Version = "v1"
                });
                var filePath = ConfigurationPath.Combine(AppContext.BaseDirectory + "DepsWebApp.xml");
                if (File.Exists(filePath))
                {
                    c.IncludeXmlComments(filePath);
                }
            });

            // Add batch of framework services
            services.AddMemoryCache();
            services.AddControllers();
        }
Пример #2
0
        public static GetRuleValue GetRulesEvaluator(IdentityHashSet identities, GetLoadedContextByIdentityType contextByIdentity, GetRule getRule)
        {
            var identityTypes  = identities.Select(x => x.Type).ToArray();
            var flattenContext = ContextHelpers.FlattenLoadedContext(contextByIdentity);

            GetRuleValue    getRuleValue     = null;
            GetContextValue recursiveContext = key =>
            {
                if (key.StartsWith("@@key:"))
                {
                    key = key.Replace("@@key:", "keys.");
                }
                if (!key.StartsWith("keys."))
                {
                    return(Option <JsonValue> .None);
                }
                var path = new ConfigurationPath(key.Split('.')[1]);
                return(getRuleValue(path).Map(x => x.Value));
            };

            var context = ContextHelpers.Merge(flattenContext, recursiveContext);

            getRuleValue = Memoize(path =>
            {
                try
                {
                    foreach (var identity in identityTypes)
                    {
                        var fixedResult = ContextHelpers.GetFixedConfigurationContext(context, identity)(path);
                        if (fixedResult.IsSome)
                        {
                            return(fixedResult);
                        }
                    }

                    return(getRule(path).Bind(x => x.GetValue(context)));
                }
                catch (Exception e)
                {
                    return(ConfigurationValue.Error(e));
                }
            });
            return(getRuleValue);
        }
Пример #3
0
        private async Task <IDictionary <string, string> > ExecuteQueryAsync(bool isBlocking = false)
        {
            //?recurse=true以递归方式查询任何节点
            var requestUri = isBlocking ? $"?recurse=true&index={_consulConfigurationIndex}" : "?recurse=true";

            using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_consulUrls[_consulUrlIndex], requestUri)))
                using (var response = await _httpClient.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Headers.Contains(ConsulIndexHeader))
                    {
                        var indexValue = response.Headers.GetValues(ConsulIndexHeader).FirstOrDefault();
                        int.TryParse(indexValue, out _consulConfigurationIndex);
                    }

                    var tokens = JToken.Parse(await response.Content.ReadAsStringAsync());
                    List <KeyValuePair <string, JToken> > pairs  = null;
                    Dictionary <string, string>           retDic = null;
                    //我这里实际只有一个token
                    int tokenCount = tokens.Count();
                    if (tokenCount == 1)
                    {
                        string valueStr = tokens[0].Value <string>("Value");
                        JToken value    = string.IsNullOrEmpty(valueStr) ? null : JToken.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(valueStr)));
                        pairs = new List <KeyValuePair <string, JToken> >(1);
                        pairs.Add(KeyValuePair.Create(string.Empty, value));
                    }
                    else if (tokenCount > 1)
                    {
                        pairs = tokens.Select(k => KeyValuePair.Create
                                              (
                                                  k.Value <string>("Key").Substring(_path.Length + 1),
                                                  k.Value <string>("Value") != null ? JToken.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(k.Value <string>("Value")))) : null
                                              ))
                                .Where(v => !string.IsNullOrWhiteSpace(v.Key)).ToList();
                    }
                    if (pairs != null)
                    {
                        retDic = pairs.SelectMany(Flatten)
                                 .ToDictionary(v => ConfigurationPath.Combine(v.Key.Split('/')), v => v.Value, StringComparer.OrdinalIgnoreCase);
                    }
                    return(retDic);
                }
        }
        public override void Load()
        {
            // TODO: react to configuration changes by listening to ConfiugrationPackageActivationContext.ConfigurationPackageModifiedEvent

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject(this.configurationPackageName);

            foreach (var configurationSection in configPackage.Settings.Sections)
            {
                foreach (var property in configurationSection.Parameters)
                {
                    // We omit encrypted values due to security concerns--if you need them, use Service Fabric APIs to access them
                    if (!property.IsEncrypted)
                    {
                        Data[ConfigurationPath.Combine(configurationSection.Name, property.Name)] = property.Value;
                    }
                }
            }
        }
        /// <summary>
        ///     Parses command line arguments from the specified string and maps them to the corresponding keys.
        /// </summary>
        public override void Load()
        {
            var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary;

            void Map(Type type, string path)
            {
                var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo property in props)
                {
                    var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute));
                    var key       = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());

                    if (attribute != default)
                    {
                        var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString();
                        var longName = (string)attribute.ConstructorArguments[1].Value;
                        var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i));

                        foreach (var argument in arguments)
                        {
                            if (dictionary.ContainsKey(argument))
                            {
                                var value = dictionary[argument].ToString();

                                if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value))
                                {
                                    value = "true";
                                }

                                Data[key] = value;
                            }
                        }
                    }
                    else
                    {
                        Map(property.PropertyType, key);
                    }
                }
            }

            Map(TargetType, Namespace);
        }
Пример #6
0
        private string BuildLogLevelPath(string?category, out string?additionalPath)
        {
            var segments = _parentPath.ToList();

            segments.Add("MinimumLevel");

            if (!String.IsNullOrWhiteSpace(category))
            {
                segments.Add("Override");
                segments.Add(category !.Trim());
                additionalPath = null;
            }
            else
            {
                additionalPath = ConfigurationPath.Combine(segments.Concat(new[] { "Default" }));
            }

            return(ConfigurationPath.Combine(segments));
        }
Пример #7
0
        internal static bool ConsoleLoggingEnabled(HostBuilderContext context)
        {
            // console logging defaults to false, except for self host
            bool enableConsole = context.HostingEnvironment.IsDevelopment();

            if (!enableConsole)
            {
                string consolePath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "Logging", "Console", "IsEnabled");
                IConfigurationSection configSection = context.Configuration.GetSection(consolePath);

                if (configSection.Exists())
                {
                    // if it has been explicitly configured that value overrides default
                    enableConsole = configSection.Get <bool>();
                }
            }

            return(enableConsole);
        }
Пример #8
0
        // Common attributes contribute to key-value pairs
        // This method adds a key-value pair if current node in reader represents a common attribute
        private static void AddAttributePair(XmlReader reader, Stack <string> prefixStack,
                                             IDictionary <string, string> data, XmlWriter writer)
        {
            if (string.Equals(reader.LocalName, NameAttributeKey, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            prefixStack.Push(reader.LocalName);
            var key = ConfigurationPath.Combine(prefixStack.Reverse());

            if (data.ContainsKey(key))
            {
                throw new FormatException(Resources.FormatError_KeyIsDuplicated(key, GetLineInfo(reader)));
            }

            data[key] = reader.Value;
            prefixStack.Pop();
        }
Пример #9
0
        public static IdentityMapNameTransfer FromTypeAttributes(string prevPathName, Type type, bool usingClassPathName)
        {
            var baseName = prevPathName;

            if (usingClassPathName)
            {
                var className = type.GetCustomAttribute <ConfigPathAttribute>();
                if (className != null)
                {
                    baseName = ConfigurationPath.Combine(baseName, className.Name);
                }
            }
            var map = type.GetProperties()
                      .Select(x => new { Property = x, Attribute = x.GetCustomAttribute <ConfigPathAttribute>() })
                      .Where(x => x.Attribute != null)
                      .ToDictionary(x => new PropertyIdentity(type, x.Property.Name), x => x.Attribute.Name);

            return(new IdentityMapNameTransfer(baseName, map));
        }
Пример #10
0
        public string Transfer(object instance, string propertyName)
        {
            if (instance  is null)
            {
                return(propertyName);
            }
            var parent = instance.GetType().BaseType;
            var name   = propertyName;

            if (!Map.TryGetValue(new PropertyIdentity(parent, propertyName), out name))
            {
                name = propertyName;
            }
            if (BasePath != null)
            {
                return(ConfigurationPath.Combine(BasePath, name));
            }
            return(name);
        }
Пример #11
0
        public void Configuration_BindsTo_AggregatorOptions()
        {
            IHost host = new HostBuilder()
                         .ConfigureAppConfiguration(c =>
            {
                c.AddInMemoryCollection(new Dictionary <string, string>
                {
                    { ConfigurationPath.Combine(AggregatorPath, "BatchSize"), "33" },
                    { ConfigurationPath.Combine(AggregatorPath, "FlushTimeout"), "00:00:33" }
                });
            })
                         .ConfigureDefaultTestWebScriptHost()
                         .Build();

            var options = host.Services.GetService <IOptions <FunctionResultAggregatorOptions> >().Value;

            Assert.Equal(33, options.BatchSize);
            Assert.Equal(TimeSpan.FromSeconds(33), options.FlushTimeout);
        }
        private static void AddConsoleIfEnabled(ILoggingBuilder builder, bool isDevelopment, IConfiguration configuration)
        {
            // console logging defaults to false, except for self host
            bool enableConsole = isDevelopment;

            string consolePath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "Logging", "Console", "IsEnabled");
            IConfigurationSection configSection = configuration.GetSection(consolePath);

            if (configSection.Exists())
            {
                // if it has been explicitly configured that value overrides default
                enableConsole = configSection.Get <bool>();
            }

            if (enableConsole)
            {
                builder.AddConsole();
            }
        }
Пример #13
0
        // The special attribute "Name" only contributes to prefix
        // This method adds a prefix if current node in reader represents a "Name" attribute
        private static void AddNamePrefix(XmlReader reader, Stack <string> prefixStack,
                                          IDictionary <string, string> data, XmlWriter writer)
        {
            if (!string.Equals(reader.LocalName, NameAttributeKey, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            // If current element is not root element
            if (prefixStack.Any())
            {
                var lastPrefix = prefixStack.Pop();
                prefixStack.Push(ConfigurationPath.Combine(lastPrefix, reader.Value));
            }
            else
            {
                prefixStack.Push(reader.Value);
            }
        }
Пример #14
0
        /// <summary>
        ///     Loads default values from the specified <see cref="TargetType"/> and maps them to the corresponding keys.
        /// </summary>
        public override void Load()
        {
            void Map(Type type, string path)
            {
                var defaults = Activator.CreateInstance(type);
                var props    = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo property in props)
                {
                    var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());

                    if (property.PropertyType.Namespace.StartsWith(Namespace))
                    {
                        Map(property.PropertyType, key);
                    }
                    else
                    {
                        // don't add array values to the configuration; these are additive across providers
                        // and the default value from the class is "stuck", so adding them again results in duplicates.
                        if (!property.PropertyType.IsArray)
                        {
                            var value = property.GetValue(defaults);

                            if (value != null)
                            {
                                Data[key] = value.ToString();
                            }
                        }
                        else
                        {
                            // serialize array defaults and stick them on the parent key
                            // (not indexed by array position).  this value is "stuck", and
                            // we want to show that in the config debug view.  this isn't really
                            // functional, just illustrative.
                            Data[key] = JsonSerializer.Serialize(property.GetValue(defaults));
                        }
                    }
                }
            }

            Map(TargetType, Namespace);
        }
        public void ConfigureLanguageWorkers_DefaultMaxMessageLength_IfDynamic()
        {
            var settings = new Dictionary <string, string>
            {
                { ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, LanguageWorkerConstants.LanguageWorkersSectionName, "maxMessageLength"), "250" }
            };

            var environment = new TestEnvironment();

            environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteSku, "Dynamic");

            var options = GetConfiguredOptions(settings, environment);

            // TODO: Logger is currently disabled
            //string message = $"Cannot set {nameof(scriptConfig.MaxMessageLengthBytes)} on Consumption plan. Default MaxMessageLength: {ScriptHost.DefaultMaxMessageLengthBytesDynamicSku} will be used";
            //var logs = testLogger.GetLogMessages().Where(log => log.FormattedMessage.Contains(message)).FirstOrDefault();
            //Assert.NotNull(logs);

            Assert.Equal(LanguageWorkerConstants.DefaultMaxMessageLengthBytesDynamicSku, options.MaxMessageLengthBytes);
        }
        /// <summary>
        /// Gets a configuration enumeration for a particular
        /// provider
        /// </summary>
        /// <param name="config">root configuration</param>
        /// <param name="providerType">provider type</param>
        /// <returns>enumerable of configuration sections</returns>
        public static IEnumerable <IConfigurationSection> GetConfiguration(this IConfiguration config, Type providerType)
        {
            var    root = config as IConfigurationRoot;
            string path = null;

            //filter the list of providers
            var providers = root.Providers.Where(p => p.GetType() == providerType);

            //build the configuration enumeration for the provider.
            //use the Aggregate extension method to build the
            //configuration cumulatively.
            //(see https://github.com/aspnet/Configuration/blob/master/src/Config/ConfigurationRoot.cs)
            var entries = providers
                          .Aggregate(Enumerable.Empty <string>(),
                                     (seed, source) => source.GetChildKeys(seed, path))
                          .Distinct()
                          .Select(key => GetSection(root, path == null ? key : ConfigurationPath.Combine(path, key)));

            return(entries);
        }
Пример #17
0
        private string GetOneConfigPath(ConfigurationPath config)
        {
            switch (config)
            {
            case ConfigurationPath.EnvLocal:
                return(this.GetEnvironmentVariableValue(ConfigurationFileGetter.LocalEnvironmentName));

            case ConfigurationPath.EnvGlobal:
                return(this.GetEnvironmentVariableValue(ConfigurationFileGetter.DefaultEnvironmentName));

            case ConfigurationPath.DefaultLocal:
                return(ConfigurationFileGetter.LocalPathName);

            case ConfigurationPath.DefaultGlobal:
                return(ConfigurationFileGetter.DefaultPathName);

            default:
                throw new IndexOutOfRangeException($"case '{config}' out of range");
            }
        }
Пример #18
0
 private void AddSecret(VaultKeyValueSecret secret)
 {
     foreach (var pair in secret.Values)
     {
         if (pair.Value is JObject json)
         {
             var jsonData = new JsonObjectParser().Parse(json);
             foreach (var jsonPair in jsonData)
             {
                 var key = ConfigurationPath.Combine(secret.Key, pair.Key, jsonPair.Key);
                 Data.Add(key, jsonPair.Value);
             }
         }
         else
         {
             var key = ConfigurationPath.Combine(secret.Key, pair.Key);
             Data.Add(key, Convert.ToString(pair.Value));
         }
     }
 }
        public static void BindConfiguration_UpdatesOptionOnConfigurationUpdate()
        {
            const string configSectionName = "Test";
            string       messageConfigKey  = ConfigurationPath.Combine(configSectionName, nameof(FakeOptions.Message));
            const string messageValue1     = "This is a test";
            const string messageValue2     = "This is the message after update";

            FakeConfigurationSource configSource = new()
            {
                InitialData = new Dictionary <string, string?>
                {
                    [messageConfigKey] = messageValue1
                }
            };

            var services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(new ConfigurationBuilder()
                                                   .Add(configSource)
                                                   .Build());
            OptionsBuilder <FakeOptions> optionsBuilder = services.AddOptions <FakeOptions>();

            _ = optionsBuilder.BindConfiguration(configSectionName);
            using ServiceProvider serviceProvider = services.BuildServiceProvider();
            var  optionsMonitor = serviceProvider.GetRequiredService <IOptionsMonitor <FakeOptions> >();
            bool updateHasRun   = false;

            optionsMonitor.OnChange((opts, name) =>
            {
                updateHasRun = true;
            });
            FakeOptions optionsValue1 = optionsMonitor.CurrentValue;

            Assert.Equal(messageValue1, optionsValue1.Message);
            configSource.Provider.Set(messageConfigKey, messageValue2);
            FakeOptions optionsValue2 = optionsMonitor.CurrentValue;

            Assert.True(updateHasRun);
            Assert.Equal(messageValue2, optionsValue2.Message);
        }
    }
Пример #20
0
        private async Task <IDictionary <string, string> > ExecuteQueryAsync(bool isBlocking = false)
        {
            IDictionary <string, string> result;
            var relativeUri = isBlocking ? $"?recurse=true&index={_consulConfigurationIndex}" : "?recurse=true";
            var fullUri     = string.Empty;

            using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_consulUrls[_consulUrlIndex], relativeUri)))
            {
                fullUri = request.RequestUri.ToString();
                try
                {
                    using (var response = await _httpClient.SendAsync(request))
                    {
                        response.EnsureSuccessStatusCode();
                        if (response.Headers.Contains(ConsulIndexHeader))
                        {
                            var indexValue = response.Headers.GetValues(ConsulIndexHeader).FirstOrDefault();
                            int.TryParse(indexValue, out _consulConfigurationIndex);
                        }

                        var tokens = JToken.Parse(await response.Content.ReadAsStringAsync());
                        result = tokens
                                 .Select(k => KeyValuePair.Create
                                         (
                                             //k.Value<string>("Key").Substring(_path.Length + 1),
                                             k.Value <string>("Key"),
                                             k.Value <string>("Value") != null ? JToken.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(k.Value <string>("Value")))) : null
                                         ))
                                 .Where(v => !string.IsNullOrWhiteSpace(v.Key))
                                 .SelectMany(Flatten)
                                 .ToDictionary(v => ConfigurationPath.Combine(v.Key.Split('/')), v => v.Value, StringComparer.OrdinalIgnoreCase);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"{ex.Message}({fullUri})", ex);
                }
            }

            return(result);
        }
Пример #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var path = Directory.GetCurrentDirectory() + "/wwwroot";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            services.AddSingleton <IFileProvider>(
                new PhysicalFileProvider(
                    ConfigurationPath.Combine(Directory.GetCurrentDirectory() + "/wwwroot")));


            services.AddDbContext <DataContext>(opt => opt.UseMySql("server=localhost;database=DataManager;user=root;password=w2ter2468"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            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
                };
            });

            services.AddScoped <IUserService, UserService>();
        }
Пример #22
0
        public void Configure_AppliesTimeoutLimits_IfDynamic()
        {
            string configPath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout");
            var    settings   = new Dictionary <string, string>
            {
                { configPath, (ScriptHostOptionsSetup.MaxFunctionTimeoutDynamic + TimeSpan.FromSeconds(1)).ToString() }
            };

            var environment = new TestEnvironment();

            environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteSku, "Dynamic");

            var ex = Assert.Throws <ArgumentException>(() => GetConfiguredOptions(settings, environment));
            var expectedMessage = "FunctionTimeout must be greater than 00:00:01 and less than 00:10:00.";

            Assert.Equal(expectedMessage, ex.Message);

            settings[configPath] = (ScriptHostOptionsSetup.MinFunctionTimeout - TimeSpan.FromSeconds(1)).ToString();
            ex = Assert.Throws <ArgumentException>(() => GetConfiguredOptions(settings, environment));
            Assert.Equal(expectedMessage, ex.Message);
        }
        public void LoggerProviders_ConsoleEnabled_InConfiguration()
        {
            IHost host = new HostBuilder()
                         .ConfigureAppConfiguration(c =>
            {
                c.AddInMemoryCollection(new Dictionary <string, string>
                {
                    { ConfigurationPath.Combine(_loggingPath, "Console", "IsEnabled"), "True" }
                });
            })
                         .ConfigureDefaultTestWebScriptHost()
                         .Build();

            IEnumerable <ILoggerProvider> loggerProviders = host.Services.GetService <IEnumerable <ILoggerProvider> >();

            Assert.Equal(4, loggerProviders.Count());
            loggerProviders.OfType <SystemLoggerProvider>().Single();
            loggerProviders.OfType <HostFileLoggerProvider>().Single();
            loggerProviders.OfType <FunctionFileLoggerProvider>().Single();
            loggerProviders.OfType <ConsoleLoggerProvider>().Single();
        }
Пример #24
0
        private static IConfiguration BuildUnifiedConfiguration()
        {
            var firstPassBuilder = new ConfigurationBuilder();

            AddConfigurationSourcesToBuilder(firstPassBuilder);
            var firstPassConfiguration = firstPassBuilder.Build();

            var keyVaultConfiguration       = firstPassConfiguration.GetSection(ConfigurationPath.Combine("Server", "KeyVault"));
            var useKeyVaultForConfiguration = firstPassConfiguration.GetValue <bool>(ConfigurationPath.Combine("Server", "ConfigureFromKeyVault"));

            if (keyVaultConfiguration.Exists() && useKeyVaultForConfiguration)
            {
                var builder = new ConfigurationBuilder();
                AddConfigurationSourcesToBuilder(builder, keyVaultConfiguration);
                return(builder.Build());
            }
            else
            {
                return(firstPassConfiguration);
            }
        }
        /// <summary>
        /// 获取Zookeeper中的数据
        /// </summary>
        /// <returns></returns>
        public IDictionary <string, string> Process()
        {
            var data = zookeeperHelper.GetDictionaryAsync(ConfigurationPath.KeyDelimiter).GetAwaiter().GetResult();

            if (!zookeeperConfigurationProvider.ZookeeperConfigurationSource.ZookeeperOptions.ExcludeRoot)
            {
                return(data);
            }

            var root       = this.zookeeperConfigurationProvider.ZookeeperConfigurationSource.ZookeeperOptions.RootPath ?? "";
            var rootSplits = root.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            IDictionary <string, string> dict = new Dictionary <string, string>();

            foreach (var key in data.Keys)
            {
                var split = key.Split(new string[] { ConfigurationPath.KeyDelimiter }, StringSplitOptions.RemoveEmptyEntries);
                var array = split.Skip(rootSplits.Length).ToArray();
                dict[ConfigurationPath.Combine(array)] = data[key];
            }
            return(dict);
        }
        public void Logging_Binds_AppInsightsOptions()
        {
            IHost host = new HostBuilder()
                         .ConfigureAppConfiguration(c =>
            {
                c.AddInMemoryCollection(new Dictionary <string, string>
                {
                    { "APPINSIGHTS_INSTRUMENTATIONKEY", "some_key" },
                    { ConfigurationPath.Combine(_loggingPath, "ApplicationInsights", "SamplingSettings", "IsEnabled"), "false" },
                    { ConfigurationPath.Combine(_loggingPath, "ApplicationInsights", "SnapshotConfiguration", "IsEnabled"), "false" }
                });
            })
                         .ConfigureDefaultTestWebScriptHost()
                         .Build();

            ApplicationInsightsLoggerOptions appInsightsOptions = host.Services.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;

            Assert.Equal("some_key", appInsightsOptions.InstrumentationKey);
            Assert.Null(appInsightsOptions.SamplingSettings);
            Assert.False(appInsightsOptions.SnapshotConfiguration.IsEnabled);
        }
        private IWebHostBuilder CreateStandbyHostBuilder(params string[] functions)
        {
            string scriptRootConfigPath = ConfigurationPath.Combine(ConfigurationSectionNames.WebHost, nameof(ScriptApplicationHostOptions.ScriptPath));

            var builder = Program.CreateWebHostBuilder()
                          .ConfigureLogging(b =>
            {
                b.AddProvider(_loggerProvider);
            })
                          .ConfigureAppConfiguration(c =>
            {
                c.AddInMemoryCollection(new Dictionary <string, string>
                {
                    { scriptRootConfigPath, _specializedScriptRoot }
                });
            })
                          .ConfigureServices((bc, s) =>
            {
                s.AddSingleton <IEnvironment>(_environment);

                // Ensure that we don't have a race between the timer and the
                // request for triggering specialization.
                s.AddSingleton <IStandbyManager, InfiniteTimerStandbyManager>();

                s.AddSingleton <IScriptHostBuilder, PausingScriptHostBuilder>();
            })
                          .ConfigureScriptHostServices(s =>
            {
                s.PostConfigure <ScriptJobHostOptions>(o =>
                {
                    // Only load the function we care about, but not during standby
                    if (o.RootScriptPath != _standbyPath)
                    {
                        o.Functions = functions;
                    }
                });
            });

            return(builder);
        }
Пример #28
0
        public static void BindConfiguration_UsesConfigurationSectionPath()
        {
            const string configSectionName = "Test";
            const string messageValue      = "This is a test";
            var          configEntries     = new Dictionary <string, string>
            {
                [ConfigurationPath.Combine(configSectionName, nameof(FakeOptions.Message))] = messageValue
            };
            var services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(new ConfigurationBuilder()
                                                   .AddInMemoryCollection(configEntries)
                                                   .Build());
            var optionsBuilder = services.AddOptions <FakeOptions>();

            _ = optionsBuilder.BindConfiguration(configSectionName);

            using ServiceProvider serviceProvider = services.BuildServiceProvider();
            var options = serviceProvider.GetRequiredService <IOptions <FakeOptions> >().Value;

            Assert.Equal(messageValue, options.Message);
        }
Пример #29
0
 private void TraverseTree(JObject tree, Dictionary <string, string> data, string parentName)
 {
     foreach (var leaf in tree)
     {
         if (leaf.Value.Type == JTokenType.Object)
         {
             TraverseTree((JObject)leaf.Value, data, ConfigurationPath.Combine(parentName, leaf.Key));
         }
         else if (leaf.Value.Type == JTokenType.Array)
         {
             int idx = 0;
             foreach (var item in leaf.Value)
             {
                 TraverseTree((JObject)item, data, ConfigurationPath.Combine(parentName, leaf.Key, idx.ToString()));
             }
         }
         else
         {
             data.Add(ConfigurationPath.Combine(parentName, leaf.Key), leaf.Value.ToObject <string>());
         }
     }
 }
Пример #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "webapi v1"));
                var xmlfile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = ConfigurationPath.Combine(AppContext.BaseDirectory, xmlfile);
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }