예제 #1
0
        /// <summary>
        /// Initializes this instance for use, this is not thread safe
        /// </summary>
        /// <returns>A task</returns>
        /// <remarks>This method is not thread safe</remarks>
        private void Initialize(string containerName)
        {
            if (!IsInitialized)
            {
                _blobServiceClient = new BlobServiceClient(_storageAccountSettings.StorageAccountConnectionString);

                // This needs to change to the input parameter containerName
                _blobContainerClient = _blobServiceClient.GetBlobContainerClient(containerName);

                _blobContainerClient.CreateIfNotExists(publicAccessType: PublicAccessType.None);

                IsInitialized = true;
            }
        }
        public async Task Run([QueueTrigger("orders")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"Browser path: {appInfo.BrowserExecutablePath}");

            int orderId = int.Parse(myQueueItem);
            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless       = true,
                ExecutablePath = appInfo.BrowserExecutablePath
            });

            var page = await browser.NewPageAsync();

            await page.GoToAsync($"http://*****:*****@InvoiceURL where OrderId = @OrderId";
                var    affectedRows = connection.Execute(sql, new { OrderId = orderId, InvoiceURL = sasUri });
            }
        }
예제 #3
0
        public BlobContainerClient GetContainerClient(string containerName)
        {
            BlobContainerClient client = null;

            try
            {
                client = new BlobContainerClient(_options.StorageConnectionString, containerName);
                client.CreateIfNotExists();
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
            }
            return(client);
        }
        public async Task <string> Insert(string tableName, string fileName, string base64Content)
        {
            BlobContainerClient container = new BlobContainerClient(settings.ConnectionString, settings.ContainerName);

            container.CreateIfNotExists(PublicAccessType.BlobContainer);
            var        blobName   = tableName + "/" + Guid.NewGuid().ToString() + fileName;
            BlobClient blobClient = container.GetBlobClient(blobName);

            byte[]       bytes = Convert.FromBase64String(base64Content);
            MemoryStream ms    = new MemoryStream(bytes);
            await blobClient.UploadAsync(ms, true);

            ms.Close();
            return(blobName);
        }
예제 #5
0
        public static void CreateSampleBlobFile()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true)
                                .Build();
            BlobContainerClient containerClient = new BlobContainerClient(configuration.GetSection("AzureBlobConfiguration").GetSection("ConnectionString").Value, "contractevents");

            containerClient.CreateIfNotExists();
            UTF8Encoding encoding = new UTF8Encoding();

            using MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(BlobSampleContent));
            containerClient.DeleteBlobIfExists(BlobName);
            containerClient.UploadBlob(BlobName, memoryStream);
        }
예제 #6
0
        public void SetUp()
        {
            _loggerProvider = new TestLoggerProvider();
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);
            _logger = loggerFactory.CreateLogger <BlobListener>();

            var account = AzuriteNUnitFixture.Instance.GetAccount();

            _blobServiceClient = account.CreateBlobServiceClient();
            _blobContainer     = _blobServiceClient.GetBlobContainerClient(TestContainerName);
            _blobContainer.DeleteIfExists();
            _blobContainer.CreateIfNotExists();
        }
예제 #7
0
        private void StartConnection()
        {
            var containerClientCreated = _blobContainerClient == null;

            if (containerClientCreated)
            {
                return;
            }

            var blobContainerClient = new BlobContainerClient(_storageSettings.ConnectionString, _storageSettings.Blob.ContainerName);

            blobContainerClient.CreateIfNotExists();

            _blobContainerClient = blobContainerClient;
        }
        /// <summary>
        /// Create a container if doesn't exist, setting permission with policy, and return assosciated SAS signature
        /// </summary>
        /// <param name="account">Storage account</param>
        /// <param name="Key">Storage account key</param>
        /// <param name="blobUri">Blob endpoint URI</param>
        /// <param name="containerName">Name of the container to be created</param>
        /// <param name="policy">Name for the policy</param>
        /// <param name="start">Start time of the policy</param>
        /// <param name="end">Expire time of the policy</param>
        /// <param name="permissions">Blob access permissions</param>
        /// <returns>the SAS for the container, in full URI format.</returns>.
        private static async Task <string> CreateContainerWithPolicySASIfNotExistAsync(string account, string key, Uri blobUri, string containerName, string policy, DateTime start, DateTime end, string permissions)
        {
            // 1. form the credentail and initial client
            StagingStorageAccount      stagingCredentials  = new StagingStorageAccount(account, key, blobUri.ToString());
            StorageSharedKeyCredential shardKeyCredentials = new StorageSharedKeyCredential(account, key);
            BlobContainerClient        containerClient     = BlobUtilities.GetBlobContainerClient(containerName, stagingCredentials);

            // 2. create container if it doesn't exist
            containerClient.CreateIfNotExists();

            // 3. validate policy, create/overwrite if doesn't match
            BlobSignedIdentifier identifier = new BlobSignedIdentifier
            {
                Id           = policy,
                AccessPolicy = new BlobAccessPolicy
                {
                    Permissions = permissions,
                    StartsOn    = start,
                    ExpiresOn   = end,
                },
            };

            var  accessPolicy = (await containerClient.GetAccessPolicyAsync()).Value;
            bool policyFound  = accessPolicy.SignedIdentifiers.Any(i => i == identifier);

            if (policyFound == false)
            {
                await containerClient.SetAccessPolicyAsync(PublicAccessType.BlobContainer, permissions : new List <BlobSignedIdentifier> {
                    identifier
                });
            }

            BlobSasBuilder sasBuilder = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                StartsOn          = start,
                ExpiresOn         = end,
            };

            sasBuilder.SetPermissions(permissions);
            BlobUriBuilder builder = new BlobUriBuilder(containerClient.Uri)
            {
                Sas = sasBuilder.ToSasQueryParameters(shardKeyCredentials)
            };
            string fullSas = builder.ToString();

            return(fullSas);
        }
        public override IDisposable?PrepareForHandleLost()
        {
            this.Options = o =>
            {
                DefaultTestingOptions(o);
                o.RenewalCadence(TimeSpan.FromMilliseconds(10));
            };

            using var md5      = MD5.Create();
            this.ContainerName = $"distributed-lock-handle-lost-{new BigInteger(md5.ComputeHash(Encoding.UTF8.GetBytes(TargetFramework.Current + TestContext.CurrentContext.Test.FullName))):x}";
            var containerClient = new BlobContainerClient(AzureCredentials.ConnectionString, this.ContainerName);

            containerClient.CreateIfNotExists();
            this._disposables.Add(() => containerClient.DeleteIfExists());
            return(new HandleLostScope(this.ContainerName));
        }
예제 #10
0
        public AzureBlobInsightsReaderService(ReaderConfig config, ILog logger, string thumbnailImageLocation)
        {
            if (config == null || logger == null)
            {
                throw new NullReferenceException();
            }

            _config                  = config;
            _logger                  = logger;
            _blobServiceClient       = new BlobServiceClient(_config.AzureBlob.ConnectionString);
            _insightsContainerClient = _blobServiceClient.GetBlobContainerClient(_config.AzureBlob.InsightsContainer);
            _insightsContainerClient.CreateIfNotExists();
            _failedInsightsContainerClient = _blobServiceClient.GetBlobContainerClient(_config.AzureBlob.FailedInsightsContainer);
            _failedInsightsContainerClient.CreateIfNotExists();
            _thumbnailImageLocation = thumbnailImageLocation;
        }
        private void CreateSampleBlobFile()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true)
                                .Build();
            var sampleBlobFileContent           = "<contract xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:sfa:schemas:contract'></contract>";
            BlobContainerClient containerClient = new BlobContainerClient(configuration.GetSection("AzureBlobConfiguration").GetSection("ConnectionString").Value, "contractevents");

            containerClient.CreateIfNotExists();
            UTF8Encoding encoding = new UTF8Encoding();

            using MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(sampleBlobFileContent));
            containerClient.DeleteBlobIfExists(_blobName);
            containerClient.UploadBlob(_blobName, memoryStream);
        }
예제 #12
0
        static async Task Main(string[] args)
        {
            const string      fileName          = "Mobile-Engagement.svg";
            var               connectionString  = "DefaultEndpointsProtocol=https;AccountName=azstorageaccount204;AccountKey=bB0Y/sDN/32ZtTBiynihekpjCI3cyk9MaJON7MWuh422QXRgv0bFE5oWYfvYDSlQJ7fEFiUqQeIsgkQ+q/TNUw==;EndpointSuffix=core.windows.net";
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("vscontainer");

            containerClient.CreateIfNotExists();

            // Uploading a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            blobClient.Upload(fileName, overwrite: true);

            BlobClient blob2   = containerClient.GetBlobClient("test/" + fileName);
            var        content = blob2.Upload(fileName, overwrite: true);

            HandleConCurrency(ConCurrencyType.Default, blob2, content);
            HandleConCurrency(ConCurrencyType.Optimistic, blob2, content);
            HandleConCurrency(ConCurrencyType.Pessimistic, blob2, content);

            // Listing Blobs
            var blobs = containerClient.GetBlobs();

            foreach (var blob in blobs)
            {
                Console.WriteLine(blob.Name);
            }

            var testBlobs = containerClient.GetBlobs(prefix: "test");

            foreach (var blob in testBlobs)
            {
                Console.WriteLine(blob.Name);
            }

            IDictionary <string, string> metadata = new Dictionary <string, string>()
            {
                ["DocType"] = "Audit",
                ["Owner"]   = "Sam"
            };

            await ListBlobsSegments(containerClient).ConfigureAwait(false);

            blob2.SetMetadata(metadata);
        }
예제 #13
0
        /// <summary>
        /// Configures the Data Protection API for the application by using Azure Storage.
        /// </summary>
        /// <param name="services">Specifies the contract for a collection of service descriptors.</param>
        /// <param name="configure">Configures the available options. Null to use defaults.</param>
        public static IServiceCollection AddDataProtectionAzure(this IServiceCollection services, Action <AzureDataProtectionOptions> configure = null)
        {
            services.TryAddSingleton(typeof(IDataProtectionEncryptor <>), typeof(DataProtectionEncryptor <>));
            var       serviceProvider    = services.BuildServiceProvider();
            var       hostingEnvironment = serviceProvider.GetRequiredService <IWebHostEnvironment>();
            var       environmentName    = Regex.Replace(hostingEnvironment.EnvironmentName ?? "Development", @"\s+", "-").ToLowerInvariant();
            const int defaultKeyLifetime = 90;
            var       options            = new AzureDataProtectionOptions {
                StorageConnectionString = serviceProvider.GetRequiredService <IConfiguration>().GetConnectionString("StorageConnection"),
                ContainerName           = environmentName,
                ApplicationName         = hostingEnvironment.ApplicationName,
                KeyLifetime             = defaultKeyLifetime
            };

            options.Services = services;
            configure?.Invoke(options);
            options.Services = null;
            if (options.KeyLifetime <= 0)
            {
                options.KeyLifetime = defaultKeyLifetime;
            }
            var container = new BlobContainerClient(options.StorageConnectionString, options.ContainerName);

            container.CreateIfNotExists();
            // Enables data protection services to the specified IServiceCollection.
            var dataProtectionBuilder = services.AddDataProtection()
                                        // Configures the data protection system to use the specified cryptographic algorithms by default when generating protected payloads.
                                        // The algorithms selected below are the default and they are added just for completeness.
                                        .UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration {
                EncryptionAlgorithm = EncryptionAlgorithm.AES_256_GCM,
                ValidationAlgorithm = ValidationAlgorithm.HMACSHA512
            })
                                        .PersistKeysToAzureBlobStorage(options.StorageConnectionString, options.ContainerName, "keys.xml")
                                        // Configure the system to use a key lifetime. Default is 90 days.
                                        .SetDefaultKeyLifetime(TimeSpan.FromDays(options.KeyLifetime))
                                        // This prevents the apps from understanding each other's protected payloads (e.x Azure slots). To share protected payloads between two apps,
                                        // use SetApplicationName with the same value for each app.
                                        .SetApplicationName(options.ApplicationName);

            if (options.DisableAutomaticKeyGeneration)
            {
                // Configure the system not to automatically roll keys (create new keys) as they approach expiration.
                dataProtectionBuilder.DisableAutomaticKeyGeneration();
            }
            return(services);
        }
예제 #14
0
      public static void Run([BlobTrigger("cookbookfiles2/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob, string name, ILogger log)
      {
          var    folderTarget     = "destino";
          var    connectionTarget = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
          string keyName          = "CopyPrefix";
          string prefix           = Configuration[keyName];

          log.LogInformation($"***Lab*****Función disparada por cambio en blob \n Name:{name} \n Size: {myBlob.Length} Bytes");
          if (name.Contains(".svg"))
          {
              BlobContainerClient containerTarget = new BlobContainerClient(connectionTarget, folderTarget);
              containerTarget.CreateIfNotExists();
              BlobClient blobTarget = containerTarget.GetBlobClient($"{prefix}_{name}");
              blobTarget.Upload(myBlob);
              log.LogInformation($"***Lab***** File {name} copied into {folderTarget}");
          }
      }
예제 #15
0
        public async Task <string> UploadImageAsync(Stream imageToUpload, Guid guid)
        {
            string containerName = DateTime.Now.ToString("yyyyMMMM").ToLower();
            string blobName      = $"{guid.ToString()}.png";

            BlobContainerClient container = new BlobContainerClient(_options.AzureBlob, containerName);

            container.CreateIfNotExists(publicAccessType: PublicAccessType.Blob);

            BlobClient blob     = container.GetBlobClient(blobName);
            var        response = await blob.UploadAsync(imageToUpload, httpHeaders : new BlobHttpHeaders()
            {
                ContentType = "image/png"
            });

            return(blob.Uri.ToString());
        }
예제 #16
0
        public BlockingKustoUploader(
            string blobConnectionString,
            string blobContainerName,
            KustoConnectionStringBuilder adminCsb,
            KustoConnectionStringBuilder kscb,
            bool demoMode,
            string tableName,
            int batchSize,
            TimeSpan flushDuration,
            bool resetTable = false)
        {
            Csb              = kscb;
            AdminCsb         = adminCsb;
            TableName        = tableName;
            BatchSize        = batchSize;
            _flushDuration   = flushDuration;
            _lastUploadTime  = DateTime.UtcNow;
            _resetTable      = resetTable;
            _initializeTable = false;

            Completed = new AutoResetEvent(false);

            if (Csb != null)
            {
                _ingestionProperties = new KustoIngestionProperties(Csb.InitialCatalog, tableName);

                if (demoMode)
                {
                    _ingestClient = KustoIngestFactory.CreateDirectIngestClient(this.AdminCsb);
                }
                else
                {
                    _ingestClient = KustoIngestFactory.CreateQueuedIngestClient(Csb);
                }
            }

            if (!string.IsNullOrEmpty(blobConnectionString) &&
                !string.IsNullOrEmpty(blobContainerName))
            {
                blobServiceClient   = new BlobServiceClient(blobConnectionString);
                blobContainerClient = blobServiceClient.GetBlobContainerClient(blobContainerName);
                blobContainerClient.CreateIfNotExists();
            }

            _nextBatch = new List <IDictionary <string, object> >();
        }
        public async Task <string> PostPhoto(IFormFile file)
        {
            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    BlobContainerClient blobServiceClient = new BlobContainerClient(ConnectionString, "blob-at");
                    blobServiceClient.CreateIfNotExists();
                    DateTime now        = DateTime.UtcNow;
                    var      blobClient = blobServiceClient.GetBlobClient($"{now.Ticks}-{file.FileName}");
                    await blobClient.UploadAsync(stream);

                    return(blobClient.Uri.ToString());
                }
            }
            return(null);
        }
예제 #18
0
        private static void SeedMedia(MediaContext context, IChecksumService checksumService, string storageConnectionString, Guid mediaId, Guid mediaVersionId, string mediaUrl)
        {
            if (!context.MediaItems.Any(x => x.Id == mediaId))
            {
                var container = new BlobContainerClient(storageConnectionString, MediaConstants.General.ContainerName);

                container.CreateIfNotExists();

                var blob = container.GetBlobClient($"{mediaVersionId}{Path.GetExtension(mediaUrl)}");

                using (var stream = new MemoryStream(File.ReadAllBytes(mediaUrl)))
                {
                    if (!blob.Exists())
                    {
                        blob.Upload(stream);
                    }

                    var mediaItem = new MediaItem
                    {
                        Id          = mediaId,
                        IsProtected = false
                    };

                    context.MediaItems.Add(mediaItem.FillCommonProperties());

                    var mediaItemVersion = new MediaItemVersion
                    {
                        Id          = mediaVersionId,
                        MediaItemId = mediaId,
                        Checksum    = checksumService.GetMd5(stream),
                        Filename    = Path.GetFileNameWithoutExtension(mediaUrl),
                        Extension   = Path.GetExtension(mediaUrl),
                        Folder      = MediaConstants.General.ContainerName,
                        MimeType    = MimeUtility.GetMimeMapping(Path.GetExtension(mediaUrl)),
                        Size        = blob.GetProperties().Value.ContentLength,
                        CreatedBy   = "system",
                        Version     = 1
                    };

                    context.MediaItemVersions.Add(mediaItemVersion.FillCommonProperties());

                    context.SaveChanges();
                }
            }
        }
예제 #19
0
 public NtStatus Mounted(IDokanFileInfo info)
 {
     try
     {
         _containerClient = new BlobContainerClient(_connectionString, _containerName);
         _containerClient.CreateIfNotExists(_publicAccessType, _containerMetaData,
                                            _blobContainerEncryptionScopeOptions, _cancellationToken);
         if (!IsNormalFile(Path.DirectorySeparatorChar.ToString(), null, out _rootDir) && !_rootDir.Exists())
         {
             _rootDir.IfNotExistsCreate();
         }
         return(DokanResult.Success);
     }
     catch (Exception ex)
     {
         return(DokanResult.Error);
     }
 }
예제 #20
0
        private async Task InitializeResourcesAsync()
        {
            if (!ResourcesInitialized)
            {
                _watermarkContainer.CreateIfNotExists(PublicAccessType.Blob);
                _uploadContainer.CreateIfNotExists();

                // OLD SDK
                //var permissions = await _publicContainer.GetPermissionsAsync();
                //if (permissions.PublicAccess == BlobContainerPublicAccessType.Off || permissions.PublicAccess == BlobContainerPublicAccessType.Unknown)
                //{
                //    // If blob isn't public, we can't directly link to the pictures
                //    await _publicContainer.SetPermissionsAsync(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
                //}

                ResourcesInitialized = true;
            }
        }
        public static IServiceCollection AddBlobContainerClient(this IServiceCollection serviceCollection, IConfiguration configuration)
        {
            string _connectionString = configuration["BlobStorage:ConnectionString"];
            string _containerName    = configuration["BlobStorage:ContainerName"];

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(_connectionString);

            // Create the container client object
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(_containerName);

            //Create the container if not exists
            blobContainerClient.CreateIfNotExists();

            serviceCollection.AddSingleton(blobContainerClient);

            return(serviceCollection);
        }
예제 #22
0
        public async Task <IActionResult> GetFileAsync(string fileId)
        {
            // TODO: Verify that user is allowed to get files for this chat/call

            // Prepare Table Storage clients
            TableServiceClient tableServiceClient = new TableServiceClient(_storageAccountConnectionString);
            TableClient        tableClient        = tableServiceClient.GetTableClient(_tableName);

            tableClient.CreateIfNotExists();

            // Get file info from Table Storage
            Azure.Response <TableEntity> getTableEntityResponse;
            try
            {
                getTableEntityResponse = await tableClient.GetEntityAsync <TableEntity>(fileId, fileId);
            }
            catch (Azure.RequestFailedException e)
            {
                if (e.Status == 404)
                {
                    return(NotFound());
                }

                return(BadRequest("Couldn't get file from storage"));
            }

            var fileName = getTableEntityResponse.Value.GetString("FileName");

            // Prepare Blob Storage clients and container
            BlobContainerClient containerClient = new BlobContainerClient(_storageAccountConnectionString, _blobContainerName);

            containerClient.CreateIfNotExists();
            BlobClient blob = containerClient.GetBlobClient(fileId);

            // MemoryStream blobStream = new MemoryStream();
            // var downloadResult = await blob.DownloadToAsync(blobStream);
            var blobStream = await blob.OpenReadAsync();

            return(new FileStreamResult(blobStream, "application/octet-stream")
            {
                FileDownloadName = fileName
            });
        }
예제 #23
0
        /// <summary>
        /// running app/svc/pod/vm is assigned an identity (user-assigned, system-assigned)
        /// </summary>
        /// <returns></returns>
        private bool TryCreateUsingMsi()
        {
            _logger.LogInformation($"trying to access blob using msi...");
            try
            {
                var containerClient = new BlobContainerClient(_blobSettings.ContainerEndpoint, new DefaultAzureCredential());
                containerClient.CreateIfNotExists();

                TryRecreateTestBlob(containerClient);
                _logger.LogInformation($"Succeed to access blob using msi");
                Client = containerClient;
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"failed to access blob {_blobSettings.Account}/{_blobSettings.Container} using msi");
                return(false);
            }
        }
예제 #24
0
        /// <summary>
        ///   Creates a new <see cref="AzureBlobStorage"/> instance with the
        ///   specified configuration.
        /// </summary>
        /// <param name="configuration">The configuration to use.</param>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="configuration"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="configuration"/> is invalid.
        /// </exception>
        public AzureBlobStorage(AzureBlobStorageConfiguration configuration)
            : base(configuration)
        {
            if (configuration.ConnectionString == null)
            {
                throw new ArgumentNullException("configuration.ConnectionString");
            }
            if (configuration.ContainerName == null)
            {
                throw new ArgumentNullException("configuration.ContainerName");
            }

            _container = new BlobContainerClient(
                configuration.ConnectionString,
                configuration.ContainerName
                );

            //Log.Information("Using Azure blob storage: {0}", _container.Uri);
            _container.CreateIfNotExists();
        }
        private static BlobContainerClient GetContainer()
        {
            // Get a connection string to our Azure Storage account.  You can
            // obtain your connection string from the Azure Portal (click
            // Access Keys under Settings in the Portal Storage account blade)
            // or using the Azure CLI with:
            //
            //     az storage account show-connection-string --name <account_name> --resource-group <resource_group>
            //
            // And you can provide the connection string to your application
            // using an environment variable.
            string connectionString = "<connection_string>";
            string containerName    = "***";

            BlobContainerClient container = new BlobContainerClient(connectionString, containerName);

            container.CreateIfNotExists();

            return(container);
        }
        public async Task <IActionResult> Upload()
        {
            var formCollection = await Request.ReadFormAsync();

            var files = formCollection.Files;

            foreach (var file in files)
            {
                var blobContainerClient = new BlobContainerClient("UseDevelopmentStorage=true", "images");
                blobContainerClient.CreateIfNotExists();
                var containerClient = blobContainerClient.GetBlobClient(file.FileName);
                var blobHttpHeader  = new BlobHttpHeaders
                {
                    ContentType = file.ContentType
                };
                await containerClient.UploadAsync(file.OpenReadStream(), blobHttpHeader);
            }

            return(Ok());
        }
예제 #27
0
        private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {
            // Get Container reference
            BlobContainerClient container = BlobServiceClient.GetBlobContainerClient("uploads");

            container.CreateIfNotExists();

            // Get reference to the blob
            BlobClient blob = container.GetBlobClient(e.Name);

            // Delete the blob if it already exists
            blob.DeleteIfExists();

            // Upload file to blob
            Console.WriteLine("Uploading to BlobStorage: {0}", e.FullPath);
            blob.Upload(e.FullPath);

            // Delete file
            File.Delete(e.FullPath);
        }
        public HomeController()
        {
            if (!containerCreated)
            {
                string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"].ToString();

                // Create a client to interact with blob service.
                BlobServiceClient client = new BlobServiceClient(connectionString);

                // Create a container named "webappstoragedotnet-imagecontainer" in this storage account first if you want interact with truly Azure service.
                blobContainer = client.GetBlobContainerClient(BlobContainerName);
                blobContainer.CreateIfNotExists();

                // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate
                // access to the resource. The second approach is to set permissions to allow public access to blobs in this container.Then you can view the image.
                blobContainer.SetAccessPolicy(PublicAccessType.Blob);

                containerCreated = true;
            }
        }
        /// <summary>
        /// Saves a stream to the specified container with the given name. If the file exists it will be overwritten
        /// </summary>
        /// <param name="fileName">Name of the file to save</param>
        /// <param name="container">Name of the container to save the file to</param>
        /// <param name="stream">Stream containing the file contents</param>
        public override void SaveFileStream(string fileName, string container, Stream stream)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException(nameof(fileName));
            }

            if (String.IsNullOrEmpty(container))
            {
                throw new ArgumentException(nameof(container));
            }
            container = container.Replace('\\', '/');

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!initialized)
            {
                Initialize();
            }

            try
            {
                var containerTuple = ParseContainer(container);

                container = containerTuple.Item1;
                fileName  = string.Concat(containerTuple.Item2, fileName);

                BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(container);
                blobContainerClient.CreateIfNotExists(PublicAccessType.None);

                BlobClient blob = blobContainerClient.GetBlobClient(fileName);
                blob.Upload(stream);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #30
0
        private async Task InitializeContainer()
        {
            var blobContainer = new BlobContainerClient(_connectionString, _blobContainerName);

            blobContainer.CreateIfNotExists();

            var directory = new DirectoryInfo("Resources");
            var files     = directory.GetFiles();

            foreach (var file in files)
            {
                var name = Path.GetFileNameWithoutExtension(file.Name).ToLower();
                if (!await CheckImageExistance(name))
                {
                    using (var stream = file.OpenRead())
                    {
                        await blobContainer.UploadBlobAsync(name, stream);
                    }
                }
            }
        }