protected void AssertBlobIsLeased(string containerName, string blobName, string leaseId)
        {
            var client    = StorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);

            if (!container.Exists())
            {
                Assert.Fail("AssertBlobIsLeased: The container '{0}' does not exist", containerName);
            }

            var blob = container.GetBlockBlobReference(blobName);

            if (!blob.Exists())
            {
                Assert.Fail("AssertBlobIsLeased: The blob '{0}' does not exist", blobName);
            }

            try
            {
                blob.RenewLease(new AccessCondition {
                    LeaseId = leaseId
                });
            }
            catch (Exception exc)
            {
                Assert.Fail("AssertBlobIsLeased: The blob '{0}' gave an {1} exception when renewing with the specified lease id: {2}", blobName, exc.GetType().Name, exc.Message);
            }
        }
示例#2
0
        private async Task Initialzie()
        {
            if (StorageAccount == null)
            {
                // Retrieve storage account from connection string.
                StorageAccount = CloudStorageAccount.Parse(_connectionString);

                // Create the blob client
                BlobClient = StorageAccount.CreateCloudBlobClient();

                // Retrieve reference to a previously created container.
                BlobContainer = BlobClient.GetContainerReference(_originalImageBlobContainerName);

                // Create the container if it doesn't already exist.
                await BlobContainer.CreateIfNotExistsAsync();

                // make access level to blob so urls are public
                var perm = await BlobContainer.GetPermissionsAsync();

                if (perm.PublicAccess != BlobContainerPublicAccessType.Blob)
                {
                    perm.PublicAccess = BlobContainerPublicAccessType.Blob;
                    await BlobContainer.SetPermissionsAsync(perm);
                }
            }
        }
        public BlobTriggerBinding(ParameterInfo parameter,
                                  StorageAccount hostAccount,
                                  StorageAccount dataAccount,
                                  IBlobPathSource path,
                                  IHostIdProvider hostIdProvider,
                                  QueuesOptions queueOptions,
                                  BlobsOptions blobsOptions,
                                  IWebJobsExceptionHandler exceptionHandler,
                                  IContextSetter <IBlobWrittenWatcher> blobWrittenWatcherSetter,
                                  SharedQueueWatcher messageEnqueuedWatcherSetter,
                                  ISharedContextProvider sharedContextProvider,
                                  IHostSingletonManager singletonManager,
                                  ILoggerFactory loggerFactory)
        {
            _parameter   = parameter ?? throw new ArgumentNullException(nameof(parameter));
            _hostAccount = hostAccount ?? throw new ArgumentNullException(nameof(hostAccount));
            _dataAccount = dataAccount ?? throw new ArgumentNullException(nameof(dataAccount));


            _blobClient                   = dataAccount.CreateCloudBlobClient();
            _accountName                  = BlobClient.GetAccountName(_blobClient);
            _path                         = path ?? throw new ArgumentNullException(nameof(path));
            _hostIdProvider               = hostIdProvider ?? throw new ArgumentNullException(nameof(hostIdProvider));
            _queueOptions                 = queueOptions ?? throw new ArgumentNullException(nameof(queueOptions));
            _blobsOptions                 = blobsOptions ?? throw new ArgumentNullException(nameof(blobsOptions));
            _exceptionHandler             = exceptionHandler ?? throw new ArgumentNullException(nameof(exceptionHandler));
            _blobWrittenWatcherSetter     = blobWrittenWatcherSetter ?? throw new ArgumentNullException(nameof(blobWrittenWatcherSetter));
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter ?? throw new ArgumentNullException(nameof(messageEnqueuedWatcherSetter));
            _sharedContextProvider        = sharedContextProvider ?? throw new ArgumentNullException(nameof(sharedContextProvider));
            _singletonManager             = singletonManager ?? throw new ArgumentNullException(nameof(singletonManager));
            _loggerFactory                = loggerFactory;
            _converter                    = CreateConverter(_blobClient);
            _bindingDataContract          = CreateBindingDataContract(path);
        }
 public GetStorageTokenController()
 {
     //IDictionary dict = Environment.GetEnvironmentVariables();
     ConnectionString = Environment.GetEnvironmentVariable(connString);
     StorageAccount   = CloudStorageAccount.Parse(ConnectionString);
     BlobClient       = StorageAccount.CreateCloudBlobClient();
 }
示例#5
0
        public BlobStorage(BlobSettings appSettings)
        {
            try
            {
                if (appSettings.ImageSize != null)
                {
                    ResizeLayer = new ResizeLayer(appSettings.ImageSize, ResizeMode.Min);
                }

                UploadThumbnail = appSettings.UploadThumbnail;

                StorageAccountName      = appSettings.StorageAccountName;
                StorageAccountAccessKey = appSettings.StorageAccountAccessKey;

                // Create a blob client and retrieve reference to images container
                BlobClient = StorageAccount.CreateCloudBlobClient();
                Container  = BlobClient.GetContainerReference(appSettings.ContainerName);

                // Create the "images" container if it doesn't already exist.
                if (Container.CreateIfNotExists())
                {
                    // Enable public access on the newly created "images" container
                    Container.SetPermissions(
                        new BlobContainerPermissions
                    {
                        PublicAccess =
                            BlobContainerPublicAccessType.Blob
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
示例#6
0
        public void GetNonExistingBlobNodeJS()
        {
            string ContainerName = Utility.GenNameString("upload-");

            // create the container
            CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(ContainerName);

            container.CreateIfNotExists();

            try
            {
                string BlobName = Utility.GenNameString("nonexisting");

                // Delete the blob if it exists
                CloudBlob blob = BlobHelper.QueryBlob(ContainerName, BlobName);
                if (blob != null)
                {
                    blob.DeleteIfExists();
                }

                //--------------Get operation--------------
                Test.Assert(!CommandAgent.GetAzureStorageBlob(BlobName, ContainerName), Utility.GenComparisonData("get blob", true));
                // Verification for returned values
                Test.Assert(CommandAgent.Output.Count == 0, "Only 0 row returned : {0}", CommandAgent.Output.Count);
                Test.Assert(CommandAgent.ErrorMessages.Count == 1, "1 error message returned : {0}", CommandAgent.ErrorMessages.Count);
            }
            finally
            {
                // cleanup
                container.DeleteIfExists();
            }
        }
示例#7
0
        /// <summary>
        /// Negative Functional Cases : for Remove-AzureStorageBlob
        /// 1. Remove a non-existing blob (Negative 2)
        /// </summary>
        internal void RemoveNonExistingBlob(Agent agent)
        {
            string CONTAINER_NAME = Utility.GenNameString("upload-");
            string BLOB_NAME      = Utility.GenNameString("nonexisting");

            // create the container
            CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME);

            container.CreateIfNotExists();

            try
            {
                // Delete the blob if it exists
                CloudBlob blob = BlobHelper.QueryBlob(CONTAINER_NAME, BLOB_NAME);
                if (blob != null)
                {
                    blob.DeleteIfExists();
                }

                //--------------Remove operation--------------
                Test.Assert(!agent.RemoveAzureStorageBlob(BLOB_NAME, CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageBlob", false));
                // Verification for returned values
                Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
                //the same error may output different error messages in different environments
                bool expectedError = agent.ErrorMessages[0].Contains(String.Format("Can not find blob '{0}' in container '{1}'", BLOB_NAME, CONTAINER_NAME)) ||
                                     agent.ErrorMessages[0].Contains("The remote server returned an error: (404) Not Found");
                Test.Assert(expectedError, agent.ErrorMessages[0]);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
示例#8
0
        public static void SetSerivceProperties(Constants.ServiceType serviceType, Microsoft.WindowsAzure.Storage.Shared.Protocol.ServiceProperties serviceProperties)
        {
            switch (serviceType)
            {
            case Constants.ServiceType.Blob:
                StorageAccount.CreateCloudBlobClient().SetServiceProperties(serviceProperties);
                break;

            case Constants.ServiceType.Queue:
                StorageAccount.CreateCloudQueueClient().SetServiceProperties(serviceProperties);
                break;

            case Constants.ServiceType.Table:
                StorageAccount.CreateCloudTableClient().SetServiceProperties(serviceProperties);
                break;

            case Constants.ServiceType.File:
                FileServiceProperties fileProperties = new FileServiceProperties();
                fileProperties.Cors          = serviceProperties.Cors;
                fileProperties.HourMetrics   = serviceProperties.HourMetrics;
                fileProperties.MinuteMetrics = serviceProperties.MinuteMetrics;
                StorageAccount.CreateCloudFileClient().SetServiceProperties(fileProperties);
                break;
            }
        }
示例#9
0
 public ImageController()
 {
     if (CloudStorageAccount.TryParse(StorageAccountConnectionString, out CloudStorageAccount StorageAccount))
     {
         cloudBlobClient = StorageAccount.CreateCloudBlobClient();
     }
 }
        public void TestFixtureTeardown()
        {
            //let's clean up!
            var client = StorageAccount.CreateCloudBlobClient();

            foreach (var containerPair in _containersToCleanUp)
            {
                var container = client.GetContainerReference(containerPair.Key);
                if (!string.IsNullOrEmpty(containerPair.Value))
                {
                    try
                    {
                        container.ReleaseLease(new AccessCondition()
                        {
                            LeaseId = containerPair.Value
                        });
                    }
                    catch
                    {
                        // ignore
                    }
                }
                container.DeleteIfExists();
            }
        }
        protected CloudBlockBlob CreateBlockBlob(string containerName, string blobName, Dictionary <string, string> metadata = null, string content = "Generic content", string contentType = "", string contentEncoding = "", string contentLanguage = "")
        {
            var client    = StorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);
            var blob      = container.GetBlockBlobReference(blobName);

            byte[] data = UTF8Encoding.UTF8.GetBytes(content);
            blob.UploadFromByteArray(data, 0, data.Length);

            blob.Properties.ContentType     = contentType;
            blob.Properties.ContentEncoding = contentEncoding;
            blob.Properties.ContentLanguage = contentLanguage;
            blob.SetProperties();

            if (metadata != null)
            {
                foreach (var key in metadata.Keys)
                {
                    blob.Metadata.Add(key, metadata[key]);
                }
                blob.SetMetadata();
            }

            return(blob);
        }
        protected Microsoft.WindowsAzure.Storage.Blob.ICloudBlob AssertBlobContainsData(string containerName, string blobName, BlobType blobType, byte[] expectedData)
        {
            var client    = StorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);

            if (!container.Exists())
            {
                Assert.Fail("AssertBlobContainsData: The container '{0}' does not exist", containerName);
            }

            var blob = (blobType == BlobType.BlockBlob
                ? (ICloudBlob)container.GetBlockBlobReference(blobName)
                : (ICloudBlob)container.GetPageBlobReference(blobName));

            if (!blob.Exists())
            {
                Assert.Fail("AssertBlobContainsData: The blob '{0}' does not exist", blobName);
            }

            using (var stream = new MemoryStream())
            {
                blob.DownloadToStream(stream);

                var gottenData = stream.ToArray();

                // Comparing strings -> MUCH faster than comparing the raw arrays
                var gottenDataString   = Convert.ToBase64String(gottenData);
                var expectedDataString = Convert.ToBase64String(expectedData);

                Assert.AreEqual(expectedData.Length, gottenData.Length);
                Assert.AreEqual(gottenDataString, expectedDataString);
            }

            return(blob);
        }
        protected List <ListBlockItem> AssertBlockListsAreEqual(string containerName, string blobName, GetBlockListResponse response)
        {
            var client    = StorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);

            if (!container.Exists())
            {
                Assert.Fail("AssertBlockExists: The container '{0}' does not exist", containerName);
            }

            var blob = container.GetBlockBlobReference(blobName);
            var committedBlockList   = blob.DownloadBlockList(BlockListingFilter.Committed);
            var uncommittedBlockList = blob.DownloadBlockList(BlockListingFilter.Uncommitted);
            var blockList            = committedBlockList.Concat(uncommittedBlockList).ToList();

            var gottenBlocks      = response.CommittedBlocks.Concat(response.UncommittedBlocks).ToList();
            var gottenBlocksCount = gottenBlocks.Count;

            Assert.AreEqual(blockList.Count, gottenBlocksCount);
            for (var i = 0; i < gottenBlocksCount; i++)
            {
                var expectedBlock = blockList[i];
                var gottenBlock   = gottenBlocks[i];
                Assert.AreEqual(expectedBlock.Name, gottenBlock.Name);
                Assert.AreEqual(expectedBlock.Length, gottenBlock.Size);
            }

            return(blockList);
        }
        protected void AssertBlobIsNotLeased(string containerName, string blobName)
        {
            var client    = StorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);

            if (!container.Exists())
            {
                Assert.Fail("AssertBlobIsNotLeased: The container '{0}' does not exist", containerName);
            }

            var blob = container.GetBlockBlobReference(blobName);

            if (!blob.Exists())
            {
                Assert.Fail("AssertBlobIsNotLeased: The blob '{0}' does not exist", blobName);
            }

            try
            {
                blob.AcquireLease(null, null);
            }
            catch (Exception exc)
            {
                Assert.Fail("AssertBlobIsNotLeased: The blob '{0}' gave an {1} exception when attempting to acquire a new lease: {2}", blobName, exc.GetType().Name, exc.Message);
            }
        }
示例#15
0
        /// <summary>
        /// Negative Functional Cases : for Remove-AzureStorageContainer
        /// 1. Remove the blob container with blobs in it without by force (Negative 3)
        /// </summary>
        internal void RemoveContainerWithoutForce(Agent agent)
        {
            string CONTAINER_NAME = Utility.GenNameString("withoutforce-");

            // create container if not exists
            CloudBlobClient    blobClient = StorageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(CONTAINER_NAME);

            container.CreateIfNotExists();
            blobUtil.CreateRandomBlob(container);

            try
            {
                //--------------Remove operation--------------
                Test.Assert(!agent.RemoveAzureStorageContainer(CONTAINER_NAME, Force: false), Utility.GenComparisonData("RemoveAzureStorageContainer", false));
                // Verification for returned values
                Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
                Test.Assert(agent.ErrorMessages[0].Contains("A command that prompts the user failed because"), agent.ErrorMessages[0]);
            }
            finally
            {
                // Recover the environment
                container.DeleteIfExists();
            }
        }
示例#16
0
        private ConnectionManagerAzureStorage()
        {
            StorageAccount = CloudStorageAccount.Parse(ConnectionString);

            //instantiate the client
            BlobClient = StorageAccount.CreateCloudBlobClient();
        }
示例#17
0
        /// <summary>
        /// This method initializes the blob client and container.
        /// </summary>
        public override void Initialize()
        {
            Client = StorageAccount.CreateCloudBlobClient();

            if (RequestOptionsDefault == null)
            {
                RequestOptionsDefault = new BlobRequestOptions()
                {
                    RetryPolicy     = new LinearRetry(TimeSpan.FromMilliseconds(200), 5)
                    , ServerTimeout = DefaultTimeout ?? TimeSpan.FromSeconds(1)
                                      //, ParallelOperationThreadCount = 64
                }
            }
            ;

            Client.DefaultRequestOptions = RequestOptionsDefault;

            if (ContainerId == null)
            {
                ContainerId = AzureStorageHelper.GetEnum <DataCollectionSupport>(Support).StringValue;
            }

            ContainerId = StorageServiceBase.ValidateAzureContainerName(ContainerId);

            Container = Client.GetContainerReference(ContainerId);

            Container.CreateIfNotExistsAsync(BlobAccessType, RequestOptionsDefault, Context).Wait();
        }
示例#18
0
        public CloudStorage(string storageConnectionString, string blobContainer, bool createIfNotExists = true)
        {
            if (string.IsNullOrWhiteSpace(blobContainer))
            {
                throw new Exception("O parâmetro 'blobContainer' não pode ser nulo, vazio ou em branco.");
            }

            if (string.IsNullOrWhiteSpace(storageConnectionString))
            {
                throw new Exception("O parâmetro 'storageConnectionString' não pode ser nulo, vazio ou em branco.");
            }

            if (blobContainer.Any(char.IsUpper))
            {
                throw new Exception("O parâmetro 'storageConnectionString' não pode conter caracteres em caixa alta.");
            }

            StorageAccount = CloudStorageAccount.Parse(storageConnectionString);
            BlobClient     = StorageAccount.CreateCloudBlobClient();
            BlobContainer  = BlobClient.GetContainerReference(blobContainer);

            if (createIfNotExists)
            {
                BlobContainer.CreateIfNotExists();
            }
        }
示例#19
0
 public GetStorageTokenController()
 {
     ConnectionString = Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MS_AzureStorageAccountConnectionString", EnvironmentVariableTarget.Process);
     Debug.WriteLine($"[GetStorageTokenController$init] Connection String = {ConnectionString}");
     StorageAccount = CloudStorageAccount.Parse(ConnectionString);
     BlobClient     = StorageAccount.CreateCloudBlobClient();
 }
示例#20
0
        public static CloudBlockBlob GetBlob(Uri uri)
        {
            CloudBlockBlob blob = StorageAccount.CreateCloudBlobClient().GetBlockBlobReference(uri.ToString());

            blob.FetchAttributes();
            return(blob);
        }
示例#21
0
        public static CloudBlockBlob CreateBlob(string containerName, string blobName)
        {
            CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(containerName);

            container.CreateIfNotExist();
            return(container.GetBlockBlobReference(blobName));
        }
示例#22
0
        /// <summary>
        /// downloads a blob asyncronously and saves it to disk
        /// </summary>
        /// <param name="container">The blob container where this file is stored</param>
        /// <param name="fileName">The path to the file in the blob container. Case sensitive. Will return false if the correct casing is not used</param>
        /// <param name="localFileName">the local path to save the blob</param>
        /// <returns>saves the blob to disk</returns>
        public async Task DownloadBlobAsync(string container, string remoteFileName, string localFileName)
        {
            try
            {
                // Create the blob client.
                var blobClient    = StorageAccount.CreateCloudBlobClient();
                var blobContainer = blobClient.GetContainerReference(container);
                // Retrieve reference to a blob named "photo1.jpg".
                var blockBlob = blobContainer.GetBlockBlobReference(remoteFileName);

                // Save blob contents to a file.
                using (var fileStream = System.IO.File.OpenWrite(localFileName))
                {
                    await blockBlob.DownloadToStreamAsync(fileStream);
                }
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine("Downloading blob was cancelled: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Downloading blob failed: {0}", ex.Message);
            }
        }
示例#23
0
        /// <summary>
        /// Uploads a string as a blob
        /// </summary>
        /// <param name="container">The blob container where this file will be stored</param>
        /// <param name="localFileName">The full path to the local file</param>
        /// <param name="fileContents">the string contents of the file</param>
        /// <param name="contentType">the content type of the file</param>
        /// <param name="cacheControlTTL">The number of seconds set against the 'public, max-age=XXXX' cache control property (default is 3600)</param>
        /// <param name="uploadTimeout">the number of seconds to wait before timing out (default is 90)</param>
        /// <param name="doCompression">whether or not to apply gzip compression</param>
        public async Task UploadStringBlobAsync(string container, string remoteFileName, string fileContents, string contentType, int?cacheControlTTL = 3600, int?uploadTimeout = 90, bool?doCompression = false)
        {
            try
            {
                var blobClient         = StorageAccount.CreateCloudBlobClient();
                var blobContainer      = blobClient.GetContainerReference(container);
                var blockBlob          = blobContainer.GetBlockBlobReference(remoteFileName);
                var blobRequestOptions = new BlobRequestOptions()
                {
                    ServerTimeout = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout)), MaximumExecutionTime = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout))
                };

                await blockBlob.UploadTextAsync(fileContents, null, null, blobRequestOptions, new OperationContext());

                blockBlob.Properties.ContentType  = contentType;
                blockBlob.Properties.CacheControl = string.Format("public, max-age={0}", cacheControlTTL);
                if (doCompression.HasValue && doCompression == true)
                {
                    blockBlob.Properties.ContentEncoding = "gzip";
                }
                blockBlob.SetProperties();
                if (doCompression.HasValue && doCompression == true)
                {
                    CompressBlob(container, remoteFileName, fileContents, contentType, cacheControlTTL);
                }
            }
            catch (StorageException ex)
            {
                var requestInformation = ex.RequestInformation;
                Trace.WriteLine(requestInformation.HttpStatusMessage);
                throw;
            }
        }
示例#24
0
        /// <summary>
        /// Uploads a local file to blob storage
        /// </summary>
        /// <param name="container">The blob container where this file will be stored</param>
        /// <param name="localFileName">The full path to the local file</param>
        /// <param name="fileContents">the stream contents of the file</param>
        /// <param name="contentType">the content type of the file</param>
        /// <param name="cacheControlTTL">The number of seconds set against the 'public, max-age=XXXX' cache control property (default is 3600)</param>
        /// <param name="uploadTimeout">the number of seconds to wait before timing out (default is 90)</param>
        /// <param name="doCompression">whether or not to apply gzip compression</param>
        public async Task UploadBlobAsync(string container, string remoteFileName, Stream fileContents, string contentType = null, int?cacheControlTTL = 3600, int?uploadTimeout = 90, bool?doCompression = false)
        {
            try
            {
                var blobClient         = StorageAccount.CreateCloudBlobClient();
                var blobContainer      = blobClient.GetContainerReference(container);
                var blockBlob          = blobContainer.GetBlockBlobReference(remoteFileName);
                var blobRequestOptions = new BlobRequestOptions()
                {
                    ServerTimeout = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout)), MaximumExecutionTime = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout))
                };
                await blockBlob.UploadFromStreamAsync(fileContents, null, blobRequestOptions, new OperationContext());

                blockBlob.Properties.ContentType  = !string.IsNullOrEmpty(contentType) ? contentType : this.ContentType(remoteFileName);
                blockBlob.Properties.CacheControl = string.Format("public, max-age={0}", cacheControlTTL);
                if (doCompression.HasValue && doCompression == true)
                {
                    blockBlob.Properties.ContentEncoding = "gzip";
                }
                blockBlob.SetProperties();
                if (doCompression.HasValue && doCompression == true)
                {
                    CompressBlob(container, remoteFileName, DownloadStringBlob(container, remoteFileName), contentType, cacheControlTTL);
                }
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine("Uploading blob was cancelled: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uploading blob failed: {0}", ex.Message);
            }
        }
示例#25
0
 /// <summary>
 /// Uploads a local file to blob storage
 /// </summary>
 /// <param name="container">The blob container where this file will be stored</param>
 /// <param name="remoteFileName">The remote name of the file</param>
 /// <param name="fileContents">the stream contents of the file</param>
 /// <param name="contentType">the content type of the file</param>
 /// <param name="cacheControlTTL">The number of seconds set against the 'public, max-age=XXXX' cache control property (default is 3600)</param>
 /// <param name="uploadTimeout">the number of seconds to wait before timing out (default is 90)</param>
 /// <param name="doCompression">whether or not to apply gzip compression</param>
 public void UploadBlob(string container, string remoteFileName, Stream fileContents, string contentType = null, int?cacheControlTTL = 3600, int?uploadTimeout = 90, bool?doCompression = false)
 {
     try
     {
         CloudBlobClient    blobClient         = StorageAccount.CreateCloudBlobClient();
         CloudBlobContainer blobContainer      = blobClient.GetContainerReference(container);
         CloudBlockBlob     blockBlob          = blobContainer.GetBlockBlobReference(remoteFileName);
         BlobRequestOptions blobRequestOptions = new BlobRequestOptions()
         {
             ServerTimeout = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout)), MaximumExecutionTime = TimeSpan.FromSeconds(Convert.ToInt16(uploadTimeout))
         };
         blockBlob.UploadFromStream(fileContents, null, blobRequestOptions);
         blockBlob.Properties.ContentType  = !string.IsNullOrEmpty(contentType) ? contentType : this.ContentType(remoteFileName);
         blockBlob.Properties.CacheControl = string.Format("public, max-age={0}", cacheControlTTL);
         if (doCompression.HasValue && doCompression == true)
         {
             blockBlob.Properties.ContentEncoding = "gzip";
         }
         blockBlob.SetProperties();
         if (doCompression.HasValue && doCompression == true)
         {
             CompressBlob(container, remoteFileName, DownloadStringBlob(container, remoteFileName), contentType, cacheControlTTL);
         }
     }
     catch (StorageException ex)
     {
         var requestInformation = ex.RequestInformation;
         Trace.WriteLine(requestInformation.HttpStatusMessage);
         throw;
     }
 }
        /// <summary>
        /// Instantiate a new AzureFileStore object.
        /// </summary>
        /// <param name="ConnectionString">Supplies the Azure connection string
        /// to initialize the file store against.</param>
        internal AzureFileStore(string ConnectionString)
        {
            StorageAccount = CloudStorageAccount.Parse(ConnectionString);
            BlobClient     = StorageAccount.CreateCloudBlobClient();

            BlobClient.DefaultRequestOptions.StoreBlobContentMD5         = true;
            BlobClient.DefaultRequestOptions.DisableContentMD5Validation = false;
        }
示例#27
0
        private static async Task <CloudBlobContainer> CreateContainerAsync(StorageAccount account, string containerName)
        {
            CloudBlobClient    client    = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(containerName);
            await container.CreateIfNotExistsAsync();

            return(container);
        }
示例#28
0
        private static CloudBlobContainer CreateContainer(StorageAccount account, string containerName)
        {
            var client = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(containerName);

            container.CreateIfNotExistsAsync().GetAwaiter().GetResult();
            return(container);
        }
示例#29
0
        public BlobRepository()
        {
            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CfCloudStorage"].ConnectionString;

            StorageAccount         = CloudStorageAccount.Parse(connectionString);
            BlobClient             = StorageAccount.CreateCloudBlobClient();
            BlobClient.RetryPolicy = RetryPolicies.Retry(4, TimeSpan.Zero);
        }
示例#30
0
        /// <summary>
        /// Functional Cases : for Get-AzureStorageContainer
        /// 1. Validate that all the containers can be enumerated (Positive 5)
        /// </summary>
        internal void EnumerateAllContainers(Agent agent)
        {
            //--------------Get operation--------------
            Test.Assert(agent.GetAzureStorageContainer(""), Utility.GenComparisonData("GetAzureStorageContainer", true));

            // Verification for returned values
            agent.OutputValidation(StorageAccount.CreateCloudBlobClient().ListContainers());
        }