Introduction
This article will discuss how we can create/use MS Azure storage in ASP.NET Web application using MS Libraries. I am not an expert to discuss all the parts of Azure Storage but I am sharing information about Blob Storage.
What is Microsoft Azure Storage?
It is a Microsoft managed cloud storage service that provides storage of the user data. Azure storage consists of Blob storage, File Storage, and Queue storage. Using this service, we can store any kind of data such as text, image, files etc.
What is Blob Storage?
Blob storage is used to store unstructured data in Microsoft managed cloud service. We can access the data from anywhere where we have an internet connection 😛 in HTTP and HTTPS mode. Also, we can restrict the access to the blob storage as public or private.
We are storing the data in file system and we will have a main folder called container and inside that, we can keep the items in folders or as it is.
Let's start with Azure Account
Create Azure Account
Those who have a Microsoft account can sign in using those account details and use the service free for 30 days. To learn about blob storage this is enough; if you need to use this for your application then you need to buy a subscription.
Property Name | Description |
Name | The name must be unique. Minimum of 3 letters long and a maximum of 24. Note: -lowercase letters and numbers are allowed. |
Deployment model | Classic:-In this mode; the resources will be independent, will not treat it as a group. We need to manage each resource separately.Resource manager (ARM): - it a new feature in Azure storage, it will consider all the resource as a group, using power shell commands we can manage the resource easily. |
Performance | Standard:-It is storing the Data in magnetic drives, if your application frequently accesses the data or bulk data storage then we can choose this.Premium:-It is mainly used with azure virtual machines, if it is best for intensive applications like database |
Replication | How/where the data replicates. Replication copies the data in the storage and keep it in same data center or in different. Please see the table of data below from Microsoft about replication strategy. |
Secure Transfer Required | It is about HTTP and HTTPS transfer. |
Subscription | Please select your subscription. |
Resource Group | It is to group different services in single group. You can create different resource group for different application. |
Location | You can select the Data Center location. |
Virtual networks (Preview) | You can use virtual network to access this storage. |
Select Blob Storage
Select the storage account and choose the storage type "Blobs" from the list.
Lets Start to Store data.
You have many options to use /manage the storage accounts. Here we are going to discuss how we can achieve the same using C# code.
In brief, in this application I am using the blob storage to store the images generated and the images uploaded from the client system via my web application.
Before we start Writing code
- Create a new web application in Visual studio (I am using Visual Studio 2015).
- Using NuGet we can install required Assembly packages.
Go to "Manage Package for Solution Menu" and search for WindowsAzure.Storage and WindowsAzure.ConfigurationManager and click on install.
Now two packages are installed in your application, see the screenshot below.
- Add the following Azure Connection string to the web.config file. Don't forget to update the "AccountName" and "AccountKey". These two items you can get from the Azure portal itself, you can even get the entire connection string from there. See the screenshot below.
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup>
- <appSettings>
- <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key" /> </appSettings>
- </configuration>
Now your Development Environment is Ready, Let's Start with blob storage.
See below screen shot for how I designed my web application to complete this task. Here the Business Logic and Models I have created, you can choose your way of coding standards, that’s your choice.
Should include the below assemblies in the code.
- using Microsoft.WindowsAzure;
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
- using Microsoft.Azure;
Create Container
As I mentioned above, Blob items will reside inside a container in Azure Blob Storage. If we check the blob item URL then the container will be a part of the URL. It's like if we are accessing the file from file explorer then the path will contain the base folder.
Eg.
Rules to Create Container Name |
Name should be in lower case |
Must be at least 3 letters long and max 63 character allowed |
Should start with letter or number no special character except "-" |
The below sample code will create a new container using C# code while creating the object of the AzureBlobHelper class.
- public class AzureBlobHelper
- {
- CloudStorageAccount storageAAccountConnection {
- get {
- return CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
- }
- }
- CloudBlobClient _blobClient {
- get {
- return storageAAccountConnection.CreateCloudBlobClient();
- }
- }
- CloudBlobContainer _blobcontainer {
- get {
- return _blobClient.GetContainerReference("sampl");
- }
- }
- public AzureBlobHelper() {
- _blobcontainer.CreateIfNotExists();
- }
- }
Now, check your storage account, you can see the container sample generated.
By default, the container will be private, no one can access from outside. To set the permissions we should use the SetPermission method as below.
- CloudBlobContainer .SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
Please try different permissions in the list.
Upload a file(Blob) to container
Just now we created container in our storage account, now we need a file inside that container
Before uploading the file to blob we need to get the reference on the container. Once the container is available in the storage account then only we can upload the files to the storage account.
As per my design while creating the object of the AzureHelper class we will get the reference to the container. Check Create Container part.
To upload the file, I have created the following function in the AzureHelper class.
- public void SaveDataToAzureBlob(postedFileModel filemodel)
- {
- Stream _streamContent;
- HttpWebRequest _requestPage = (HttpWebRequest) WebRequest.Create(filemodel.filePath);
- HttpWebResponse _responseRequest = (HttpWebResponse) _requestPage.GetResponse();
- CloudBlockBlob _blockblob = _blobcontainer.GetBlockBlobReference(filemodel.filename);
-
- _blockblob.UploadFromStream(_responseRequest.GetResponseStream());
- }
You can upload the file to blob from Stream, File,ByteArray,Text etc. Try to find out the proper upload function for your requirement from the CloudBlockBlob class.
If the file name contains any directory name then those directories will create automatically in container.
Eg./Image/Barcode/image.png
Get List of Items from Blob
We created the container, uploaded the files to the blob. Now we are trying to get the list of items from the blob. For this also we need the reference of the container, and with the help of CloudBlobContainer.ListBlobs() function we can retrieve the all the items from the container.
The first parameter is will be the name of the blob object or you need all the file then just pass "null" as parameter. See the example code below.
- public List < BlobList > GetListOfata(postedFileModel filemodel) {
- List < BlobList > _blobList = new List < BlobList > ();
- if (filemodel != null) {
- CloudBlockBlob _blobpage = (CloudBlockBlob) _blobcontainer.ListBlobs(filemodel.filename, false).FirstOrDefault();
- _blobList.Add(new BlobList() {
- URI = _blobpage.Uri.ToString(), length = _blobpage.Properties.Length
- });
- } else {
- foreach(IListBlobItem item in _blobcontainer.ListBlobs(null, false)) {
- if (item.GetType() == typeof(CloudBlockBlob)) {
- CloudBlockBlob _blobpage = (CloudBlockBlob) item;
- _blobList.Add(new BlobList() {
- URI = _blobpage.Uri.AbsoluteUri.ToString(), length = _blobpage.Properties.Length
- });
- }
- }
- }
- return _blobList;
- }
In first condition, only the blob has the given name and in the else condition, we are getting all the list of items.
Conclusion
It's your turn to check, find out and use the remaining functions and services by Azure blob storage. I just discussed about Save and List the items from the Blob storage. You will get more help from the URL mentioned in the Reference part.
Reference
- https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-deployment-model
- https://docs.microsoft.com/en-us/azure/storage/blobs/storage-dotnet-how-to-use-blobs