Wednesday, April 11, 2012

Azure CLoud Blob container without web role

You don't need Azure project or other roles to use blob. If you want to use Azure client in .Net project, you can add your config to app settings section and reference it. Azure client is a wrapper to rest calls. They have some request signing steps which make the calls difficult to implement with simple webrequests.

Settings:
 <add key="AzureBlobStorage" value="AccountName=youraccountname;AccountKey=YOURKEYeZgfgdfg==;DefaultEndpointsProtocol=https"/>

CLoud talker:



   /// <summary>
    /// Wrapper arount blob client
    /// </summary>
    public class CloudTalker
    {
        /// <summary>
        /// Logger
        /// </summary>
        protected static readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Get Client obj based on your app settings
        /// </summary>
        /// <returns></returns>
        public CloudBlobClient GetBlobClient()
        {
            var accountBlob = ConfigurationManager.AppSettings["AzureBlobStorage"];

            var account = CloudStorageAccount.Parse(accountBlob.ToString());
            
            return account.CreateCloudBlobClient();

        }

        /// <summary>
        /// Sync call for uploadting text
        /// </summary>
        /// <param name="blobItem"></param>
        public void CreateBlobText(BlobItem blobItem)
        {
            var client = GetBlobClient();
            var cloudBlobContainer = client.GetContainerReference(blobItem.ContainerReference);
            cloudBlobContainer.CreateIfNotExist();

            var blob = cloudBlobContainer.GetBlobReference(blobItem.FileName);
            blob.UploadText(blobItem.Content);
            
        }

        /// <summary>
        /// Create blob from stream in async mode
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <param name="stream"></param>
        public void CreateBlobFromStream(string path, string fileName, Stream stream)
        {
            var client = GetBlobClient();
            var cloudBlobContainer = client.GetContainerReference(path);
            cloudBlobContainer.CreateIfNotExist();

            var blob = cloudBlobContainer.GetBlobReference(fileName);
            logger.Trace("Upload Stream Start path:"+path+" file "+fileName);
            blob.BeginUploadFromStream(stream, UploadFinished, blob.Uri);
        }

        /// <summary>
        /// To keep track latest upload
        /// </summary>
        private static string LatestUploadURI { get; set; }

        /// <summary>
        /// Callback for upload
        /// </summary>
        /// <param name="asyncResult"></param>
        private void UploadFinished(IAsyncResult asyncResult)
        {
            // async msg
            var bloburi = (Uri)asyncResult.AsyncState;
            
            LatestUploadURI = bloburi.ToString();
            logger.Trace("Upload Stream Finished path:" + LatestUploadURI);
        }

        public int CountBlobs(string containerId)
        {

            CloudBlobClient blobClient = GetBlobClient();
            CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference(containerId);

            cloudBlobContainer.FetchAttributes();

            string count = cloudBlobContainer.Metadata["ItemCount"];
            string countUpdateTime = cloudBlobContainer.Metadata["CountUpdateTime"];

            bool recountNeeded = false;

            if (String.IsNullOrEmpty(count) || String.IsNullOrEmpty(countUpdateTime))
            {
                recountNeeded = true;
            }
            else
            {
                DateTime dateTime = new DateTime(long.Parse(countUpdateTime));
                // Are we close to the last modified time?
                if (Math.Abs(dateTime.Subtract(cloudBlobContainer.Properties.LastModifiedUtc).TotalSeconds) > 5)
                {
                    recountNeeded = true;
                }
            }

            int blobCount;
            if (recountNeeded)
            {
                blobCount = 0;
                BlobRequestOptions options = new BlobRequestOptions();
                options.BlobListingDetails = BlobListingDetails.Metadata;

                foreach (IListBlobItem item in cloudBlobContainer.ListBlobs(options))
                {
                    blobCount++;
                }

                cloudBlobContainer.Metadata.Set("ItemCount", blobCount.ToString());
                cloudBlobContainer.Metadata.Set("CountUpdateTime", DateTime.Now.Ticks.ToString());
                cloudBlobContainer.SetMetadata();
            }
            else
            {
                blobCount = int.Parse(count);
            }

            return blobCount;
        }

        public IEnumerable<BlobContainerView> ListContainers()
        {
            var containerlist = new List<BlobContainerView>();

            var client = GetBlobClient();
            var cloudBlobContainers = client.ListContainers();

            foreach (var cloudBlobContainer in cloudBlobContainers)
            {
                containerlist.Add(new BlobContainerView { Name = cloudBlobContainer.Name, Uri = cloudBlobContainer.Uri.ToString(), BlobCount = cloudBlobContainer.ListBlobs().Count() });

            }

            return containerlist;
        }

        public IEnumerable<ListBlobItemView> ListAllBlobs(string folder)
        {
            var client = GetBlobClient();
            var cloudBlobContainer = client.GetContainerReference(folder);
            var listBlobItems = cloudBlobContainer.ListBlobs();

            return listBlobItems.ToModelView();
        }

        public string GetBlobText(BlobItem blobItem)
        {
            CloudBlob blob = GetBlob(blobItem);
            if (blob.HasBlob())
            {
                return blob.DownloadText();
            }
            return "";
        }

        public CloudBlob GetBlob(BlobItem blobItem)
        {
            var client = GetBlobClient();
            var cloudBlobContainer = client.GetContainerReference(blobItem.ContainerReference);
            return cloudBlobContainer.GetBlobReference(blobItem.FileName);
        }

        public void DeleteBlob(BlobItem blobItem)
        {
            var client = GetBlobClient();
            var cloudBlobContainer = client.GetContainerReference(blobItem.ContainerReference);
            var blob = cloudBlobContainer.GetBlobReference(blobItem.FileName);
            blob.DeleteIfExists();
        }


        public void GetBlobStream(BlobItem blobItem, Stream target)
        {
            CloudBlob blob = GetBlob(blobItem);
            if (blob.HasBlob())
            {
                blob.DownloadToStream(target);
            }
        }

    }
    public class BlobContainerView
    {
        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }
        public string Uri { get; set; }
        public int BlobCount { get; set; }
    }
    public class BlobItem
    {

        public string ContainerReference { get; set; }

        public string FileName { get; set; }

        public string Content { get; set; }

        /// <summary>
        /// to use in stream mode
        /// </summary>
        public Stream Stream { get; set; }
    }
    public static class BlobExtensions
    {
        public static bool HasBlob(this CloudBlob blob)
        {
            try
            {
                blob.FetchAttributes();
                return true;
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
                {
                    return false;
                }
                throw;
            }
        }
    }
    public class ListBlobItemView
    {
        [Required]
        [Display(Name = "Container Name")]
        public string ContainerName { get; set; }
        public string Uri { get; set; }
        public string ParentUri { get; set; }
        public string ContainerUri { get; set; }
    }

    public static class ListBlobExtensions
    {
        public static ListBlobItemView ToModelView(this IListBlobItem item)
        {
            return new ListBlobItemView { Uri = item.Uri.ToString(), ParentUri = item.Parent.Uri.ToString(), ContainerUri = item.Container.Uri.ToString() };
        }


        public static IEnumerable<ListBlobItemView> ToModelView(this IEnumerable<IListBlobItem> items)
        {
            var blobitems = new List<ListBlobItemView>();
            items.ToList().ForEach(t =>
            {

                blobitems.Add(new ListBlobItemView
                {
                    ContainerName = t.Container.Name,
                    Uri = t.Uri.ToString(),
                    ParentUri = t.Parent.Uri.ToString(),
                    ContainerUri = t.Container.Uri.ToString()
                });
            });


            return blobitems;
        }
    }

No comments:

Post a Comment

Hey!
Let me know what you think?