Esempio n. 1
0
        static async Task Main(string[] args)
        {
            ISerializer serializer    = new Serializer();
            var         loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddConsole()
                .AddEventLog();
            });
            ILogger logger = loggerFactory.CreateLogger <Program>();

            var connectionStringKeyVaultFetchStore = new SimpleStringKeyVaultFetchStore(
                new KeyVaultFetchStoreOptions <string>()
            {
                ExpirationSeconds = 3600,
                KeyVaultName      = "kv-queueflow",
                SecretName        = "stazfuncqueueflow-primary-connection-string"
            }, logger);

            var connectionString = await connectionStringKeyVaultFetchStore.GetStringValueAsync();



            var accountName = "stazfuncqueueflow";
            var queueName   = "queue-main";

            string queueUri = $"https://{accountName}.queue.core.windows.net/{queueName}";

            // Get a credential and create a client object for the blob container.
            //           QueueClient queueClient = new QueueClient(new Uri(queueUri),new DefaultAzureCredential());
            QueueClient queueClient = new QueueClient(connectionString, queueName);
            // Create the queue
            await queueClient.CreateAsync();


            while (true)
            {
                QueueMessage[] messages = await queueClient.ReceiveMessagesAsync(maxMessages : 10);

                // Process and delete messages from the queue
                foreach (QueueMessage message in messages)
                {
                    var decoded = message.MessageText.Base64Decode();
                    // "Process" the message
                    Console.WriteLine($"Message: {message.MessageText} - {decoded}");
                    var job = serializer.Deserialize <Job>(decoded);

                    // Let the service know we're finished with
                    // the message and it can be safely deleted.
                    await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
                }

                Thread.Sleep(1000);
            }
        }
        public async Task <string> GetSecretAsync(string keyVaultName, string secretName)
        {
            try
            {
                var kvFetchStore = new SimpleStringKeyVaultFetchStore(
                    new KeyVaultFetchStoreOptions <string>()
                {
                    ExpirationSeconds = 3600,
                    KeyVaultName      = keyVaultName,
                    SecretName        = secretName
                }, _keyVaultClient, _logger);
                var secret = await kvFetchStore.GetStringValueAsync();

                return(secret);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
            return(null);
        }
Esempio n. 3
0
        static async Task Main(string[] args)
        {
            ISerializer serializer    = new Serializer();
            var         loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddConsole()
                .AddEventLog();
            });
            ILogger logger = loggerFactory.CreateLogger <Program>();

            var connectionStringKeyVaultFetchStore = new SimpleStringKeyVaultFetchStore(
                new KeyVaultFetchStoreOptions <string>()
            {
                ExpirationSeconds = 3600,
                KeyVaultName      = "kv-queueflow",
                SecretName        = "stazfuncqueueflow-primary-connection-string"
            }, logger);

            var connectionString = await connectionStringKeyVaultFetchStore.GetStringValueAsync();



            var accountName = "stazfuncqueueflow";
            var queueName   = "queue-main";

            string queueUri = $"https://{accountName}.queue.core.windows.net/{queueName}";

            // Get a credential and create a client object for the blob container.
            //           QueueClient queueClient = new QueueClient(new Uri(queueUri),new DefaultAzureCredential());
            QueueClient queueClient = new QueueClient(connectionString, queueName);
            // Create the queue
            await queueClient.CreateAsync();

            Console.WriteLine("\nAdding messages to the queue...");

            int index = 0;

            while (true)
            {
                // Send several messages to the queue
                for (int i = 0; i < 10; i++)
                {
                    var job = new Job
                    {
                        Id         = Guid.NewGuid().ToString(),
                        IssuedTime = DateTime.UtcNow,
                        Name       = "My SuperDuper Job"
                    };
                    var json = serializer.Serialize(job);

                    var encodedMsg = json.Base64Encode();
                    await queueClient.SendMessageAsync(encodedMsg);

                    Console.WriteLine(encodedMsg);
                    index++;
                }
                Thread.Sleep(1000);
            }
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                _logger.LogInformation("ConfigureServices");



                var nameKeyVault           = "kv-shorturl2";
                var snCosmosConfigTemplate = "cosmosConfigTemplateProduction";
                var snCosmosPrimaryKey     = "cosmosPrimaryKeyProduction";

                //                var snCosmosConfigTemplate = "cosmosConfigTemplateEmulator";
                //                var snCosmosPrimaryKey = "cosmosPrimaryKeyEmulator";

                var instrumentationKeyKeyVaultFetchStore = new SimpleStringKeyVaultFetchStore(
                    new KeyVaultFetchStoreOptions <string>()
                {
                    ExpirationSeconds = 3600,
                    KeyVaultName      = nameKeyVault,
                    SecretName        = "appis-azfuncshorturl2-instrumentation-key"
                }, _logger);
                var instrumentationKey = instrumentationKeyKeyVaultFetchStore.GetStringValueAsync().GetAwaiter().GetResult();
                // The following line enables Application Insights telemetry collection.
                services.AddApplicationInsightsTelemetry(instrumentationKey);
                var telemetryClient = new TelemetryClient(new TelemetryConfiguration()
                {
                    ConnectionString = $"InstrumentationKey={instrumentationKey}"
                });
                services.AddSingleton <TelemetryClient>(telemetryClient);

                var cosmosPrimaryKeyVaultFetchStore = new SimpleStringKeyVaultFetchStore(
                    new KeyVaultFetchStoreOptions <string>()
                {
                    ExpirationSeconds = 3600,
                    KeyVaultName      = nameKeyVault,
                    SecretName        = snCosmosPrimaryKey
                }, _logger);
                var primaryKey = cosmosPrimaryKeyVaultFetchStore.GetStringValueAsync().GetAwaiter().GetResult();

                var cosmosKeyVaultOptions = new KeyVaultFetchStoreOptions <CosmosConfiguration>()
                {
                    ExpirationSeconds = 3600,
                    KeyVaultName      = nameKeyVault,
                    SecretName        = snCosmosConfigTemplate
                };
                var cosmosConfigurationKeyVaultFetchStore = new CosmosConfigurationKeyVaultFetchStore(cosmosKeyVaultOptions, _logger);
                var cosmosConfiguration = cosmosConfigurationKeyVaultFetchStore.GetConfigurationAsync().GetAwaiter().GetResult();

                cosmosConfiguration.PrimaryKey = cosmosConfiguration.PrimaryKey.Replace("{{primaryKey}}", primaryKey);
                cosmosConfiguration.PrimaryConnectionString = cosmosConfiguration.PrimaryConnectionString.Replace("{{primaryKey}}", primaryKey);

                var jwtValidateSettingsKeyVaultOptions = new KeyVaultFetchStoreOptions <JwtValidation>()
                {
                    ExpirationSeconds = 3600,
                    KeyVaultName      = nameKeyVault,
                    SecretName        = "jwtValidateSettings"
                };
                var JwtValidationKeyVaultFetchStore = new JwtValidationKeyVaultFetchStore(jwtValidateSettingsKeyVaultOptions, _logger);
                var jwtValidation = JwtValidationKeyVaultFetchStore.GetConfigurationAsync().GetAwaiter().GetResult();


                _logger.LogInformation($"primaryKey:{!string.IsNullOrEmpty(primaryKey)}");
                _logger.LogInformation($"cosmosEndpointUri:{cosmosConfiguration.Uri}");

                services.AddHttpClient();
                services.AddControllers();

                _logger.LogInformation($"jwtValidateSettings:{jwtValidation != null} - JsonConvert.DeserializeObject");
                var tok = jwtValidation.ToTokenValidationParameters();
                services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority                 = jwtValidation.Authority;
                    options.RequireHttpsMetadata      = false;
                    options.TokenValidationParameters = tok;
                });

                services.AddUrlShortenerService();
                services.AddGuidUrlShortenerAlgorithm();

                // services.AddInMemoryUrlShortenerOperationalStore();
                services.AddCosmosDBUrlShortenerOperationalStore();

                TenantConfiguration tenantConfiguration = null;
                try
                {
                    _logger.LogInformation($"SafeFetchSettings(\"azFuncShorturlClientCredentials\")");
                    var creds = SafeFetchSettings("azFuncShorturlClientCredentials");
                    _logger.LogInformation($"azFuncShorturlClientCredentials:{!string.IsNullOrEmpty(creds)} - base64");
                    creds = Base64Decode(creds);
                    _logger.LogInformation($"azFuncShorturlClientCredentials:{!string.IsNullOrEmpty(creds)} - decoded");
                    tenantConfiguration = JsonConvert.DeserializeObject <TenantConfiguration>(creds);
                    _logger.LogInformation($"tenantConfiguration ok");
                }
                catch (Exception e)
                {
                    _logger.LogInformation($"tenantConfiguration not ok, setting to null");
                    tenantConfiguration = null;
                }

                services.AddKeyVaultTenantStore(options =>
                {
                    options.ExpirationSeconds = 3600;
                    options.KeyVaultName      = nameKeyVault;
                    options.SecretName        = "azFuncShorturlClientCredentials";
                    options.Value             = tenantConfiguration; // ok if null.  If it is not null we don't go to key vault at all
                });

                services.AddSimpleItemStore <ShortUrlCosmosDocument>(options =>
                {
                    options.EndPointUrl  = cosmosConfiguration.Uri;
                    options.PrimaryKey   = primaryKey;
                    options.DatabaseName = "shorturl";
                    options.Collection   = new Collection()
                    {
                        CollectionName = "shorturl",
                        ReserveUnits   = 400
                    };
                });
                services.AddSimpleItemStore <ExpiredShortUrlCosmosDocument>(options =>
                {
                    options.EndPointUrl  = cosmosConfiguration.Uri;
                    options.PrimaryKey   = primaryKey;
                    options.DatabaseName = "shorturl";
                    options.Collection   = new Collection()
                    {
                        CollectionName = "expired-shorturl",
                        ReserveUnits   = 400
                    };
                });

                services.AddScopedRequestHook <ScopedRequestHook>();
                if (_hostingEnvironment.IsDevelopment())
                {
                    services.Configure <MiddlewareOptions>(Configuration.GetSection("middleware"));
                }
                else
                {
                    // TODO, get from keyvault
                }
                // Example of adding default correlation ID (using the GUID generator) services
                // As shown here, options can be configured via the configure degelate overload
                services.AddDefaultCorrelationId(options =>
                {
                    options.AddToLoggingScope     = true;
                    options.EnforceHeader         = false;
                    options.IgnoreRequestHeader   = false;
                    options.IncludeInResponse     = true;
                    options.RequestHeader         = "My-Custom-Correlation-Id";
                    options.ResponseHeader        = "X-Correlation-Id";
                    options.UpdateTraceIdentifier = false;
                });
            }
            catch (Exception ex)
            {
                _exConfigureServices = ex;
                // defer throw, because we need to log in the Configure() function.
            }
        }