Как работать с Optimisti c Concurrency в Azure .Storage.Blobs v12.xx из Azure dll - PullRequest
1 голос
/ 13 июля 2020

Я пытаюсь реализовать пример, представленный в Learn Path https://github.com/MicrosoftDocs/mslearn-support-concurrency-blob-storage/blob/master/src/OptimisticNewsEditor/Program.cs

Я пытаюсь использовать dll v12, который равен Azure .Storage.Blobs это код У меня есть.

public static async Task Main()
        {
            
            BlobContainerClient container;
            try
            {
                container = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName);
                await container.CreateIfNotExistsAsync(PublicAccessType.None);

            }
            catch (Exception)
            {
                var msg = $"Storage account not found. Ensure that the environment variable " +
                    " is set to a valid Azure Storage connection string and that the storage account exists.";
                Console.WriteLine(msg);
                return;
            }

            // First, the newsroom chief writes the story notes to the blob
            await SimulateChief();
            Console.WriteLine();

            await Task.Delay(TimeSpan.FromSeconds(2));

            // Next, two reporters begin work on the story at the same time, one starting soon after the other
            var reporterA = SimulateReporter("Reporter A", writingTime: TimeSpan.FromSeconds(12));
            await Task.Delay(TimeSpan.FromSeconds(4));
            var reporterB = SimulateReporter("Reporter B", writingTime: TimeSpan.FromSeconds(4));

            await Task.WhenAll(reporterA, reporterB);
            await Task.Delay(TimeSpan.FromSeconds(2));

            Console.WriteLine();
            Console.WriteLine("=============================================");
            Console.WriteLine();
            Console.WriteLine("Reporters have finished, here's the story saved to the blob:");

            BlobDownloadInfo story = await container.GetBlobClient(blobName).DownloadAsync();

            Console.WriteLine(new StreamReader(story.Content).ReadToEnd());
        }

        private static async Task SimulateReporter(string authorName, TimeSpan writingTime)
        {
            // First, the reporter retrieves the current contents
            Console.WriteLine($"{authorName} begins work");
            var blob = new BlobContainerClient(connectionString, containerName).GetBlobClient(blobName);

            var contents = await blob.DownloadAsync();

            Console.WriteLine($"{authorName} loads the file and sees the following content: \"{new StreamReader(contents.Value.Content).ReadToEnd()}\"");

            // Store the current ETag
            var properties = await blob.GetPropertiesAsync();
            var currentETag = properties.Value.ETag;
            Console.WriteLine($"\"{contents}\" has this ETag: {properties.Value.ETag}");

            // Next, the author writes their story. This takes some time.
            Console.WriteLine($"{authorName} begins writing their story...");
            await Task.Delay(writingTime);
            Console.WriteLine($"{authorName} has finished writing their story");

            try
            {
                // Finally, they save their story back to the blob.
                var story = $"[[{authorName.ToUpperInvariant()}'S STORY]]";
                await uploadDatatoBlob(blob, story);
                Console.WriteLine($"{authorName} has saved their story to Blob storage. New blob contents: \"{story}\"");
            }
            catch (RequestFailedException e)
            {
                // Catch error if the ETag has changed it's value since opening the file
                Console.WriteLine($"{authorName} sorry cannot save the file as server returned an error: {e.Message}");
            }
        }

        private static async Task SimulateChief()
        {
            var blob = new BlobContainerClient(connectionString, containerName).GetBlobClient(blobName);

            var notes = "[[CHIEF'S STORY NOTES]]";
            await uploadDatatoBlob(blob, notes);
            Console.WriteLine($"The newsroom chief has saved story notes to the blob {containerName}/{blobName}");
        }

        private static async Task uploadDatatoBlob(BlobClient blob, string notes)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(notes);
            MemoryStream stream = new MemoryStream(byteArray);
            await blob.UploadAsync(stream, overwrite: true);
        }

Мне нужно изменить UploadAsyn c, чтобы проверить наличие ETag перед загрузкой. В старой версии Azure. Net CLI у нас была библиотека Microsoft. Azure .Storage.Blob, теперь это обрабатывалась Optimisti c Concurrency с помощью

await blob.UploadTextAsync(story, null, accessCondition: AccessCondition.GenerateIfMatchCondition(currentETag), null, null);

Как мне это сделать в v12 dll. Любая помощь приветствуется.

1 Ответ

1 голос
/ 13 июля 2020

Используйте следующее переопределение метода UploadAsync:

UploadAsync(Stream, BlobHttpHeaders, IDictionary<String,String>, BlobRequestConditions, IProgress<Int64>, Nullable<AccessTier>, StorageTransferOptions, CancellationToken)

Вы можете определить условия доступа как часть параметра BlobRequestConditions.

...