Ejemplo n.º 1
0
        /// <inheritdoc />
        public async Task <Uri> StoreFileAsync(
            VersionedInstanceIdentifier versionedInstanceIdentifier,
            Stream stream,
            CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(versionedInstanceIdentifier, nameof(versionedInstanceIdentifier));
            EnsureArg.IsNotNull(stream, nameof(stream));

            BlockBlobClient blob = GetInstanceBlockBlob(versionedInstanceIdentifier);

            stream.Seek(0, SeekOrigin.Begin);

            var blobUploadOptions = new BlobUploadOptions {
                TransferOptions = _options.Upload
            };

            try
            {
                await blob.UploadAsync(
                    stream,
                    blobUploadOptions,
                    cancellationToken);

                return(blob.Uri);
            }
            catch (Exception ex)
            {
                throw new DataStoreException(ex);
            }
        }
Ejemplo n.º 2
0
        private async Task <string> UploadImageAsync(HttpPostedFileBase fileToUpload)
        {
            try
            {
                string              connectionString  = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
                BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
                string              containerName     = "techstoreimage";
                BlobContainerClient containerClient   = blobServiceClient.GetBlobContainerClient(containerName);
                string              fileName          = Guid.NewGuid().ToString() + ".jpg";
                BlobClient          blobClient        = containerClient.GetBlobClient(fileName);
                BlobUploadOptions   blobUploadOptions = new BlobUploadOptions
                {
                    HttpHeaders = new BlobHttpHeaders
                    {
                        ContentType = "image/jpeg"
                    }
                };
                await blobClient.UploadAsync(fileToUpload.InputStream, blobUploadOptions);

                return(blobClient.Uri.AbsoluteUri);
            }
            catch
            { }
            return("default.jpg");
        }
Ejemplo n.º 3
0
    public async Task Step2_cause_blob_to_end_up_in_a_limbo_state_by_moving_it()
    {
        // Download the blob
        var serviceClient   = new BlobServiceClient(connectionString);
        var containerClient = serviceClient.GetBlobContainerClient("repro");
        var blobClient      = containerClient.GetBlobClient("aabbccdd-1122-3344-5566-778899aabbcc.txt");

        var response = await blobClient.DownloadAsync();

        // upload to the destination - first two characters and then the original blob
        var uploadClient = containerClient.GetBlobClient("aa/aabbccdd-1122-3344-5566-778899aabbcc.txt");

        // The code set the LocalId in case this is an insert and verifies the blob tag value is lesser value in case it's an update
        var options = new BlobUploadOptions
        {
            Tags = new Dictionary <string, string> {
                { "LocalId", "123" }
            },
            Conditions = new BlobRequestConditions
            {
                TagConditions = $@"""LocalId"" < '123'"
            }
        };

        try
        {
            await uploadClient.UploadAsync(response.Value.Content, options);
        }
        catch (RequestFailedException exception) when(exception.ErrorCode == BlobErrorCode.ConditionNotMet)
        {
            output.WriteLine("The blob 'repo/aa/aabbccdd-1122-3344-5566-778899aabbcc.txt' is now a limbo state.");
        }
    }
Ejemplo n.º 4
0
        protected void SendFile(BlobClient blob, string fileNameAndPath)
        {
            if (!File.Exists(fileNameAndPath))
            {
                throw new CantSendFileDataWhenFileDoesNotExistException(fileNameAndPath);
            }

            if (!overwrite && blob.ExistsAsync().Result)
            {
                return;
            }

            using (StreamReader sr = new StreamReader(fileNameAndPath))
            {
                var uploadOptions = new BlobUploadOptions()
                {
                    HttpHeaders = new BlobHttpHeaders()
                    {
                        ContentHash = ComputeHash(fileNameAndPath)
                    },
                    TransferOptions = new global::Azure.Storage.StorageTransferOptions()
                    {
                        InitialTransferSize = 50000000
                    }
                };

                blob.Upload(sr.BaseStream, uploadOptions);
            }
        }
Ejemplo n.º 5
0
        public async Task UploadAsync_Stream_Tags()
        {
            // Arrange
            await using DisposingContainer test = await GetTestContainerAsync();

            var        name = GetNewBlobName();
            BlobClient blob = InstrumentClient(test.Container.GetBlobClient(name));
            var        data = GetRandomBuffer(Constants.KB);
            IDictionary <string, string> tags    = BuildTags();
            BlobUploadOptions            options = new BlobUploadOptions
            {
                Tags = tags
            };

            // Act
            using (var stream = new MemoryStream(data))
            {
                await blob.UploadAsync(stream, options);
            }

            Response <GetBlobTagResult> response = await blob.GetTagsAsync();

            // Assert
            AssertDictionaryEquality(tags, response.Value.Tags);
        }
        /// <summary>
        /// Adds a new item to the container
        /// </summary>
        /// <param name="file">File object that will be added</param>
        /// <returns>A storage item representing the added item</returns>
        public async Task <StoredItem> AddItem(IFormFile file, string containerName)
        {
            var container = await GetContainer(containerName);

            var blobClient = container.GetBlobClient(Guid.NewGuid().ToString());

            // Configure the content type and store the original file name as metadata
            BlobUploadOptions options = new BlobUploadOptions();

            options.HttpHeaders = new BlobHttpHeaders
            {
                ContentType = file.ContentType
            };
            options.Metadata = new Dictionary <string, string>()
            {
                { Constants.FileNameMetadataItemName, file.FileName }
            };

            // Upload the file
            using (var stream = file.OpenReadStream())
            {
                await blobClient.UploadAsync(stream, options);
            }

            // Return uploaded file info as storage item
            return(new StoredItem
            {
                Name = file.FileName,
                Location = blobClient.Name,
                FileSize = file.Length
            });
        }
Ejemplo n.º 7
0
        private async Task <string> PersistFileToAzureStorage(
            BlobFileUpload blobFileUpload,
            IFormFile formFile,
            CancellationToken cancellationToken = default)
        {
            var storage      = _configuration.GetValue <string>("AzureStorage:StorageAndContainerName");
            var fileFullName = $"{storage}{blobFileUpload.Name}";
            var blobUri      = new Uri(fileFullName);

            var blobUploadOptions = new BlobUploadOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "uploadedBy", blobFileUpload.UploadedBy },
                    { "description", blobFileUpload.Description }
                }
            };

            var blobClient = new BlobClient(blobUri, _tokenAcquisitionTokenCredential);

            var inputStream = formFile.OpenReadStream();
            await blobClient.UploadAsync(inputStream, blobUploadOptions, cancellationToken);

            return($"{blobFileUpload.Name} successfully saved to Azure Storage Container");
        }
        public async Task <BlobCreateResultModel> CreateAsync(string containerName, string blobName, Stream stream, string contentType = "", CancellationToken cancellationToken = default)
        {
            try
            {
                var containerClient = GetBlobContainerClient(containerName);

                EnsureContainerCreated(containerClient);

                var blobClient = containerClient.GetBlobClient(blobName);

                var uploadOptions = new BlobUploadOptions();

                if (!string.IsNullOrWhiteSpace(contentType))
                {
                    uploadOptions.HttpHeaders = new BlobHttpHeaders {
                        ContentType = contentType
                    };
                }

                var result = await blobClient.UploadAsync(stream, uploadOptions, cancellationToken);

                return(new BlobCreateResultModel
                {
                    ContainerName = blobClient.BlobContainerName,
                    BlobName = blobClient.Name,
                    Uri = blobClient.Uri.ToString(),
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);

                throw;
            }
        }
        void UploadText(BlobClient blob, string text, BlobRequestConditions conditions)
        {
            //var properties = blob.GetProperties();

            var headers = new BlobHttpHeaders
            {
                // Set the MIME ContentType every time the properties
                // are updated or the field will be cleared
                ContentType     = "text/plain",
                ContentLanguage = "en-us",

                // Populate remaining headers with
                // the pre-existing properties
                //CacheControl = properties.Value.CacheControl,
                //ContentDisposition = properties.Value.ContentDisposition,
                ContentEncoding = "UTF-8", // properties.Value.ContentEncoding,
                //ContentHash = properties.Value.ContentHash
            };

            // Set the blob's properties.
            //blob.SetHttpHeaders(headers);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
            {
                // Set the If-Match condition to the original ETag.
                var options = new BlobUploadOptions()
                {
                    Conditions  = conditions,
                    HttpHeaders = headers,
                };

                blob.Upload(stream, options);
            }
        }
        private static async Task <string> ImageUploadToBlob(string fileName, MemoryStream imageStream, string contentType, AppSettings appSettings)
        {
            var containerName           = appSettings.MediaStorageContainer;
            var storageConnectionString = appSettings.MediaStorageConnectionString;

            //create a blob container client
            BlobContainerClient blobContainerClient = new BlobContainerClient(storageConnectionString, containerName);

            //create a blob
            BlobClient blobClient        = blobContainerClient.GetBlobClient(fileName);
            var        blobUploadOptions = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = contentType
                }
            };

            await blobClient.UploadAsync(imageStream, blobUploadOptions);

            //get url (without query string as it will contain SAS token if used in connection string)
            string url = blobClient.Uri.GetLeftPart(UriPartial.Path);

            return(url);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Uploads the image to azure blob storage
        /// </summary>
        /// <param name="file"> file to upload </param>
        /// <returns> new BlobClient object </returns>
        public async Task <BlobClient> UploadImage(IFormFile file)
        {
            BlobContainerClient container = new BlobContainerClient(Configuration["ImageBlob"], "images");

            await container.CreateIfNotExistsAsync();

            BlobClient blob = container.GetBlobClient(file.FileName);

            using var stream = file.OpenReadStream();

            BlobUploadOptions options = new BlobUploadOptions()
            {
                HttpHeaders = new BlobHttpHeaders()
                {
                    ContentType = file.ContentType
                }
            };

            if (!blob.Exists())
            {
                await blob.UploadAsync(stream, options);
            }

            return(blob);
        }
Ejemplo n.º 12
0
        /// <inheritdoc/>
        public async Task UploadBlobAsync(
            BlobContainerClient containerClient,
            string blobName,
            Stream input,
            string contentType,
            string contentEncoding,
            CancellationToken cancellationToken = default)
        {
            try
            {
                // Ensure container is created
                await containerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken : cancellationToken);

                var headers = new BlobHttpHeaders
                {
                    ContentEncoding = contentEncoding,
                    ContentType     = contentType,
                };

                var options = new BlobUploadOptions
                {
                    HttpHeaders = headers,
                };

                // Upload blob
                BlobClient blob = containerClient.GetBlobClient(blobName);
                await blob.UploadAsync(input, options, cancellationToken);
            }
            catch (Exception ex)
            {
                throw CreateException(ex, "Could not upload BLOB", containerClient.Name, blobName);
            }
        }
        private static void UploadImages(bool upload1000)
        {
            Console.WriteLine("Uploading images");
            int uploaded = 0;

            // Setup the number of the concurrent operations.
            BlobUploadOptions options = new BlobUploadOptions
            {
                TransferOptions = new Azure.Storage.StorageTransferOptions
                {
                    MaximumConcurrency = 64
                }
            };

            // Set ServicePointManager.DefaultConnectionLimit to the number of eight times the number of cores.
            ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 8;
            ServicePointManager.Expect100Continue      = false;
            // Setup the transfer context and track the upload progress.
            //var context = new SingleTransferContext
            //{
            //    ProgressHandler =
            //        new Progress<TransferStatus>(
            //            (progress) => { Console.WriteLine("Bytes uploaded: {0}", progress.BytesTransferred); })
            //};

            if (upload1000)
            {
                LoadImagesFromDisk(true);
                for (var i = 0; i < 200; i++)
                {
                    foreach (var image in _sourceImages)
                    {
                        // Rewind the memory stream
                        image.Position = 0;
                        var filename        = GenerateRandomFileName();
                        var blobBlockClient = new BlockBlobClient(BlobStorageConnection, "images", filename);
                        var task            = blobBlockClient.UploadAsync(image, options);
                        task.Wait();
                        uploaded++;
                        Console.WriteLine($"Uploaded image {uploaded}: {filename}");
                    }
                }
            }
            else
            {
                LoadImagesFromDisk(false);
                foreach (var image in _sourceImages)
                {
                    var filename        = GenerateRandomFileName();
                    var blobBlockClient = new BlockBlobClient(BlobStorageConnection, "images", filename);
                    var task            = blobBlockClient.UploadAsync(image, options);
                    task.Wait();
                    uploaded++;
                    Console.WriteLine($"Uploaded image {uploaded}: {filename}");
                }
            }

            Console.WriteLine("Finished uploading images");
        }
Ejemplo n.º 14
0
        internal byte[] GetThumbnail(string fileId, string fileName, int width, int height, int align)
        {
            byte[] bytes = null;

            string thumbBlobName = $"{ObjectType}/{ObjectId}/{width}x{height}x{align}/{fileName}";

            var thumbBlob = Container.GetBlobClient(thumbBlobName);

            if (thumbBlob.Exists())
            {
                var downloadResult = thumbBlob.DownloadContent().Value;

                bytes = downloadResult.Content.ToArray();
            }
            else
            {
                var imageBlob = Container.GetBlobClient(fileId);

                if (imageBlob.Exists())
                {
                    Stream       imageStream = null;
                    MemoryStream thumbStream = null;

                    try
                    {
                        var downloadResult = imageBlob.DownloadContent().Value;
                        imageStream = downloadResult.Content.ToStream();

                        thumbStream = new MemoryStream();
                        Thumbnail.Create(imageStream, fileName, width, height, align, thumbStream);

                        var uploadOptions = new BlobUploadOptions
                        {
                            HttpHeaders = new BlobHttpHeaders
                            {
                                ContentType  = MimeType.Jpeg,
                                CacheControl = Settings.ClientCacheControl
                            }
                        };

                        thumbBlob.Upload(thumbStream, uploadOptions);

                        thumbStream.Position = 0;

                        bytes = thumbStream.ToArray();
                    }
                    finally
                    {
                        imageStream?.Dispose();
                        thumbStream?.Dispose();
                    }
                }
            }

            return(bytes);
        }
Ejemplo n.º 15
0
        public string UploadImage(string id, Stream stream, string contentType)
        {
            BlobClient blobClient = _blobContainerClient.GetBlobClient(id);
            var        options    = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders {
                    ContentType = contentType
                },
            };

            blobClient.Upload(stream, options);
            return(blobClient.Uri.AbsoluteUri);
        }
        public Task FileUploadAsync(string name, MemoryStream file, string mimetype, CancellationToken cancellationToken)
        {
            BlobClient blob = _assetsContainer.GetBlobClient(name);

            var options = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = mimetype
                }
            };

            return(blob.UploadAsync(file, options, cancellationToken));
        }
Ejemplo n.º 17
0
        /// <inheritdoc/>
        public async Task <Response <BlobContentInfo> > WritePolicyConditionallyAsync(string filepath, Stream fileStream, string blobLeaseId)
        {
            BlobClient blobClient = CreateBlobClient(filepath);

            BlobUploadOptions blobUploadOptions = new BlobUploadOptions()
            {
                Conditions = new BlobRequestConditions()
                {
                    LeaseId = blobLeaseId
                }
            };

            return(await WriteBlobStreamInternal(blobClient, fileStream, blobUploadOptions));
        }
Ejemplo n.º 18
0
        /// <inheritdoc/>
        public async ValueTask PutFileAsync(IFileSystemEntry entry, CancellationToken cancellationToken = default)
        {
            var options = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = entry.ContentType,
                }
            };

            // TODO: Check file size limit here.
            using Stream stream = await entry.CreateReadStreamAsync();

            _ = await this.container.GetBlobClient(entry.Name).UploadAsync(stream, options, cancellationToken);
        }
Ejemplo n.º 19
0
        private async Task WriteStateAndCreateContainerIfNotExists <T>(string grainType, GrainReference grainId, IGrainState <T> grainState, BinaryData contents, string mimeType, BlobClient blob)
        {
            try
            {
                var conditions = string.IsNullOrEmpty(grainState.ETag)
                    ? new BlobRequestConditions {
                    IfNoneMatch = ETag.All
                }
                    : new BlobRequestConditions {
                    IfMatch = new ETag(grainState.ETag)
                };

                var options = new BlobUploadOptions
                {
                    HttpHeaders = new BlobHttpHeaders {
                        ContentType = mimeType
                    },
                    Conditions = conditions,
                };

                var result = await DoOptimisticUpdate(
                    () => blob.UploadAsync(contents, options),
                    blob,
                    grainState.ETag)
                             .ConfigureAwait(false);

                grainState.ETag         = result.Value.ETag.ToString();
                grainState.RecordExists = true;
            }
            catch (RequestFailedException exception) when(exception.IsContainerNotFound())
            {
                // if the container does not exist, create it, and make another attempt
                if (this.logger.IsEnabled(LogLevel.Trace))
                {
                    this.logger.LogTrace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound,
                                         "Creating container: GrainType={GrainType} GrainId={GrainId} ETag={ETag} to BlobName={BlobName} in Container={ContainerName}",
                                         grainType,
                                         grainId,
                                         grainState.ETag,
                                         blob.Name,
                                         container.Name);
                }
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);

                await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, mimeType, blob).ConfigureAwait(false);
            }
        }
        public async Task Second_upload_of_blob_from_RetryableStreamImpl_with_tags_and_INvalid_conditions_should_NOT_overwrite_blob()
        {
            BlobClient blobClient = Fixture.GetBlobClient(Guid.NewGuid().ToString());

            var options = new BlobUploadOptions
            {
                Tags = new Dictionary <string, string> {
                    { "MyTag", "10" }
                }
            };

            await using var sourceStream = await Fixture.GetSampleBlob();

            await blobClient.UploadAsync(sourceStream, options).ConfigureAwait(false);

            string text = await TestFixture.DownloadAndReadBlobContents(blobClient).ConfigureAwait(false);

            Assert.Equal("sample", text);

            // Reupload with conditions
            options = new BlobUploadOptions
            {
                Tags = new Dictionary <string, string> {
                    { "MyTag", "1" }
                },
                Conditions = new BlobRequestConditions
                {
                    TagConditions = $@"""MyTag"" < '1'"
                }
            };

            await using var sourceStream2 = await Fixture.GetSampleBlob(TestFixture.Samples.sample2);

            try
            {
                await blobClient.UploadAsync(sourceStream2, options).ConfigureAwait(false);
            }
            catch (RequestFailedException exception) when(exception.ErrorCode == BlobErrorCode.ConditionNotMet)
            {
                // We are expecting this! The BlobRequestConditions aren't met
            }

            // We should still have original content here
            text = await TestFixture.DownloadAndReadBlobContents(blobClient).ConfigureAwait(false);

            Assert.Equal("sample", text);
        }
        private async Task <string> UploadAsync(BlobContainerClient client, AuditEvent auditEvent, string existingBlobName)
        {
            var blobName = existingBlobName ?? BlobNameBuilder?.Invoke(auditEvent) ?? string.Format("{0}.json", Guid.NewGuid());
            var blob     = client.GetBlobClient(blobName);
            var options  = new BlobUploadOptions()
            {
                Metadata   = MetadataBuilder?.Invoke(auditEvent),
                AccessTier = AccessTierBuilder?.Invoke(auditEvent)
            };

#if NETSTANDARD2_0
            await blob.UploadAsync(new BinaryData(auditEvent, JsonSettings), options);
#else
            await blob.UploadAsync(new BinaryData(auditEvent, Core.Configuration.JsonSettings), options);
#endif
            return(blobName);
        }
Ejemplo n.º 22
0
        private static async Task ImageUploadToBlob(BlobContainerClient blobContainerClient, HttpContent content, string fileName)
        {
            // Get image stream
            var stream = await content.ReadAsStreamAsync();

            //create a blob
            var blobClient        = blobContainerClient.GetBlobClient(fileName);
            var blobUploadOptions = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = content.Headers.ContentType.ToString()
                }
            };

            await blobClient.UploadAsync(stream, blobUploadOptions);
        }
Ejemplo n.º 23
0
        public async Task Upload_ImmutableStorageWithVersioning(bool multipart)
        {
            // Arrange
            await using DisposingImmutableStorageWithVersioningContainer vlwContainer = await GetTestVersionLevelWormContainer(TestConfigOAuth);

            BlockBlobClient blockBlob = InstrumentClient(vlwContainer.Container.GetBlockBlobClient(GetNewBlobName()));

            byte[] data = GetRandomBuffer(Constants.KB);
            using Stream stream = new MemoryStream(data);

            BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy
            {
                ExpiresOn  = Recording.UtcNow.AddMinutes(5),
                PolicyMode = BlobImmutabilityPolicyMode.Unlocked
            };

            // The service rounds Immutability Policy Expiry to the nearest second.
            DateTimeOffset expectedImmutabilityPolicyExpiry = RoundToNearestSecond(immutabilityPolicy.ExpiresOn.Value);

            BlobUploadOptions options = new BlobUploadOptions
            {
                ImmutabilityPolicy = immutabilityPolicy,
                LegalHold          = true
            };

            if (multipart)
            {
                StorageTransferOptions transferOptions = new StorageTransferOptions
                {
                    InitialTransferSize = Constants.KB / 2,
                    MaximumTransferSize = Constants.KB / 2
                };
                options.TransferOptions = transferOptions;
            }

            // Act
            await blockBlob.UploadAsync(stream, options);

            // Assert
            Response <BlobProperties> propertiesResponse = await blockBlob.GetPropertiesAsync();

            Assert.AreEqual(expectedImmutabilityPolicyExpiry, propertiesResponse.Value.ImmutabilityPolicy.ExpiresOn);
            Assert.AreEqual(immutabilityPolicy.PolicyMode, propertiesResponse.Value.ImmutabilityPolicy.PolicyMode);
            Assert.IsTrue(propertiesResponse.Value.HasLegalHold);
        }
Ejemplo n.º 24
0
        private static async Task IndexUploadToBlob(BlobContainerClient blobContainerClient, MediaItem mediaItem, string fileName)
        {
            //convert string to stream
            var stream = new MemoryStream();

            JsonHelper.WriteJsonToStream(mediaItem, stream);

            //create a blob
            var blobClient        = blobContainerClient.GetBlobClient(fileName);
            var blobUploadOptions = new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = "application/json"
                }
            };

            await blobClient.UploadAsync(stream, blobUploadOptions);
        }
Ejemplo n.º 25
0
        public async Task <string> SaveDocumentAsync(string fileName, string contentType, Stream fileStream, CancellationToken token)
        {
            _logger.LogInformation($"fileName: {fileName}");
            var blobContainer = await GetContainerAsync();

            // Get a reference to a blob
            var             blobClient      = blobContainer.GetBlobClient(fileName);
            var             options         = new BlobUploadOptions();
            BlobHttpHeaders blobHttpHeaders = new BlobHttpHeaders();

            blobHttpHeaders.ContentType = contentType;
            options.HttpHeaders         = blobHttpHeaders;

            options.HttpHeaders.ContentType = contentType;

            await blobClient.UploadAsync(fileStream, options, token);

            return(string.Concat(blobClient.Uri.AbsoluteUri, "?", DateTime.UtcNow.ToEpoch()));
        }
Ejemplo n.º 26
0
        public async Task UploadAsync_File_Tags()
        {
            // Arrange
            await using DisposingContainer test = await GetTestContainerAsync();

            var        name = GetNewBlobName();
            BlobClient blob = InstrumentClient(test.Container.GetBlobClient(name));
            var        data = GetRandomBuffer(Constants.KB);
            IDictionary <string, string> tags    = BuildTags();
            BlobUploadOptions            options = new BlobUploadOptions
            {
                Tags = tags
            };

            using (var stream = new MemoryStream(data))
            {
                var path = Path.GetTempFileName();

                try
                {
                    File.WriteAllBytes(path, data);

                    // Test that we can upload a read-only file.
                    File.SetAttributes(path, FileAttributes.ReadOnly);

                    // Act
                    await blob.UploadAsync(path, options);
                }
                finally
                {
                    if (File.Exists(path))
                    {
                        File.SetAttributes(path, FileAttributes.Normal);
                        File.Delete(path);
                    }
                }
            }

            Response <GetBlobTagResult> response = await blob.GetTagsAsync();

            // Assert
            AssertDictionaryEquality(tags, response.Value.Tags);
        }
        public async Task Upload_blob_from_RetryableStreamImpl_with_tags_should_work()
        {
            BlobClient blobClient = Fixture.GetBlobClient(Guid.NewGuid().ToString());

            var options = new BlobUploadOptions
            {
                Tags = new Dictionary <string, string> {
                    { "MyTag", "1" }
                }
            };

            await using var sourceStream = await Fixture.GetSampleBlob();

            await blobClient.UploadAsync(sourceStream, options).ConfigureAwait(false);

            string text = await TestFixture.DownloadAndReadBlobContents(blobClient).ConfigureAwait(false);

            Assert.Equal("sample", text);
        }
        public void UploadBlob(string containerName, string blobName, string contentType, Stream content)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);

            if (!containerClient.Exists())
            {
                throw new ApplicationException($"Unable to upload blobs to container '{containerName}' as the container does not exists");
            }

            var blobClient = containerClient.GetBlobClient(blobName);
            var options    = new BlobUploadOptions()
            {
                HttpHeaders = new BlobHttpHeaders()
                {
                    ContentType = contentType
                }
            };
            var response = blobClient.Upload(content, options);
        }
Ejemplo n.º 29
0
    public async Task Step3_attempt_to_upload_a_new_version_of_blob_using_stream_workaround_that_works()
    {
        // Download the blob
        var serviceClient   = new BlobServiceClient(connectionString);
        var containerClient = serviceClient.GetBlobContainerClient("repro");
        var blobClient      = containerClient.GetBlobClient("aabbccdd-1122-3344-5566-778899aabbcc.txt");

        var response = await blobClient.DownloadAsync();

        // upload to the destination - first two characters and then the original blob
        var uploadClient = containerClient.GetBlobClient("aa/aabbccdd-1122-3344-5566-778899aabbcc.txt");

        // The code set the LocalId in case this is an insert and verifies the blob tag value is lesser value in case it's an update
        var options = new BlobUploadOptions
        {
            Tags = new Dictionary <string, string> {
                { "LocalId", "456" }
            },
            Conditions = new BlobRequestConditions
            {
                TagConditions = $@"""LocalId"" < '456'"
            }
        };

        // Workaround for https://github.com/Azure/azure-sdk-for-net/issues/20931
        await using var memoryStreamFix = new MemoryStream();
        await response.Value.Content.CopyToAsync(memoryStreamFix).ConfigureAwait(false);

        memoryStreamFix.Position = 0;
        // End Workaround

        try
        {
            await uploadClient.UploadAsync(memoryStreamFix, options);
        }
        catch (RequestFailedException exception) when(exception.ErrorCode == BlobErrorCode.ConditionNotMet)
        {
            output.WriteLine("Failed to copy 'repo/aa/aabbccdd-1122-3344-5566-778899aabbcc.txt' to 'repo/aa/aabbccdd-1122-3344-5566-778899aabbcc.txt' despite workaround.");
            output.WriteLine("Reason: 'repo/aa/aabbccdd-1122-3344-5566-778899aabbcc.txt' reported as existing and condition not met (412) despite 'repo/aa/aabbccdd-1122-3344-5566-778899aabbcc.txt' absense.");
            output.WriteLine($"Exception: {exception.Message}");
        }
    }
Ejemplo n.º 30
0
        public async Task <StoragePutResult> PutAsync(
            string path,
            Stream content,
            string contentType,
            CancellationToken cancellationToken)
        {
            var blob = _container.GetBlockBlobClient(path);

            //new global::Azure.Storage.Blobs.Models.BlobRequestConditions { }
            //var condition = AccessCondition.GenerateIfNotExistsCondition();

            //blob.Properties.ContentType = contentType;

            try
            {
                var options = new BlobUploadOptions
                {
                    Metadata = new Dictionary <string, string>
                    {
                        { "ContentType", contentType }
                    },
                    AccessTier = AccessTier.Cool,
                    //Conditions = new BlobRequestConditions
                    //{
                    //    IfMatch = new ETag()
                    //}
                };
                await blob.UploadAsync(content, options, cancellationToken);

                return(StoragePutResult.Success);
            }
            catch (RequestFailedException e) when(e.IsAlreadyExistsException())
            {
                using var targetStream = await blob.OpenReadAsync(new BlobOpenReadOptions (true), cancellationToken);

                content.Position = 0;
                return(content.Matches(targetStream)
                    ? StoragePutResult.AlreadyExists
                    : StoragePutResult.Conflict);
            }
        }