Example #1
0
 public TennantParamsController(DeployDBContext context, IOptions <AzureStorageConfig> config, IHostingEnvironment env)
 {
     _context        = context;
     _storageConfig  = config.Value;
     _service        = new TenantParameters(_context, config);
     this.hostingEnv = env;
 }
        public static async Task <BlobDownloadInfo> GetThumbNail(AzureStorageConfig _storageConfig, TokenAcquisitionTokenCredential tokenCredential, TelemetryClient telemetryClient, string imageName)
        {
            Uri        blobUri    = new Uri(string.Format("https://{0}.blob.core.windows.net/{1}/{2}", _storageConfig.AccountName, _storageConfig.ImageContainer, imageName));
            BlobClient blobClient = new BlobClient(blobUri, tokenCredential, null);

            return(await blobClient.DownloadAsync());
        }
 public ImagesController(IOptions <Dictionary <string, AzureStorageConfig> > config, ITrackingRepository trackingRepository)
 {
     this.storageConfig             = config.Value["upload-image-container"];
     this.outBoundNotificationQueue = config.Value["outbound-notification-queue"];
     this.catalogStorageConfig      = config.Value["catalog-image-container"];
     this.trackingRepository        = trackingRepository;
 }
Example #4
0
        public ImagesController(IUnitOfWork unitOfWork, IOptions <AzureStorageConfig> config)
        {
            _unitOfWork = unitOfWork ??
                          throw new ArgumentNullException(nameof(unitOfWork));

            storageConfig = config.Value;
        }
 public ProductsController(ApplicationDbContext context, IOptions <AzureStorageConfig> config, ILogger <ProductsController> logger, IConfiguration configuration)
 {
     _context       = context;
     storageConfig  = config.Value;
     this._logger   = logger;
     _configuration = configuration;
 }
 public LessonPlanController(ILessonPlanCreateManager lessonPlanCreateManager, ILessonPlanRepository lessonPlanRepository,
                             IOptions <AzureStorageConfig> config)
 {
     LessonPlanCreation = lessonPlanCreateManager;
     LessonPlanRepo     = lessonPlanRepository;
     StorageConfig      = config.Value;
 }
        public static async Task <List <string> > GetImageUrls(AzureStorageConfig _storageConfig, List <string> images)
        {
            List <string> imageUrls = new List <string>();

            // Create storagecredentials object by reading the values from the configuration (appsettings.json)
            StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

            // Create cloudstorage account by passing the storagecredentials
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            // Create blob client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Get reference to the container
            CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);

            // Set the permission of the container to public
            await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            foreach (var imageFile in images)
            {
                CloudBlob blobItem = container.GetBlobReference(imageFile);
                if (blobItem != null)
                {
                    imageUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
                }
            }

            return(await Task.FromResult(imageUrls));
        }
Example #8
0
        public Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            foreach (var eventData in messages)
            {
                var body = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

                dynamic bodybject = JsonConvert.DeserializeObject(body);
                dynamic dataobject;

                string soracom;
                if (bodybject.payloads == null)
                {
                    dataobject = bodybject;
                    soracom    = "Beam";
                }
                else
                {
                    dataobject = bodybject.payloads;
                    soracom    = "Funnel";
                }

                AzureStorageConfig _storageConfig = new AzureStorageConfig()
                {
                    ConnectionString = AzureStorageConnectionString,
                    Container        = soracom
                };

                Console.WriteLine($"{soracom} received. date: '{dataobject.date}', Data: '{dataobject.data}'");

                //Soracom soracom = Soracom.ParseJSON(data);
            }
            return(context.CheckpointAsync());
        }
 public CmsItemStorageService(AzureStorageService azureStorageService, AzureTableService tableService, IOptions <CmsConfiguration> cmsConfiguration, IOptions <AzureStorageConfig> azureStorageConfig)
 {
     this.azureStorageService = azureStorageService;
     this.tableService        = tableService;
     this.cmsConfiguration    = cmsConfiguration.Value;
     this.azureStorageConfig  = azureStorageConfig.Value;
 }
Example #10
0
        public static async Task <bool> DeleteFileFromStorage(string fileName,
                                                              AzureStorageConfig _storageConfig)
        {
            // Create a URI to the blob
            Uri imageBlobUri = new Uri("https://" +
                                       _storageConfig.AccountName +
                                       ".blob.core.windows.net/" +
                                       _storageConfig.ImageContainer +
                                       "/" + fileName);

            Uri thumbnailBlobUri = new Uri("https://" +
                                           _storageConfig.AccountName +
                                           ".blob.core.windows.net/" +
                                           _storageConfig.ThumbnailContainer +
                                           "/" + fileName);

            // Create StorageSharedKeyCredentials object by reading
            // the values from the configuration (appsettings.json)
            StorageSharedKeyCredential storageCredentials =
                new StorageSharedKeyCredential(_storageConfig.AccountName, _storageConfig.AccountKey);

            //TODO Set another event to delete thumbnail
            var deleteResult = await DeleteIfExistsAsync(thumbnailBlobUri, storageCredentials);

            return(deleteResult && await DeleteIfExistsAsync(imageBlobUri, storageCredentials));
        }
Example #11
0
 public DeployTypesController(DeployDBContext context, IOptions <AzureStorageConfig> config)
 {
     _storageConfig = config.Value;
     _context       = context;
     _service       = new DeployTypesService(_context);
     _tenantService = new TenantParameters(_context, config);
 }
Example #12
0
        public static async Task <List <string> > GetImageUrls(AzureStorageConfig _storageConfig)
        {
            List <string> imageUrls = new List <string>();

            StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);

            BlobContinuationToken continuationToken = null;

            BlobResultSegment resultSegment = null;

            do
            {
                resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);

                foreach (var blobItem in resultSegment.Results)
                {
                    imageUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
                }

                continuationToken = resultSegment.ContinuationToken;
            }while (continuationToken != null);

            return(await Task.FromResult(imageUrls));
        }
Example #13
0
        public static async Task <bool> UploadFileToStorage(AzureStorageConfig _storageConfig, Stream fileStream, string fileName)
        {
            try
            {
                // Create storagecredentials object by reading the values from the configuration (appsettings.json)
                StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

                // Create cloudstorage account by passing the storagecredentials
                CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
                //CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);
                var container = blobClient.GetContainerReference(_storageConfig.ImageContainer);
                container.CreateIfNotExistsAsync().Wait();

                // Get the reference to the block blob from the container
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

                // Upload the file
                await blockBlob.UploadFromStreamAsync(fileStream);
            }
            catch (Exception error)
            {
                throw new Exception(error.Message.ToString());
            }
            return(await Task.FromResult(true));
        }
Example #14
0
        public static async Task <List <string> > GetThumbNailUrls(AzureStorageConfig _storageConfig, TokenAcquisitionTokenCredential tokenCredential, TelemetryClient telemetryClient, string pathBase)
        {
            List <string> thumbnailUrls = new List <string>();

            // Create a URI to the storage account
            Uri blobUri = new Uri(_storageConfig.FullAccountName);

            BlobServiceClient blobServiceClient = new BlobServiceClient(blobUri, tokenCredential, null);

            // Get reference to the container
            BlobContainerClient container = blobServiceClient.GetBlobContainerClient(_storageConfig.ImageContainer);

            if (container.Exists())
            {
                foreach (BlobItem blobItem in container.GetBlobs())
                {
                    if (IsImage(blobItem.Name))
                    {
                        string imageUrl = string.Format("{0}api/images/thumbnail?ImageName={1}", pathBase, blobItem.Name);
                        thumbnailUrls.Add(imageUrl);
                        telemetryClient.TrackTrace("Found Thumbnail - " + imageUrl);
                    }
                }
            }
            else
            {
                telemetryClient.TrackException(new ArgumentNullException(string.Format("Container {0} not found!", container.Name)));
                container.CreateIfNotExists(PublicAccessType.None, null, null);
            }

            return(await Task.FromResult(thumbnailUrls));
        }
Example #15
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            AzureStorageConfig azureStorageConfig = new AzureStorageConfig()
            {
                AccountName    = "myAccount",
                AccountKey     = "r564d8g4f8ht8y7t98y789gh787==7-87[8[7]8787--55623154er12df4g7t7a",
                ImageContainer = "myContainer"
            };

            try
            {
                Console.WriteLine("Paste the file path");
                var    path     = Console.ReadLine();
                string fileName = path.Substring(path.LastIndexOf('\\'));
                fileName = fileName.Substring(1);

                var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                var ret    = await UploadFileToStorage(stream, fileName, azureStorageConfig);

                if (ret)
                {
                    Console.WriteLine("Image uploaded!!");
                    Console.ReadLine();
                    return;
                }
            }
            catch (Exception error)
            {
                Console.WriteLine($">>> Fail to upload image!! \r\n{error.Message}");
                Console.ReadLine();
            }
        }
Example #16
0
 public UserController(UserManager <ApplicationUser> userMan, SignInManager <ApplicationUser> signinMan, ApplicationDbContext db, IOptions <AzureStorageConfig> configOption, IConfiguration config)
 {
     this.userMan       = userMan;
     this.signinMan     = signinMan;
     this.db            = db;
     this.storageConfig = configOption.Value;
     this.config        = config;
 }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageService"/> class.
        /// </summary>
        /// <param name="keyVaultService">Key Vault Service</param>
        /// <param name="config">Config</param>
        public StorageService(IKeyVaultService keyVaultService, IOptions <AzureStorageConfig> config)
        {
            Contract.Requires(config != null, nameof(config));
            Contract.Requires(keyVaultService != null, nameof(keyVaultService));

            this.config          = config.Value;
            this.keyVaultService = keyVaultService;
        }
Example #18
0
 public WorkerService(ILogger <WorkerService> logger,
                      IOptions <AzureCognitiveServicesConfig> configCognitiveServices,
                      IOptions <AzureStorageConfig> configAzureStorage)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _configCognitiveServices = configCognitiveServices.Value;
     _configAzureStorage      = configAzureStorage.Value;
 }
Example #19
0
 public Handler(
     UserAssetsDbContext userAssetsDbContext,
     IOptions <AzureStorageConfig> storageConfig,
     IOptions <ServiceSettings> serviceSettings)
 {
     _userAssetsDbContext = userAssetsDbContext;
     _storageConfig       = storageConfig.Value;
     _serviceSettings     = serviceSettings.Value;
 }
        public MessagesController(IUnitOfWork unitOfWork, IMapper mapper, IOptions <AzureStorageConfig> config)
        {
            _unitOfWork = unitOfWork ??
                          throw new ArgumentNullException(nameof(unitOfWork));
            _mapper = mapper ??
                      throw new ArgumentNullException(nameof(mapper));

            storageConfig = config.Value;
        }
 public BlobCreatorController(IOptions <AzureStorageConfig> config,
                              IPoemManager poemManager,
                              IWritingTemplateManager writingTemplate,
                              IArtPieceManager artPieceManager)
 {
     storageConfig    = config.Value;
     this.poemManager = poemManager;
     WritingTemplate  = writingTemplate;
     ArtPieceManager  = artPieceManager;
 }
 public ImagesController(IOptions <AzureStorageConfig> config)
 {
     storageConfig = new AzureStorageConfig()
     {
         AccountKey         = _accountKey,
         AccountName        = _accountName,
         ImageContainer     = "instructor-images",
         ThumbnailContainer = "thumbnails"
     };
 }
Example #23
0
 public PhotosController(
     AzureStorageConfig storageConfig,
     UserManager <ApplicationUser> userManager,
     ApplicationDbContext dbContext
     )
 {
     _storageConfig = storageConfig ?? throw new NullReferenceException();
     _userManager   = userManager ?? throw new NullReferenceException();
     _dbContext     = dbContext ?? throw new NullReferenceException();
 }
Example #24
0
        public static string BlobUrl(AzureStorageConfig _storageConfig, string imageFileName)
        {
            var account         = new CloudStorageAccount(new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey), true);
            var cloudBlobClient = account.CreateCloudBlobClient();
            var container       = cloudBlobClient.GetContainerReference(_storageConfig.ImageContainer);
            var blob            = container.GetBlockBlobReference(imageFileName);

            //blob.UploadFromFile("File Path ....");//Upload file....

            return(blob.Uri.AbsoluteUri);
        }
Example #25
0
        private TdsDataObject createTdsDataObject()
        {
            TdsDataObject      tdsDataObject  = new TdsDataObject();
            AzureStorageConfig _storageConfig = new AzureStorageConfig()
            {
                ConnectionString = StorageConnectionString,
                Container        = Container
            };

            tdsDataObject.InitTables(_storageConfig);
            return(tdsDataObject);
        }
        public static async Task <List <string> > GetThumbNailUrls(AzureStorageConfig _storageConfig)
        {
            List <string> thumbnailUrls = new List <string>();

            try
            {
                // Create storagecredentials object by reading the values from the configuration (appsettings.json)
                StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

                // Create cloudstorage account by passing the storagecredentials
                CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

                // Create blob client
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                // Get reference to the container
                CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ThumbnailContainer);

                BlobContainerPermissions perm = await container.GetPermissionsAsync();

                perm.PublicAccess = BlobContainerPublicAccessType.Blob;
                await container.SetPermissionsAsync(perm);

                BlobContinuationToken continuationToken = null;

                BlobResultSegment resultSegment = null;

                //Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
                //When the continuation token is null, the last page has been returned and execution can exit the loop.
                do
                {
                    //This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter,
                    //or by calling a different overload.
                    resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);

                    foreach (var blobItem in resultSegment.Results)
                    {
                        thumbnailUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
                    }

                    //Get the continuation token.
                    continuationToken = resultSegment.ContinuationToken;
                }while (continuationToken != null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(await Task.FromResult(thumbnailUrls));
        }
        public void Setup()
        {
            _factory       = new BenchesWebApplicationFactory();
            _client        = _factory.CreateClient();
            _containerName = $"Container_{Guid.NewGuid().ToString().ToLower()}";

            AzureStorageConfig azureAppSettings = new AzureStorageConfig()
            {
                ConnectionString  = _connectionString,
                FileContainerName = _containerName
            };
            IOptions <AzureStorageConfig> options = Options.Create(azureAppSettings);

            _sut = new BlobStorageService(options);
        }
Example #28
0
        public void SetUp()
        {
            AzureStorageConfig.RegisterConfiguration();

            var testContainerName = "unittests" + Guid.NewGuid().ToString();
            var testTableName     = "unittests" + Guid.NewGuid().ToString().Replace("-", string.Empty);
            var account           = CloudStorageAccount.DevelopmentStorageAccount;
            var client            = account.CreateCloudBlobClient();

            this.tableClient = account.CreateCloudTableClient();
            this.tableClient.GetTableReference(testTableName).CreateIfNotExists();
            this.container = client.GetContainerReference(testContainerName);
            this.container.CreateContainerWithPublicBlobsIfNotExistAsync();
            this.controller = new InboxControllerForTest(this.container.Name, testTableName, CloudConfigurationName);
        }
Example #29
0
        public static AzureStorageConfigValidationResult Validate(AzureStorageConfig storageConfig)
        {
            AzureStorageConfigValidationResult validation = new AzureStorageConfigValidationResult();

            if (storageConfig.ConnectionString == string.Empty)
            {
                validation.AddError("ConnectionString", "ConnectionString key is empty. Check configuration.");
            }

            if (storageConfig.ImageContainer == string.Empty)
            {
                validation.AddError("ImageContainer", "Image container name is empty. Check configuration.");
            }

            return(validation);
        }
        public DataStorage(ILogger <DataStorage> logger, IOptions <AzureStorageConfig> azureStorageConfig)
        {
            buckets = new List <Bucket>
            {
                new Bucket(1, "< 249", 0, 249),
                new Bucket(2, "250 - 499", 250, 499),
                new Bucket(3, "500 - 999", 500, 999),
                new Bucket(4, "1000 - 4999", 1000, 4999),
                new Bucket(5, "5000 - 24999", 5000, 24999),
                new Bucket(6, "> 25000", 25000, null),
            };
            sourceDataJson          = JsonConvert.SerializeObject(new SourceData());
            this.azureStorageConfig = azureStorageConfig.Value;
            this.logger             = logger;

            LoadSourceDataFromDisk();
        }