Wednesday, 22 August 2012

Use Windows Azure Storage in your classic asp application


In this post I am going to explain how to use windows azure storage in our classic asp application. This is one of the scenario of moving your classic asp application to Azure Platform.
When we move to azure we can not use the server local space to save/upload files so in this case window azure is great things.
Below are the steps which need to be followed to achieve using of windows azure storage in classic asp application:
Step 1: Create a .net COM Visible class library solution which will have business logic to save/update/read file to/from the window storage.
To create a COM visible .net class library follow below steps:
  •     Create an interface with basic method signatures like create file, delete file, read file and list files.
    •          Create a class inheriting above interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Net;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
using System.IO;
using System.Collections;
namespace StorageUtilities
{
    [ComVisible(true),
    GuidAttribute("FADA9268-29C1-4BD2-BE61-6ABC8DB81959")]
    [ProgId("StorageUtilities.FileStorageOperations")]
    public class FileStorageOperations : IFileStorageOperations
    {
        private CloudBlobClient blobStorage;
        private CloudStorageAccount storageAccount;
        /// <summary>
        /// create a new file inside the blob container
        /// </summary>
        /// <param name=”blobcontainerName”>BlobContainer name</param>
        /// <param name=”fileName”>file name with extension</param>
        /// <param name=”fileContent”>file content</param>
        /// <param name=”fileType”>file type (for example: application/xls for xls file</param>
        /// <returns></returns>
        public string CreateFile(string accountName, string accountKey,stringblobContainerName, string fileName, string fileContent, string fileType)
        {
            try
            {
                //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                storageAccount=new CloudStorageAccount(newStorageCredentialsAccountAndKey(accountName,accountKey),true);
                // read account configuration settings
                blobContainerName = blobContainerName.ToLower();
                //Get the container reference
                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(blobContainerName);
                // Create a blob in container and upload contents to it
                string uniqueBlobName = string.Format(blobContainerName + ”/” + fileName);
                var blob = blobStorage.GetBlobReference(uniqueBlobName);
                //var sas = blob.GetSharedAccessSignature(new SharedAccessPolicy()
                //{
                //    Permissions = SharedAccessPermissions.Write,
                //    SharedAccessExpiryTime = DateTime.Now.AddMinutes(10)
                //});
                blob.Properties.ContentType = fileType;
                blob.UploadText(fileContent);
                return blob.Uri.ToString();
            }
            catch (Exception ex)
            {
               return ”Error:” + ex.Message;
            }
        }
        ///// <summary>
        ///// Delete the existing file from the blobcontainer
        ///// </summary>
        ///// <param name=”blobcontainerName”>BlobContainer name</param>
        ///// <param name=”fileName”>file name with extension</param>
        ///// <returns></returns>
        public string DeleteFile(string accountName, string accountKey, stringblobContainerName, string fileName)
        {
            try
            {
                //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                storageAccount=new CloudStorageAccount(newStorageCredentialsAccountAndKey(accountName,accountKey),true);
                blobContainerName = blobContainerName.ToLower();
                //Get the container reference
                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(blobContainerName);
                //Get the blob reference and delete the file.
                string uniqueBlobName = string.Format(blobContainerName + ”/” + fileName);
                var blob = blobStorage.GetBlobReference(uniqueBlobName);
                blob.DeleteIfExists();
                return ”true”;
            }
            catch (Exception ex)
            {
                return ”Error:” + ex.Message;
            }
        }
        ///// <summary>
        ///// Read the existing file in blob and returns the contents as a string
        ///// </summary>
        ///// <param name=”blobcontainerName”>BlobContainer name</param>
        ///// <param name=”fileName”>file name with extension</param>
        ///// <returns></returns>
        public object[] ReadFileContent(string accountName, string accountKey,string blobContainerName, string fileName)
        {
            try
            {
                //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                storageAccount = new CloudStorageAccount(newStorageCredentialsAccountAndKey(accountName, accountKey), true);
                ArrayList fileinfo = new ArrayList();
                blobContainerName = blobContainerName.ToLower();
                //Get the container reference
                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(blobContainerName);
                //Get the blob reference and read the content of the file.
                string uniqueBlobName = string.Format(blobContainerName + ”/” + fileName);
                var blob = blobStorage.GetBlobReference(uniqueBlobName);
                TextReader stringReader = new StringReader(blob.DownloadText());
                while (stringReader.Peek() >= 0)
                {
                    fileinfo.Add(stringReader.ReadLine());
                }
                return fileinfo.Cast<object>().ToArray(); ;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Returns files infos stored on blob
        /// </summary>
        /// <param name=”blobContainerName”>Blob Container Name</param>
        /// <returns></returns>
        public object[] Listfiles(string accountName, string accountKey, stringblobContainerName)
        {
            FileInfo[] filesInfo;
            try
            {
                //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                storageAccount=new CloudStorageAccount(newStorageCredentialsAccountAndKey(accountName,accountKey),true);
                blobContainerName = blobContainerName.ToLower();
                //Get the container reference
                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(blobContainerName);
                int noOfBlobs = container.ListBlobs().Count();
                filesInfo = new FileInfo[noOfBlobs];
                int count = 0;
                // Loop over blobs within the container and output the URI to each of them
                foreach (var blobItem in container.ListBlobs())
                {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.FilePath = blobItem.Uri.ToString();
                    var blob = blobStorage.GetBlobReference(blobItem.Uri.ToString());
                    fileInfo.Filename = blob.Name;
                    fileInfo.FileSize = ((Microsoft.WindowsAzure.StorageClient.CloudBlob)(blobItem)).Attributes.Properties.Length.ToString();
                    fileInfo.ContentType = ((Microsoft.WindowsAzure.StorageClient.CloudBlob)(blobItem)).Attributes.Properties.ContentType.ToString();
                    fileInfo.DateLastModified = ((Microsoft.WindowsAzure.StorageClient.CloudBlob)(blobItem)).Attributes.Properties.LastModifiedUtc.ToString();
                    filesInfo[count] = fileInfo;
                    count++;
                }
                return filesInfo.Cast<object>().ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
                // return (“Error:” + ex.Message).ToString().ToArray();
            }
        }
    }
}
  • Right click on the project, Go to Properties =>Build, and check the checkbox for “Register for COM  interop” as shown in below image.
 
  • Got to Signing and import the key as it is required to register the assembly to GAC.
 
  • Now we are ready with COM visible .net component.
Step 2: Now follow the below link to make use of our created component to the classic asp azure application.
        Above link has very nice explanation on how to make use of COM visible .net component to classic asp application.
  • Test the code using below code in your asp page.
          <%
 dim filestorageop,uploadedfile, strContent
 set filestorageop=server.CreateObject(“StorageUtilities.FileStorageOperations”)
 dim accountname,accountkey, containerName
 accountname=”AzureStorageAccountName”
 accountkey=”AzureStorageAccountKey”
 containerName=”exportfile”
 ’Creating file
 strContent=filestorageop.CreateFile(accountname,accountkey,containerName,”testfile1.txt”, ”text to write into the file”, ”application/txt”)
 ’Reading Content from the file
 strContent=filestorageop.ReadFileContent(accountname,accountkey,containerName,”testfile1.txt”)
 Dim mobjFolderContents
 dim mobjFileItem
 ’List all the files from the container
 mobjFolderContents = filestorageop.Listfiles(accountname,accountkey,containerName)
 Response.Write(UBound(mobjFolderContents))
  Response.Write ”<BR>”
              For each mobjFileItem in mobjFolderContents
                Response.Write(“FileName: “ & mobjFileItem.Filename)
          Response.Write ”<BR>”
          Response.Write(“FilePath: “ & mobjFileItem.FilePath & ”  “)
          Response.Write ”<BR>”
          Response.Write(“FileSize: “ & mobjFileItem.FileSize & ”  “)
          Response.Write ”<BR>”
          Response.Write(“Content Type: “ & mobjFileItem.ContentType & ”  “)
          Response.Write ”<BR>”
          Response.Write(“Date Last Modified: “ & mobjFileItem.DateLastModified)
          Response.Write ”<BR>”
          Response.Write ”<BR>”
        next
 set filestorageop=nothing
%>
Note: Please feel free to write in case of any query you have.

2 comments: