Monday, 29 May 2023

Create, read and write Blobs in Azure Blob storage / containers using C# .NET

using Azure.Storage;

using Azure.Storage.Blobs;

using Azure.Storage.Blobs.Models;

using System;

using System.Threading.Tasks;

 

namespace BlobStorage

{  

 internal class Program

 {

        private const string blobServiceEndpoint = "https://mediastorrp.blob.core.windows.net/";

        private const string storageAccountName = "mediastorrp";

        private const string storageAccountKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        public static async Task Main(string[] args)

        {

        StorageSharedKeyCredential accountCredentials = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);

        BlobServiceClient serviceClient = new BlobServiceClient(new Uri(blobServiceEndpoint), accountCredentials);

 

            //1 get blob storage account details

        AccountInfo info = await serviceClient.GetAccountInfoAsync();

        await Console.Out.WriteLineAsync($"Connected to Azure Storage Account");

        await Console.Out.WriteLineAsync($"Account name:\t{storageAccountName}");

        await Console.Out.WriteLineAsync($"Account kind:\t{info?.AccountKind}");

        await Console.Out.WriteLineAsync($"Account sku:\t{info?.SkuName}");

 

            //2 Call iterate method for all containers in the account

        await EnumerateContainersAsync(serviceClient);

 

            //2 call method to enumerate all blobs in a container

        string existingContainerName = "raster-graphics";

        await EnumerateBlobsAsync(serviceClient, existingContainerName);

 

        // read blob

        string newContainerName = "vector-graphics";

        BlobContainerClient containerClient = await GetContainerAsync(serviceClient, newContainerName);

        string uploadedBlobName = "graph.svg";

        BlobClient blobClient = await GetBlobAsync(containerClient, uploadedBlobName);

        await Console.Out.WriteLineAsync($"Blob Url:\t{blobClient.Uri}");

        }

 

        // Iterate all containers in the account

        private static async Task EnumerateContainersAsync(BlobServiceClient client)

        {

        await foreach (BlobContainerItem container in client.GetBlobContainersAsync())

        {

            await Console.Out.WriteLineAsync($"Container:\t{container.Name}");

        }

        }

 

        // Iterate all blobs in the container

        private static async Task EnumerateBlobsAsync(BlobServiceClient client, string containerName)

        {

        BlobContainerClient container = client.GetBlobContainerClient(containerName);

        await Console.Out.WriteLineAsync($"Searching:\t{container.Name}");

        await foreach (BlobItem blob in container.GetBlobsAsync())

        {

            await Console.Out.WriteLineAsync($"Existing Blob:\t{blob.Name}");

        }

        }

 

        // get or create container if not exists

    private static async Task<BlobContainerClient> GetContainerAsync(BlobServiceClient client, string containerName)

    {

        BlobContainerClient container = client.GetBlobContainerClient(containerName);

        await container.CreateIfNotExistsAsync(PublicAccessType.Blob);

        await Console.Out.WriteLineAsync($"New Container:\t{container.Name}");

        return container;

    }

    private static async Task<BlobClient> GetBlobAsync(BlobContainerClient client, string blobName)

    {

        BlobClient blob = client.GetBlobClient(blobName);

        await Console.Out.WriteLineAsync($"Blob Found:\t{blob.Name}");

        return blob;

    }

 }

}


Call Azure API using Bearer acess token

using System;

using System.Drawing;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using System.Web;

using Azure.Identity;

using Azure.Core;

using Nancy.Json;

using Newtonsoft.Json;

 

namespace AzCallAzureApi

{

    internal class Program1

    {

        static async Task Main()

        {

            try

            {

                // get the access first token first.

                string token = await GetAccessToken("TenantID", "ClientID", "ClientSecret");

                // get the API and process the result

                await GetResults(token);

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Exception: {ex.Message}");

            }

        }

 

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)

        {

            Console.WriteLine("Begin GetAccessToken");

 

            var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);

            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), CancellationToken.None);

            return result.Token;

        }

 

        // Set authorization and call the required api method

        private static async Task<string> GetResults(string token)

        {

            var httpClient = new HttpClient

            {

                BaseAddress = new Uri("https://management.azure.com/subscriptions/")

            };

            string URI = "Your URI";

            httpClient.DefaultRequestHeaders.Remove("Authorization");

            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            HttpResponseMessage response = await httpClient.GetAsync(URI);

            if (response.IsSuccessStatusCode)

            {

                var HttpsResponse = await response.Content.ReadAsStringAsync();

                var JSONObject = JsonConvert.DeserializeObject<object>(HttpsResponse);

            Console.WriteLine(JSONObject);

            var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>((string)JSONObject);

            return response.StatusCode.ToString();

            }

            return string.Empty;

        }  

    }

}