Starting Azure Platform as a Service (PaaS) Development 101 Series: Lesson 3 of n – BLOB


Welcome back to the series Smile You can always view the list of all lessons here. Lesson 3 will be all about Azure BLOB Storage.

First things first.!

BLOB storage is part of storage accounts. BLOB storage enables you to store files in the cloud. When you upload a file into a BLOB container, you will start referring to the file as a BLOB and not a file anymore, don’t ask me why Smile with tongue out. There are two types of BLOBs, Block BLOBs and Page BLOBs. Block BLOBs can sit in one fixed block of a max of 200GB while Page BLOBs can grow up to 1TB and is used mostly when ranges of bytes in a file are frequently updated. Unfortunately you will get a flat container, meaning you can not have folders and sub folders there. Easiest trick in the book to get organized is to include a “/” in the BLOB name e.g. “images/avatar01.png” instead of “avatar1.png”.  Below diagram quickly illustrates the structure where containers sit inside storage accounts and BLOBs would sit inside the containers.

image

To learn more about Azure BLOB Storage click here.

What are we building today?

Since we have established by now that we won’t have fancy sample applications but instead direct answers in this series, I expect you to go over the previous lesson before continuing. I won’t show you how to create a storage account and get your hands on an access key every post Winking smile 

In a nutshell, we will build a simple CRUD command line application for an Azure Blob. Checkout the below screenshot of the console application.

image

The Console Application

Very straight forward, an endless loop displaying the menu and waiting for the user to input. A switch statement is there to trigger the right function based on user input.

  1. private const string Protocol = "https";
  2. private const string AccountName = "paas101";
  3. private const string AccountKey = "XXXXXX-KEY GOES HERE";
  4. private const string ContainerName = "lesson03";
  5. private const string Success = "\nOperation completed successfuly. Press any key to go back.";
  6.  
  7. private static string _connection;
  8.  
  9. static void Main(string[] args)
  10. {
  11.     _connection = string.Format("DefaultEndpointsProtocol={0};AccountName={1};AccountKey={2}",
  12.     Protocol, AccountName, AccountKey);
  13.  
  14.     Console.TreatControlCAsInput = true;
  15.     Console.Clear();
  16.  
  17.     while (true)
  18.     {
  19.         Console.Clear();
  20.  
  21.         Console.WriteLine("Welcome to Lesson 03, let's play with BLOB Storage.");
  22.         Console.WriteLine("\t1. Upload a new BLOB");
  23.         Console.WriteLine("\t2. Delete a specific BLOB");
  24.         Console.WriteLine("\t3. List all BLOBs");
  25.         Console.WriteLine("\t4. Exit");
  26.  
  27.         Console.WriteLine("So what do you want to do?");
  28.  
  29.         int input;
  30.         if (!int.TryParse(Console.ReadKey().KeyChar.ToString(), out input)) return;
  31.  
  32.         switch (input)
  33.         {
  34.             case 1:
  35.                 UploadNewBlob();
  36.                 break;
  37.             case 2:
  38.                 DeleteBlob();
  39.                 break;
  40.             case 3:
  41.                 ListAllBlobs();
  42.                 break;
  43.             case 4:
  44.                 Exit();
  45.                 break;
  46.         }
  47.     }
  48. }
  49.  
  50. private static void Exit()
  51. {
  52.     Environment.Exit(0);
  53. }

 

Upload a new BLOB

To keep it simple, we will ask the user for the path of a file they would like to upload to the BLOB container. At the main menu, when the user would input 1, they will be directed to the input screen.

image

At the input screen we will ask them about their file path.

image

Check out the function’s code below. We simply establish a BLOB client, get a reference to the container, ask the user for the file path and execute the upload activity.

  1. private static void UploadNewBlob()
  2. {
  3.     try
  4.     {
  5.         var client = CloudStorageAccount.Parse(_connection).CreateCloudBlobClient();
  6.  
  7.         Console.Clear();
  8.         Console.WriteLine("Where is your file?");
  9.         var filePath = Console.ReadLine();
  10.  
  11.         var container = client.GetContainerReference(ContainerName);
  12.         container.CreateIfNotExists();
  13.  
  14.         var blob = container.GetBlockBlobReference(filePath.Substring(filePath.LastIndexOf("\\") + 1));
  15.  
  16.         using (var fileStream = File.OpenRead(filePath))
  17.         {
  18.             blob.UploadFromStream(fileStream);
  19.         }
  20.  
  21.         Console.WriteLine(Success);
  22.         Console.ReadKey();
  23.     }
  24.     catch (StorageException ex)
  25.     {
  26.         Console.WriteLine(ex.Message);
  27.         Console.ReadKey();
  28.     }
  29. }

 

Delete a specific BLOB

From the main menu, the user will input 2 and be directed to the input screen.

image

At the input screen we will ask the user for the name of the BLOB they would like to delete.

image

To verify that the Blob was deleted, Browse the Server Explorer to reach the container and list it’s contents. As you can see the Blob03

image

Check out the function’s code below. We simply establish a BLOB client, get a reference to the container, ask the user for the BLOB name and execute the deletion activity.

  1. private static void DeleteBlob()
  2. {
  3.     try
  4.     {
  5.         var client = CloudStorageAccount.Parse(_connection).CreateCloudBlobClient();
  6.  
  7.         var container = client.GetContainerReference(ContainerName);
  8.         container.CreateIfNotExists();
  9.  
  10.         Console.Clear();
  11.         Console.WriteLine("\nEnter Blob name: ");
  12.  
  13.         var blobName = Console.ReadLine();
  14.         var blockBlob = container.GetBlockBlobReference(blobName);
  15.         blockBlob.Delete();
  16.  
  17.         Console.WriteLine(Success);
  18.         Console.ReadKey();
  19.     }
  20.     catch (StorageException ex)
  21.     {
  22.         Console.WriteLine(ex.Message);
  23.         Console.ReadKey();
  24.     }
  25. }

 

List all BLOBs in a Container

From the main menu, the user will input 3 and be directed to the list screen.

image

At the list screen an output of all the BLOB Uri’s will be displayed.

image

Check out the function’s code below. We simply establish a BLOB client, get a reference to the container, and finally loop the container BLOBs printing out the Uri.

  1. private static void ListAllBlobs()
  2. {
  3.     try
  4.     {
  5.         var client = CloudStorageAccount.Parse(_connection).CreateCloudBlobClient();
  6.  
  7.         var container = client.GetContainerReference(ContainerName);
  8.         container.CreateIfNotExists();
  9.  
  10.         Console.Clear();
  11.  
  12.         foreach (var item in container.ListBlobs(null, false))
  13.         {
  14.             var blockBlob = item as CloudBlockBlob;
  15.             if (blockBlob != null)
  16.             {
  17.                 var blob = blockBlob;
  18.                 Console.WriteLine(blob.Uri);
  19.             }
  20.             else
  21.             {
  22.                 var blob = item as CloudPageBlob;
  23.                 if (blob != null)
  24.                 {
  25.                     var pageBlob = blob;
  26.                     Console.WriteLine(pageBlob.Uri);
  27.                 }
  28.                 else
  29.                 {
  30.                     var blobDirectory = item as CloudBlobDirectory;
  31.                     if (blobDirectory == null) continue;
  32.                     var directory = blobDirectory;
  33.                     Console.WriteLine("Directory: {0}", directory.Uri);
  34.                 }
  35.             }
  36.         }
  37.  
  38.         Console.WriteLine(Success);
  39.         Console.ReadKey();
  40.     }
  41.     catch (StorageException ex)
  42.     {
  43.         Console.WriteLine(ex.Message);
  44.         Console.ReadKey();
  45.     }
  46. }

aaaand we are done with the lesson. Let me know if you have any questions or comments Smile

Comments (4)

  1. Luigi Crispo says:

    molto interessante

  2. Anonymous says:

    I always worry about how efficient (in execution speed and space) BLOB storage is with relatively small files. In my application, I have lots of small image files many of which are around 10k bytes in size. I wonder if BLOG storage is better than storing such small images as database field values.

  3. BALSHARFI says:

    @Paul Topping: Personally I would always go for BLOB and CDN. A hit over CDN will be always faster than connecting to a database and querying a table. In addition, how would the solution scale in case you have a growing user base globally? There are a lot of things to consider 🙂

  4. BALSHARFI says:

    @Luigi Crispo: grazie il mio amico per la lettura il mio diario

Skip to main content