Log retries in Azure.Storage.Blob

129 Views Asked by At

I want to update a very old C# WinForms project which uses Microsoft.WindowsAzure.Storage library to use the "newest" possible Azure storage library Azure.Storage. I'm using .Net Framework 4.8.

One of the operations I'm not able to replace seems to be the Microsoft.WindowsAzure.Storage.OperationContext. We did log all the retries in the old app and I was wondering if this is still possible? How should I log errors or success with the new library?

Old code:

        var context = new OperationContext();
        context.ClientRequestID = myid; //"some request id";
        context.Retrying += (sender, args) =>
        {
            int retryCnt = context.RequestResults.Count;               
            ErrorMessage("Upload failed. Start Retry " + retryCnt + " for BLOB: " + blobName, myid);
        };

        // define action when request is completed -> the request is also completed when the upload failed
        context.RequestCompleted += (sender, args) =>
        {
            /* Collect operation completion information */
            if (args.Response != null)
            {
                DebugMessage("Upload completed for BLOB " + blobName, myid);
            }
            else
            {
                int retryCnt = context.RequestResults.Count - 1;
                ErrorMessage("Upload failed (Retry " + retryCnt + ") for BLOB " + blobName, myid);
            }
        };

I implemented retries with azure.storage using:

        BlobContainerClient container = null;            
        var options = new BlobClientOptions();            
        options.Retry.MaxRetries = 4;

        /* Create Handle to storage container using the sas to identify */
        try
        {                
            container = new BlobContainerClient(new Uri(sasToken),options);              
        }
        catch (Exception ex)
        {
            ErrorMessage("container reference couldn't be set" + ex.Message, String.Empty);
        }

Unfortunately I couln't find any good documentations on the retry topic.

1

There are 1 best solutions below

0
On

I tried the below Winforms .Net Framework 4.8. code with the newest Azure storage library and retry logic for uploading blob.

csproj :

ItemGroup>
    <Reference Include="Azure.Storage.Blobs, Version=12.19.1.0, Culture=neutral, PublicKeyToken=92742159e12e44c8, processorArchitecture=MSIL">
      <HintPath>..\packages\Azure.Storage.Blobs.12.19.1\lib\netstandard2.0\Azure.Storage.Blobs.dll</HintPath>
    </Reference>
    <Reference Include="Azure.Storage.Common, Version=12.18.1.0, Culture=neutral, PublicKeyToken=92742159e12e44c8, processorArchitecture=MSIL">
      <HintPath>..\packages\Azure.Storage.Common.12.18.1\lib\netstandard2.0\Azure.Storage.Common.dll</HintPath>
    </Reference>
</ItemGroup>

MainForm.cs :

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

namespace AzureBlobUploader
{
    public partial class MainForm : Form
    {
        private const string accountName = "<storage_name>";
        private const string containerName = "<container_name>";
        private const string blobName = "<blob_name>";
        private const string filePath = "<path_to_local_file>";
        private const string sasToken = "<SAS_token>";

        private Button uploadButton;

        public MainForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.uploadButton = new Button();
            this.SuspendLayout();

            this.uploadButton.Location = new System.Drawing.Point(12, 12);
            this.uploadButton.Name = "uploadButton";
            this.uploadButton.Size = new System.Drawing.Size(75, 23);
            this.uploadButton.TabIndex = 0;
            this.uploadButton.Text = "Upload";
            this.uploadButton.Click += new System.EventHandler(this.uploadButton_Click);

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(300, 200);
            this.Controls.Add(this.uploadButton);
            this.Name = "MainForm";
            this.Text = "Azure Blob Uploader";
            this.ResumeLayout(false);
        }

        private async void uploadButton_Click(object sender, EventArgs e)
        {
            await UploadBlobAsync();
        }

        private async Task UploadBlobAsync()
        {
            var blobUri = new Uri($"https://{accountName}.blob.core.windows.net/{containerName}/{blobName}{sasToken}");

            var options = new BlobClientOptions()
            {
                Retry =
                {
                    MaxRetries = 4,
                    Delay = TimeSpan.FromSeconds(2),
                    MaxDelay = TimeSpan.FromSeconds(16)
                }
            };

            var blobClient = new BlobClient(blobUri, options);

            int retryCount = 0;
            bool uploadSuccessful = false;

            while (retryCount <= options.Retry.MaxRetries)
            {
                try
                {
                    using (var fileStream = File.OpenRead(filePath))
                    {
                        await blobClient.UploadAsync(fileStream, true);
                        uploadSuccessful = true;
                        MessageBox.Show($"Blob '{blobName}' uploaded successfully!");
                        break; 
                    }
                }
                catch (RequestFailedException ex)
                {
                    retryCount++;
                    MessageBox.Show($"Upload attempt {retryCount} failed with status code: {ex.Status}");
                }
            }

            if (!uploadSuccessful)
            {
                MessageBox.Show($"Upload failed after {retryCount} retries for blob '{blobName}'");
            }
        }
    }
}

Output :

It ran successfully as shown below. Then, I clicked on Upload button. The blob uploaded successfully.

enter image description here

The blob was uploaded successfully to the storage account in the Azure portal.

enter image description here