Exemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Admin, "get", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            string requestInfo  = null;
            string errorContext = null;

            try
            {
                errorContext = "inspecting request";
                var key = req.BindGet <Shared.Models.CreateKey>();

                errorContext = "searching for key";
                var config         = context.GetConfig();
                var storageOptions = new StorageAccountOptions();
                config.Bind("StorageAccount", storageOptions);
                var keyStore = new KeyStore(storageOptions);

                var find = await keyStore.FindKeyAsync(key);

                return(new OkObjectResult(find.data.Select(keyInfo => keyInfo.Key)));
            }
            catch (Exception exc)
            {
                log.LogError(exc, $"{exc.Message} while {errorContext}: {requestInfo}");
                return(new BadRequestObjectResult(exc.Message));
            }
        }
Exemplo n.º 2
0
        private async Task <CloudQueue> CreateCloudQueue(
            StorageQueueOptions options,
            StorageAccountOptions storageAccountOptions,
            CancellationToken cancellationToken = default)
        {
            var sw = Stopwatch.StartNew();

            var cloudStorageAccount = await storageAccountOptions.CloudStorageAccount.Value;

            var cloudQueueClient = cloudStorageAccount.CreateCloudQueueClient();

            var queue = cloudQueueClient.GetQueueReference(options.QueueName);

            var created = await queue.CreateIfNotExistsAsync(cancellationToken);

            if (created)
            {
                _logger?.LogInformation("  - No Azure Queue [{queueName}] found - so one was auto created.", options.QueueName);
            }
            else
            {
                _logger?.LogInformation("  - Using existing Azure Queue [{QueueName}] [{optionsName}].", options.QueueName, options);
            }
            sw.Stop();

            _logger?.LogInformation("  - {nameOf} ran for {seconds}", nameof(CreateCloudQueue), sw.Elapsed.TotalSeconds);

            return(queue);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Adds Azure Storage Health Check.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="name"></param>
        /// <param name="containerName"></param>
        /// <param name="setup"></param>
        /// <param name="failureStatus"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddAzureBlobStorageCheck(
            this IHealthChecksBuilder builder,
            string name,
            string containerName,
            Action <StorageAccountOptions> setup,
            HealthStatus?failureStatus = default,
            IEnumerable <string> tags  = default)
        {
            var options = new StorageAccountOptions();

            setup?.Invoke(options);

            builder.Services.AddOptions <StorageAccountOptions>(name)
            .Configure((opt) =>
            {
                opt.ConnectionString = options.ConnectionString;
                opt.ContainerName    = containerName;
                opt.Name             = options.Name;
                opt.Token            = options.Token;
            });

            builder.AddCheck <AzureBlobStorageHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

            return(builder);
        }
Exemplo n.º 4
0
        private async Task <CloudTable> CreateOrGetBlobTable(
            StorageTableOptions options,
            StorageAccountOptions storageOptions,
            CancellationToken cancellationToken = default)
        {
            var sw = ValueStopwatch.StartNew();

            var storageAccount = CreateStorageAccountFromConnectionString(storageOptions.ConnectionString);

            if (storageAccount == null)
            {
                throw new NullReferenceException($"{nameof(storageAccount)} wasn't created please make sure Connection String is provided.");
            }

            var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

            var table = tableClient.GetTableReference(options.TableName);

            if (await table.CreateIfNotExistsAsync(cancellationToken))
            {
                _logger.LogInformation("[Azure Table] No Azure Table [{tableName}] found - so one was auto created.", options.TableName);
            }
            else
            {
                _logger.LogInformation("[Azure Table] Using existing Azure Table:[{tableName}].", options.TableName);
            }

            _logger.LogInformation("[Azure Table][{methodName}] Elapsed: {seconds}sec", nameof(CreateOrGetBlobTable), sw.GetElapsedTime().TotalSeconds);

            return(table);
        }
Exemplo n.º 5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            string requestInfo  = null;
            string errorContext = null;

            try
            {
                errorContext = "inspecting request";
                var key = req.BindGet <LicenseKey>();

                errorContext = "searching for key";
                var config         = context.GetConfig();
                var storageOptions = new StorageAccountOptions();
                config.Bind("StorageAccount", storageOptions);
                var keyStore = new KeyStore(storageOptions);
                var result   = await keyStore.ValidateKeyAsync(key);

                return(new OkObjectResult(new ValidateResult()
                {
                    Success = result.success,
                    Message = result.message
                }));
            }
            catch (Exception exc)
            {
                log.LogError(exc, $"{exc.Message} while {errorContext}: {requestInfo}");
                return(new BadRequestObjectResult(exc.Message));
            }
        }
        public StorageFileProvider(StorageAccountOptions options, string containerName)
        {
            var storageAccount = options.CloudStorageAccount.Value.GetAwaiter().GetResult();

            var blobClient = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference(containerName);
        }
Exemplo n.º 7
0
 private CloudStorageAccount CreateCloudStorageAccount(StorageAccountOptions options)
 {
     if (!CloudStorageAccount.TryParse(options.ConnectionString, out CloudStorageAccount storageAccount))
     {
         throw new Exception("Invalid storage account connecting string. Please verify the connection string and try again");
     }
     return(storageAccount);
 }
Exemplo n.º 8
0
        public BlobsController(IOptions <StorageAccountOptions> storageAccountOptionsAccessor)
        {
            _storageAccountOptions = storageAccountOptionsAccessor.Value;

            // Create a BlobServiceClient object which will be used to create a container client
            _blobServiceClient = new BlobServiceClient(_storageAccountOptions.ConnectionString);
            _containerClient   = _blobServiceClient.GetBlobContainerClient(_storageAccountOptions.ContainerName);
            _blobClient        = _containerClient.GetBlobClient(_storageAccountOptions.BlobName);
        }
Exemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMediatR(typeof(Program).Assembly);
            services.AddScoped <IBlobStorageService, BlobStorageService>();
            var storageAccountOptions = new StorageAccountOptions();

            Configuration.GetSection(StorageAccountOptions.SectionName).Bind(storageAccountOptions);
            services.AddSingleton(storageAccountOptions);
        }
Exemplo n.º 10
0
 public HomeController(ILogger <HomeController> logger,
                       ApplicationDbContext context,
                       IConfiguration configuration,
                       IOptionsSnapshot <StorageAccountOptions> storageOptions)
 {
     _logger                = logger;
     _context               = context;
     _configuration         = configuration;
     _storageAccountOptions = storageOptions.Value;
 }
 public BlobImagesController(
     IAuthorizationService authorizationService,
     IOptions <StorageAccountOptions> storageAccountOptions)
 {
     _authzService          = authorizationService;
     _storageAccountOptions = storageAccountOptions.Value;
     _blobUtility           = new BlobUtility(
         _storageAccountOptions.StorageAccountNameOption,
         _storageAccountOptions.StorageAccountKeyOption);
 }
Exemplo n.º 12
0
        private static async Task <CloudQueue> GetQueue(StorageAccountOptions options)
        {
            var storageAccount           = new CloudStorageAccount(new StorageCredentials(options.Name, options.Key), true);
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue       queue       = queueClient.GetQueueReference($"{options.QueueName}{new Random().Next()}");

            Console.WriteLine($"Using queue '{queue.Name}'");
            await queue.CreateIfNotExistsAsync();

            return(queue);
        }
Exemplo n.º 13
0
 public SignShopController(
     IHttpClientFactory clientFactory,
     IOptions <StorageAccountOptions> storageAccountOptions)
 {
     _clientFactory         = clientFactory;
     _httpClient            = _clientFactory.CreateClient(ApiClient);
     _storageAccountOptions = storageAccountOptions.Value;
     _blobUtility           = new BlobUtility(
         _storageAccountOptions.StorageAccountNameOption,
         _storageAccountOptions.StorageAccountKeyOption);
 }
        public LoggerProviderFactory(
            IOptions <StorageAccountOptions> storageAccountOptions,
            ILoggerFactory loggerFactory,
            IEventCollectorFactory fastLoggerFactory = null)
        {
            _storageAccountOptions = storageAccountOptions.Value;
            _loggerFactory         = loggerFactory;
            _hasFastTableHook      = fastLoggerFactory != null;

            _loggerProvider = new Lazy <object>(CreateLoggerProvider);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageBlob"/> class.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="storageAccountOptions"></param>
        /// <param name="logger"></param>
        public StorageBlob(
            StorageBlobOptions options,
            StorageAccountOptions storageAccountOptions,
            ILogger logger = default)
        {
            _storageAccountOptions = storageAccountOptions ?? throw new ArgumentNullException(nameof(storageAccountOptions));

            _logger = logger;

            _container = new Lazy <Task <CloudBlobContainer> >(() => CreateCloudBlobContainer(options));
        }
Exemplo n.º 16
0
        private static async Task <CloudTable> GetTableReferenceAsync(StorageAccountOptions storageAccountOptions)
        {
            var storageAccount              = new CloudStorageAccount(new StorageCredentials(storageAccountOptions.Name, storageAccountOptions.Key), true);
            CloudTableClient tableClient    = storageAccount.CreateCloudTableClient();
            string           tableName      = $"{storageAccountOptions.TableName}{new Random().Next()}";
            CloudTable       tableReference = tableClient.GetTableReference(tableName);
            await tableReference.CreateIfNotExistsAsync();

            Console.WriteLine($"Using table '{tableName}'");

            return(tableReference);
        }
Exemplo n.º 17
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Admin, "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            string requestInfo  = null;
            string errorContext = null;

            try
            {
                errorContext = "inspecting request";

                // generate key for a product
                var json = await req.ReadAsStringAsync();

                requestInfo = json;
                var createKey = JsonConvert.DeserializeObject <Shared.Models.CreateKey>(json);
                var key       = new LicenseKey()
                {
                    Email   = createKey.Email,
                    Product = createKey.Product,
                    Key     = new StringIdBuilder()
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Add("-")
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Add("-")
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Build()
                };

                var config = context.GetConfig();

                // save to storage account
                errorContext = "saving key";
                var storageOptions = new StorageAccountOptions();
                config.Bind("StorageAccount", storageOptions);
                var keyStore = new KeyStore(storageOptions);
                await keyStore.SaveKeyAsync(key);

                // send to user
                errorContext = "sending key to user";
                var sendGridOptions = new SendGridOptions();
                config.GetSection("SendGrid").Bind(sendGridOptions);
                await SendConfirmationEmailAsync(key, sendGridOptions);

                log.LogInformation(JsonConvert.SerializeObject(key));
                return(new OkObjectResult(key));
            }
            catch (Exception exc)
            {
                log.LogError(exc, $"{exc.Message} while {errorContext}: {requestInfo}");
                return(new BadRequestObjectResult(exc.Message));
            }
        }
        public ImagesController(IHostingEnvironment host, PathologyHandbookContext context, IOptionsSnapshot <ImageSettings> imageOptions, IOptionsSnapshot <StorageAccountOptions> storageOptions)
        {
            _imageSettings         = imageOptions.Value;
            _storageAccountOptions = storageOptions.Value;
            _host    = host;
            _context = context;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse($"DefaultEndpointsProtocol=https;AccountName={_storageAccountOptions.StorageAccountNameOption};AccountKey={_storageAccountOptions.StorageAccountKeyOption}");

            // Gain Access to the containers and blobs in your Azure storage account
            _blobClient = storageAccount.CreateCloudBlobClient();
        }
Exemplo n.º 19
0
        private static StorageAccountOptions ParseStorageAccountOptions()
        {
            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("appsettings.json")
                                           .AddUserSecrets <Program>()
                                           .Build();

            var storageAccountOptions = new StorageAccountOptions();

            configuration.Bind("StorageAccount", storageAccountOptions);
            return(storageAccountOptions);
        }
Exemplo n.º 20
0
        public StorageQueue(
            StorageQueueOptions storageQueueOptions,
            StorageAccountOptions storageAccountOptions,
            ILogger logger = default)
        {
            if (storageAccountOptions == null)
            {
                throw new ArgumentNullException(nameof(storageAccountOptions));
            }

            _storageQueueOptions = storageQueueOptions ?? throw new ArgumentNullException(nameof(storageQueueOptions));

            _logger = logger;

            _queue = new Lazy <Task <CloudQueue> >(() => CreateCloudQueue(_storageQueueOptions, storageAccountOptions));
        }
Exemplo n.º 21
0
        // TODO - add new cases for adhesive w/ and w/o corrplast, and plasticore options ---- Could have made option value property...

        public SalesController(
            SignInManager <IdentityUser> signInManager,
            UserManager <IdentityUser> userManager,
            IHttpClientFactory clientFactory,
            ISalesService salesService,
            IOptions <StorageAccountOptions> storageAccountOptions)
        {
            _signInManager         = signInManager;
            _userManager           = userManager;
            _clientFactory         = clientFactory;
            _httpClient            = _clientFactory.CreateClient(ApiClient);
            _salesService          = salesService;
            _storageAccountOptions = storageAccountOptions.Value;
            _blobUtility           = new BlobUtility(
                _storageAccountOptions.StorageAccountNameOption,
                _storageAccountOptions.StorageAccountKeyOption);
        }
Exemplo n.º 22
0
 public WorkOrdersController(ApplicationDbContext context,
                             UserManager <ApplicationUser> userManager,
                             SignInManager <ApplicationUser> signInManager,
                             RoleManager <AppRole> roleManager,
                             IOptionsSnapshot <StorageAccountOptions> storageOptions,
                             IOptionsSnapshot <TwilioSMS> twilioSMS,
                             IOptionsSnapshot <EmailConfiguration> EmailConfiguration
                             )
 {
     _context               = context;
     _userManager           = userManager;
     _signInManager         = signInManager;
     _roleManager           = roleManager;
     _storageAccountOptions = storageOptions.Value;
     _twilioSMS             = twilioSMS.Value;
     _EmailConfiguration    = EmailConfiguration.Value;
 }
 public DashboardLoggingSetup(
     StorageAccountOptions storageAccountOptions,
     IWebJobsExceptionHandler exceptionHandler,
     ILoggerFactory loggerFactory,
     IFunctionInstanceLogger functionInstanceLogger,
     IFunctionExecutor functionExecutor,
     SharedQueueHandler sharedQueueHandler,
     ILoadBalancerQueue storageServices
     )
 {
     _storageAccountOptions  = storageAccountOptions;
     _exceptionHandler       = exceptionHandler;
     _loggerFactory          = loggerFactory;
     _functionInstanceLogger = functionInstanceLogger;
     _functionExecutor       = functionExecutor;
     _sharedQueueHandler     = sharedQueueHandler;
     _storageServices        = storageServices;
 }
Exemplo n.º 24
0
        private static void RegisterOptions(
            IHealthChecksBuilder builder,
            string name,
            Action <StorageAccountOptions> setup)
        {
            var options = new StorageAccountOptions();

            setup?.Invoke(options);

            builder.Services.ConfigureOptions <StorageAccountOptionsSetup>();

            builder.Services.AddOptions <StorageAccountOptions>(name)
            .Configure((opt) =>
            {
                opt.ConnectionString = options.ConnectionString;
                opt.Name             = options.Name;
                opt.Token            = options.Token;
            });
        }
Exemplo n.º 25
0
        private static async Task Main(string[] args)
        {
            Configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                            .AddJsonFile(GetBaseDirectoryPath("appsettings.json"), true)
                            .Build();

            var builder = new HostBuilder()
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddMediatR(typeof(Program).Assembly);
                services.AddTransient <IHtmlParser>(provider => new HtmlParser());
                services.AddTransient(provider => new WebClient());
                services.AddTransient <IHttpRequestsFactory, HttpRequestsFactory>();
                services.AddHostedService <FileParsingService>();

                var storageAccountOptions = new StorageAccountOptions();
                Configuration.GetSection(StorageAccountOptions.SectionName).Bind(storageAccountOptions);
                services.AddSingleton(storageAccountOptions);
                services.AddScoped <IBlobStorageService, BlobStorageService>();
            })
                          .ConfigureLogging(logBuilder =>
            {
                logBuilder.ClearProviders();
                logBuilder.AddConsole(options =>
                {
                    options.DisableColors   = true;
                    options.TimestampFormat = "[MM.dd.yyyy HH:mm:ss.fff] ";
                });
            })
                          .ConfigureHostConfiguration(provider =>
            {
                provider.AddConfiguration(Configuration);
                // NLog
                var nLogConfigSection    = Configuration.GetSection("NLog");
                LogManager.Configuration = new NLogLoggingConfiguration(nLogConfigSection);
                NLogBuilder.ConfigureNLog(LogManager.Configuration);
            })
                          .UseConsoleLifetime();

            await builder.Build().RunAsync();
        }
Exemplo n.º 26
0
        private async Task <CloudTable> CreateOrGetBlobTable(
            StorageTableOptions options,
            StorageAccountOptions storageOptions,
            CancellationToken cancellationToken = default)
        {
            var storageAccount = CreateStorageAccountFromConnectionString(storageOptions.ConnectionString);

            var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

            var table = tableClient.GetTableReference(options.TableName);

            if (await table.CreateIfNotExistsAsync(cancellationToken))
            {
                _logger?.LogInformation("Created Table named: {0}", options.TableName);
            }
            else
            {
                _logger?.LogInformation("Table {0} already exists", options.TableName);
            }

            return(table);
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            StorageAccountOptions storageAccountOptions = ParseStorageAccountOptions();
            CloudTable            tableReference        = GetTableReferenceAsync(storageAccountOptions).GetAwaiter().GetResult();

            try
            {
//                InsertExample.InsertEntities(tableReference).GetAwaiter().GetResult();
                BulkInsertExample.InsertAllSamples(tableReference).GetAwaiter().GetResult();
                QueryExample.ExecuteAllQueries(tableReference);
            }
            catch (StorageException e)
            {
                Console.Error.WriteLine(e.RequestInformation.ExtendedErrorInformation.ErrorMessage);
                throw;
            }
            finally
            {
                Console.WriteLine("Done.");
                Console.ReadKey();
                tableReference.DeleteIfExistsAsync().GetAwaiter().GetResult();
            }
        }
 public BlobStorageService(StorageAccountOptions options)
 {
     _client = CloudStorageAccount.Parse(options.ConnectionString)
               .CreateCloudBlobClient();
 }
Exemplo n.º 29
0
 public GetAllBlobs_Cmd_Handler(IBlobStorageService blobStorageService, StorageAccountOptions options)
 {
     _blobStorageService = blobStorageService;
     _options            = options;
 }
Exemplo n.º 30
0
 public ImagesController(IMediator mediator, StorageAccountOptions options)
 {
     _mediator = mediator;
     _options  = options;
 }