Azure Storage – Part 3 – Read and Edit BLOB Storage Data from Azure Web App

Santosh Gaikwad
Latest posts by Santosh Gaikwad (see all)

<< Part 1        << Part 2      >> Part 4      >> Part 5          Download code

What is BLOB Storage?

BLOB is an acronym for Binary Large Object, which is a collection of binary data stored as a single entity.

Azure Blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred to as object storage.

BLOB storage can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.

For more information about Blob Storage please refer Part 2

How to read data programmatically from Blob storage?

Generally you would not be using Blob storage to upload data manually, there would be a system which will write data to and read data from blob storage.

This article focuses on reading, updating, deleting data from Blob storage using .NET code.

Step 1: Create Azure Blob Storage

Login to Azure ARM portal and create Blob storage account and container. To know about how to create Blob storage account and container, please refer article Azure Blob Storage

Blob Storage
Blob Storage

Step 2: Setup development environment

You need to install Visual Studio 2017; I am using Azure VM with Visual Studio 2017 for development environment. If you want to know more about how to create VMs with Specific software image in Azure please refer article Virtual Machine in Azure.

Development Environment
Development Environment

Step 3: Create new ASP.NET Web App

I decided to create ASP.NET Web app, but you can even select console app or windows form app, which ever you are comfortable with.

Create Web App
Create Web App

I have selected MVC template, it’s up to you which template you want to select. Code to read and update Azure Blob storage remains same irrespective of template.

Step 4: Use NuGet to install the required packages

There are two packages you need to reference in your project to complete this tutorial:

Microsoft Azure Storage Client Library for .NET: This package provides programmatic access to data resources in your storage account.

Microsoft Azure Configuration Manager library for .NET: This package provides a class for parsing a connection string in a configuration file, regardless of where your application is running.

Install Nuget Packages
Install Nuget Packages

Step 5: Create Views, Controller for Blob Details

Create views and controller for blob details, assumption is that you are aware of MVC pattern, hence skipping the steps for creating views, controller and making changes. Views are used to CRUD operations.

MVC Solution Structure
MVC Solution Structure

Step 6: Configure your storage connection string

The Azure Storage Client Library for .NET supports using a storage connection string to configure endpoints and credentials for accessing storage services. The best way to maintain your storage connection string is in a configuration file.

Add StorageConnectionString in web.config, make sure you copy connection string from the BLOB you created in Azure Portal,  following screen snap shows how to get the connection string.

  <appSettings>
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=blobstoragesci;AccountKey=qLYzEE72GWvhunLPkkZt9I2mPo5NP3HOaLDuqTIzXh/kqqrSr8a9ZAuvZKzwOnm7estxeE2u8aJEMULY0vRnfA==;EndpointSuffix=core.windows.net" />
  </appSettings>

Navigate to the Blob -> Access Keys (under settings section in properties blade), copy connection string, you can copy from either of the keys; they act as a backup keys, if one is compromised for some reason you can immediately use another one.

BLOB Access Keys and Connection String
BLOB Access Keys and Connection String

Step 7: Create class for model and business logic to Read and Edit Blob Storage data

Create following classes, which acts as a business layer which interacts with Azure Blob Storage, better not to add code directly to controller to achieve separation of concerns. Call methods of this class from controller of Blobdetails for actions like read, upload, delete, and download.

Create View model class for holding data to transfer from business layer to presentation layer.

File: BlobdetailsViewModels.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    [Table("Blobdetails")]
    public class BlobdetailsViewModels
    {
        public BlobdetailsViewModels()
        {
        }

        public BlobdetailsViewModels(string blobname, DateTime blobdate, string blobtype, long blobsize)
        {
            this.BlobName = blobname;
            this.BlobModifiedData = blobdate;
            this.BlobType = blobtype;
            this.BlobSize = blobsize;
        }

        [Key]
        public string BlobName { get; set; }
        public DateTime BlobModifiedData { get; set; }
        public string BlobType { get; set; }
        public long BlobSize { get; set; }
    }
}

Create class for business logic to perform actions on Azure BLOB storage, this is the important class file which interacts with Azure BLOB.

File: ReadEditBlob.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Azure; // Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Blob; // Namespace for Blob storage types
using WebApplication1.Models;
using System.IO;

namespace WebApplication1.BusinessLogic
{
    public class ReadEditBlob
    {
        public static void DeleteData(string filename)
        {
            try
            {
                // Retrieve storage account from connection string.
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnectionString"));
               // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

               // Retrieve reference to a previously created container.
                CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

               // Retrieve reference to a blob named "myfile.txt".
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
               // Delete the blob.
                blockBlob.Delete();           
            }
            catch (Exception)
            {
                throw;
            }
        }

       public static List<BlobdetailsViewModels> ReadBlobData()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

           // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

           // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
           List<BlobdetailsViewModels> blobdetailsViewModels = new List<BlobdetailsViewModels>();

           // Loop over items within the container and output the length and URI.
            foreach (IListBlobItem item in container.ListBlobs(null, false))
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    blobdetailsViewModels.Add(new BlobdetailsViewModels(Path.GetFileName(blob.Uri.AbsolutePath), blob.Properties.LastModified.Value.LocalDateTime, blob.BlobType.ToString(), blob.Properties.Length));
              }
            }
            return blobdetailsViewModels;
        }

       public static void UploadFile(string filelocation)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

           // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

           // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
           // Retrieve reference to a blob named "newfile".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("newfile");

           // Create or overwrite the "myblob" blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead(filelocation))
            {
                blockBlob.UploadFromStream(fileStream);
            }
        }
       public static string DownloadBlobToString(string blobname)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));
           // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
           // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
           CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(blobname);

           string text;
            using (var memoryStream = new MemoryStream())
            {
                blockBlob2.DownloadToStream(memoryStream);
                text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            return text;
        }
    }
}

Step 8: Testing web application

Deploy web app to Azure and its ready for testing.

Navigate to Home Page of web app

Home Page
Home Page

Click on the blob details link to read data from blob storage and list on web page

BLOB Data
BLOB Data

Following image shows data in Blob storage in Azure.

BLOB Data
BLOB Data

 

<< Part 1        << Part 2      >> Part 4      >> Part 5      Download code


Check Articles From Categories      Health and Parenting      Inspiring Stories      Technology      Microsoft Azure      SharePoint O365

4 Replies to “Azure Storage – Part 3 – Read and Edit BLOB Storage Data from Azure Web App”

  1. Good article. Can you share the source code used in the above sample app. Will use and check. Kindly share that project with us if you don’t mind. Thanks in advance.

    1. Hi Muthu,

      Thanks for motivating comments. sure will be providing code too, actually i work on temporary VMs, i am looking into better ways to share source code as an attachment along with article. i will see if project is still available with me and upload it.

      Regard,
      Santosh.

    2. Now you can download the code from the link provided on article.

      it contains code of only specific files and not entire solution.

Leave a Reply

Your email address will not be published. Required fields are marked *