Ejemplo n.º 1
0
        static async Task Main(string[] args)
        {
            IConfigurationRefresher refresher     = null;
            IConfiguration          configuration = null;

            var builder = new ConfigurationBuilder();

            builder.AddAzureAppConfiguration(options =>
            {
                options
                .ConnectWithManagedIdentity("https://abc1234configstore.azconfig.io")
                .ConfigureRefresh(refresh =>
                {
                    refresh
                    .Register("test", refreshAll: true)
                    .SetCacheExpiration(TimeSpan.FromSeconds(1));
                });
                refresher = options.GetRefresher();
            });

            configuration = builder.Build();

            PrintConfig(configuration);
            await refresher.Refresh();

            PrintConfig(configuration);
        }
Ejemplo n.º 2
0
        private static async Task Run(CancellationToken token)
        {
            string        display = string.Empty;
            StringBuilder sb      = new StringBuilder();

            do
            {
                sb.Clear();

                // Trigger and wait for an async refresh for registered configuration settings
                await _refresher.Refresh();

                sb.AppendLine($"{Configuration["AppName"]} has been configured to run in {Configuration["Language"]}");
                sb.AppendLine();

                sb.AppendLine(string.Equals(Configuration["Language"], "spanish", StringComparison.OrdinalIgnoreCase) ? "Buenos Dias." : "Good morning");
                sb.AppendLine();

                sb.AppendLine("Press any key to exit...");

                display = sb.ToString();

                Console.Clear();
                Console.Write(display);

                await Task.Delay(1000);
            } while (!token.IsCancellationRequested);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            IConfiguration          configuration = null;
            IConfigurationRefresher refresher     = null;

            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient
                .AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            var builder = new ConfigurationBuilder();

            builder.AddAzureAppConfiguration(options =>
            {
                options
                .ConnectWithManagedIdentity("https://abc1234configstore.azconfig.io")
                .Use("MyApp1:*")
                .ConfigureRefresh(refresh =>
                {
                    refresh
                    .Register("MyApp1:Sentinel", refreshAll: true)
                    .SetCacheExpiration(TimeSpan.FromSeconds(1));
                }).UseAzureKeyVault(keyVaultClient);

                refresher = options.GetRefresher();
            });

            configuration = builder.Build();
            PrintConfig(configuration);
            refresher.Refresh().Wait();
            PrintConfig(configuration);
        }
 public async Task InvokeAsync(HttpContext context)
 {
     if (_refresher != null)
     {
         await _refresher.Refresh();
     }
     await _next(context);
 }
Ejemplo n.º 5
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
        {
            await configurationRefresher.Refresh();

            var myApp1Config = configuration.GetSection("MyApp1");

            return(new OkObjectResult(myApp1Config["Message"]));
        }
Ejemplo n.º 6
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return(Host.CreateDefaultBuilder(args)
                   // Configures app as Windows Service
                   .UseWindowsService()
                   // Configures other services, Options objects
                   .ConfigureServices((hostContext, services) =>
            {
                var storageSettings = hostContext.Configuration.GetSection("Storage");
                services.Configure <StorageSettings>(storageSettings);

                services.AddHostedService <Worker>();
                services.AddApplicationInsightsTelemetryWorkerService();
            })
                   // Sets up Azure App Config
                   .ConfigureAppConfiguration((hostContext, config) =>
            {
                var settings = config.Build();

                var applicationConfigurationEndpoint = hostContext.HostingEnvironment.IsDevelopment()
                                                       // Gets Azure App Config details from KeyVault
                        ? KeyVaultClient
                                                       .GetSecretAsync(settings["KeyVault"], "ApplicationConfiguration-ConnectionString")
                                                       .Result.Value
                                                       // Falls back to app.settings.json
                        : settings["AppConfiguration:ConnectionString"];

                config.AddAzureAppConfiguration(options =>
                {
                    var appConfigurationOptions = hostContext.HostingEnvironment.IsDevelopment()
                                                  // Uses connections string
                            ? options.Connect(applicationConfigurationEndpoint)
                                                  // Uses Azure Managed Identity
                            : options.Connect(new Uri(applicationConfigurationEndpoint),
                                              new ManagedIdentityCredential());

                    appConfigurationOptions
                    .ConfigureRefresh(refresh =>
                    {
                        refresh.Register("Storage:ConnectionString", "Label1")
                        .Register("ApplicationInsights:InstrumentationKey", "Label1")
                        .SetCacheExpiration(TimeSpan.FromSeconds(1));
                    })
                    .UseAzureKeyVault(KeyVaultClient);

                    // Settings Auto-Refresh
                    _refresher = options.GetRefresher();

                    _timer = new Timer(async _ => await _refresher.Refresh().ConfigureAwait(false),
                                       null,
                                       TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
                });
            }));
        }
Ejemplo n.º 7
0
 public void Run([TimerTrigger("*/5 * * * * *")] TimerInfo myTimer)
 {
     try
     {
         configurationRefresher.Refresh();
     }
     catch (KeyVaultReferenceException)
     {
         // Keyvalue reference error. log exception and/or throw. Propagate as appropriate.
     }
     catch (Exception)
     {
         // log exception and / or throw.
         // Ignore unknown errors for now (not the best approach).
     }
 }
Ejemplo n.º 8
0
        public async Task <string> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
        {
            // Signal to refresh the configuration watched keys are modified. This will be no-op
            // if the cache expiration time window is not reached.
            _configRefresher.Refresh(); // Can do sync by adding await

            // CONFIG (standard)
            var configValue = _config[ConfigKeys.FnMessage];

            // CONFIG (from KV)
            var kvConfigValue = _config[ConfigKeys.AKVSourcedSecret];

            // FEATURE
            var featureValue = _features.IsEnabled(Features.FlipFlop);

            return($"Config: {configValue} || Feature: {featureValue} || From KV: {kvConfigValue}");
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (_refresher != null)
            {
                var policy = Policy
                             .Handle <KeyVaultReferenceException>()
                             .Or <Exception>()
                             .WaitAndRetryAsync(3, s =>
                {
                    return(TimeSpan.FromSeconds(2 * s));
                },
                                                onRetry: (response, delay, retryCount, context) =>
                {
                    // log on retry if required.
                });

                await policy.ExecuteAsync(async() =>
                {
                    await _refresher.Refresh();
                });
            }
            await _next(context);
        }
 public void Run([TimerTrigger("*/5 * * * * *")] TimerInfo myTimer, ILogger log)
 {
     configurationRefresher.Refresh();
 }