Azure Blob Storage Helper Class and Shared Access Policy

Hi,

I have create a simple helper class that can be used to Upload Blobs to a public and private container. It then also allows you to grant users Temporary access at the blob level for 2 days. This is nice when you want to provide a download link that will expire.

Below is the class

using System.IO;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;



namespace Common.Azure
{
    public interface IStorage
    {

        string ContainerThumbnails { get; }
        string ContainerPhotos { get; }

        CloudStorageAccount StorageAccountInfo { get; set; }
        CloudBlobClient BlobClient { get; set; }

        CloudBlob UploadBlob(string blobUri, Stream stream, string containerName, bool isPublic);
        string GetSharedAccessSignatureToDownloadBlob(string blobUri, string containerName, string userName);
    }
}

 

using System;
using System.Configuration;
using System.IO;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace Common.Azure
{
    public class Storage : IStorage
    {
        public string ContainerThumbnails
        {
            get { return "photothumbnails"; }
        }
        public string ContainerPhotos
        {
            get { return "photos"; }
        }


        public CloudStorageAccount StorageAccountInfo { get; set; }
        public CloudBlobClient BlobClient { get; set; }

        public Storage()
        {

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                if (RoleEnvironment.IsAvailable)
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                else
                    configSetter(ConfigurationManager.AppSettings[configName]);
            });

            StorageAccountInfo = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            BlobClient = StorageAccountInfo.CreateCloudBlobClient();
        }



        public CloudBlob UploadBlob(string blobUri, Stream stream, string containerName, bool isPublic)
        {
            var container = BlobClient.GetContainerReference(containerName);
            container.CreateIfNotExist();

            if (isPublic)
            {
                var permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Container
                };
                container.SetPermissions(permissions);
            }
            else
            {
                var permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Off
                };
                container.SetPermissions(permissions);
            }


            var blob = container.GetBlockBlobReference(blobUri);
            blob.UploadFromStream(stream);
            return blob;
        }

        public string GetSharedAccessSignatureToDownloadBlob(string blobUri, string containerName, string userName)
        {
            var container = BlobClient.GetContainerReference(containerName);
            container.CreateIfNotExist();
            var blob = container.GetBlockBlobReference(blobUri);




              
            var containeraccess= new SharedAccessPolicy();
            containeraccess.Permissions = SharedAccessPermissions.Read;

            var blobaccess = new SharedAccessPolicy
                                 {
                                     SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2)
                                 };

            var perm = new BlobContainerPermissions
                           {
                               PublicAccess = BlobContainerPublicAccessType.Off
                           };
            perm.SharedAccessPolicies.Clear();
            perm.SharedAccessPolicies.Add(userName, containeraccess);

            container.SetPermissions(perm, new BlobRequestOptions());

            return blob.GetSharedAccessSignature(blobaccess, userName);
        }
    }
}

Now, in a MVC 3 controller, I can call the helper class when an order is submitted and removed from the shopping cart:

orderDetails.DownloadLink = storage.GetSharedAccessSignatureToDownloadBlob(photo.Photo_Url),
                                                                          "photos",
                                                                          cartItem.Username);

 

That’s all this is to it, then on the downloads link, you just render the shared access url

   //
        //Get: /Download/
        [HttpGet]
        public ActionResult Download(int photoId)
        {
            var userName = HttpContext.User.Identity.Name;
            OrderDetail order = _storeDb.OrderDetails.Include("Photo").Include("Order").First(x => x.PhotoId == photoId && x.Order.Username == userName);

            if (order == null)
                return View("InvalidPhoto");

            order.DownloadCount += 1;
            _storeDb.SaveChanges();

            string path = order.Photo.Photo_Url + order.DownloadLink;
            return base.Redirect(path);

        }

e.g.

http://myblobs.com/containername/blobname.jpg?se=2011-02-22T01%3A07%3A20Z&sr=b&si=romiko&sig=PsfUXcJtWRoWBvIiz%2FvHoUJnYF2D70%2B3CdlBbn9SiOM%3D

Advertisements

One thought on “Azure Blob Storage Helper Class and Shared Access Policy

  1. My developer is trying to persuade me to move to .
    net from PHP. I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using WordPress on several websites for about a year and am
    concerned about switching to another platform. I have heard good things about blogengine.

    net. Is there a way I can import all my wordpress content into it?
    Any kind of help would be really appreciated!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s