Alessandro Del Sole's Blog

/* A programming space about Microsoft® .NET® */
posts - 159, comments - 0, trackbacks - 0

My Links

News

Your host

This is me! This space is about Microsoft® .NET® and Microsoft® Visual Basic development. Enjoy! :-)

These postings are provided 'AS IS' for entertainment purposes only with absolutely no warranty expressed or implied and confer no rights.

Microsoft MVP

My MVP Profile

I'm a VB!

Watch my interview in Seattle

My new book on VB 2015!

Pre-order VB 2015 Unleashed Pre-order my new book "Visual Basic 2015 Unleashed". Click for more info!

My new book on LightSwitch!

Visual Studio LightSwitch Unleashed My book "Visual Studio LightSwitch Unleashed" is available. Click the cover!

Your visits

Follow me on Twitter!

CodePlex download Download my open-source projects from CodePlex!

Article Categories

Archives

Post Categories

.NET Framework

Blogroll

Help Authoring

Microsoft & MSDN

Setup & Deployment

Visual Basic 2005/2008/2010

Windows Azure: interacting in Visual Basic code with the Blob Storage - part one

With this blog post I would like to start a series about how we can interact from Visual Basic 2010 with the on-line Cloud Storage offered by Windows Azure. My goal is not discussing what Windows Azure is and how the storage works (except for some necessary hints), since you can find more detailed documentation across the Internet; instead I will show you how to write code for managing containers and blobs in your storage account.

My assumptions about you

I assume that you already have an account on Windows Azure and that you already created your storage account. If you need help about that, have a look at the MSDN Library.

The real goal

The actual goal of this series is showing how you can store and read your files to and from the Blob Storage. This is discussed using the new APIs available in the Windows Azure SDK 1.4 that you definitely need to download and install. Finally, the approach to the discussion is something that works on the client side. You usually find examples about accessing the cloud storage from Silverlight, but you know that there is not only the Web so you will see something different.

Where we are now and where we are heading to

A few months ago I published a new project onto CodePlex, called Azure Blob Studio 2011, which is available as both a WPF client and an extension for Visual Studio 2010. This tool allows interacting with your storage to store and download files, organized in folders. Inside that project I created a class that exposes most of the objects available in the new APIs, in a way that is a little bit better in my opinion. So we now begin writing that class called BlobService in order to understand how to write managed code against the storage. The series is made of 4 blog posts. If you can't wait or if you are just curious, you can download the code from CodePlex.

Cloud Storage overview

When you activate a Windows Azure subscription, Microsoft provides an online storage where you can store your data and that is called Cloud Storage. Basically the online storage is made of 4 services:

  • Blob: in this space you can store binary data such as images, videos, documents; that is, files
  • Table: here you can store tabular data, according to the well-known "columns/rows" logic. This is for unstructured data, meaning that tables do not have relationships. On the other side, this space provides a high scalability
  • Queue: this service allows exchanging messages between roles (Web and Worker) that are the main parts of a Web application for Windows Azure
  • Drive: come il nome lascia intendere, si tratta di hard disk virtuali formattati in NTFS che permettono caricamento/lettura di informazioni da parte delle applicazioni Web che girano su Azure

What we are focusing in this series is the Blob Storage for a number of reasons, and the first one is that it is the space that makes more sense in client applications. If you are wondering why, here's the example: I have my Word and PDF documents or other documents that I want to place in my cloud storage so that I can reach them from a simple WPF or Windows Forms client (especially if I do not have any possibility of deploying a Silverlight application to a Web site).

Code interaction

The Cloud Storage can be reached by developers in two different ways:

  • REST approach, which means sending http requests
  • managed APIs, which means using .NET libraries provided by the Windows Azure SDK 1.4

We are going to use the second way in Visual Studio 2010, so let's download and install the SDK. Once installed, it is time to lcate a library called Microsoft.WindowsAzure.StorageClient.dll within the folder C:\Program Files\Windows Azure SDK\v1.4\Ref. This is the library that we are going to reference in moments.

Fundamentals

Sorry, I will explain these in code.. more fun :-)

Let's start: CloudStorageAccount & CloudBlobClient

Start by opening Visual Studio 2010 to create a new Class Library project with Visual Basic 2010. Rename the main class into BlobService. When ready, add a reference to the Microsoft.WindowsAzure.StorageClient.dll assembly. Now, it is important to consider two things:

  • how to obtain access credentials for the online storage
  • how to obtain a managed reference to the storage

The CloudStorageAccount class, from the Microsoft.WindowsAzure namespace, is our entry point to the storage and allows specifying access credentials. As you know, these are made of the Account Name/Shared Key pair. The first element was defined when creating the storage, whereas the second one is generated by Azure and you can get it within the developer portal. A managed reference to the storage is instead represented by the CloudBlobClient class.

So at the class level the first thing to do is adding two declarations as follows:

Public Class BlobService

Private AccountInfo As CloudStorageAccount
Private blobStorage As CloudBlobClient

The CloudStorageAccount class provides several methods for managing credentials. This class also allows setting the local development storage as the target, by assigning the DevelopmentStorageAccount property. If instead you want to access the online storage, you can generally use the FromConfigurationSettings method, in case you supplied your credentials in the configuration file, or the Parse (or TryParse) method which instead analyzes a string containing credentials and that transform such a string into an instance of CloudStorageAccount.

Since our class will be a simplified but unique way of accessing the storage, we can distinguish the two ways of supplying credentials via two constructor overloads; we in fact assume that, for privacy reasons, access credentials to the storage will not be supplied in the configuration file so they will be hard-coded:

    Public Sub New(ByVal accountName As String, ByVal sharedKey As String)

        If String.IsNullOrEmpty(accountName) Or String.IsNullOrEmpty(sharedKey) Then
Throw New ArgumentNullException()
End If

Me.AccountInfo = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + accountName + ";AccountKey=" + sharedKey)
blobStorage = AccountInfo.CreateCloudBlobClient()
End Sub

Public Sub New()
'Use the dev account
Me.AccountInfo = CloudStorageAccount.DevelopmentStorageAccount
blobStorage = AccountInfo.CreateCloudBlobClient()
End Sub

As you can see the string containing credentials must respect some criteria, such as the indication of the end point protocol and the pair AccountName/AccountKey. In case the user wanted to use just the local development storage, the instance is simply assigned with DevelopmentStorageAccount.

Once we have the account instance we can invoke the CreateCloudBlobClient method, which returns an object of type CloudBlobClient, which represents a managed reference to the storage (either online or local).

This is very important because the CloudBlobClient object offers all the necessary members required to access containers and blobs. At this point you might be wondering how you can catch invalid credentials.

The answer is (quite) simple: the credentials check is not automatic on the instace of CloudStorageAccount, so in theory a user could enter invalid credentails. The trick is invoking any method (such as those able of listing containers): if the method invocation returns a StorageClientException, then it means that credentials are invalid.

This kind of check will be implemented later in the blog post series; it cannot be done now because first you need to understand how you can work with containers.

Working with containers

You can compare the concept of Container in the cloud to the concept of folder on disk. One container can contain blobs and other containers.The CloudBlobClient class provides several methods for working with containers, but there are some common steps:

  1. we try to get a reference to the desired container via the GetContainerReference method
  2. if it does not exist, we can create the container and get a reference at this point
  3. if it exists, we just get a reference

Getting a manged reference to a container is required to work later with blobs; such a reference is represented by an instance of the CloudBlobContainer class. Just to make things easier, let's start by retrieving the list of containers available on the storage. Let's write some code that invokes the instance ListContainers method from the CloubBlobClient class:

    Public Overridable Function ListContainers() As IEnumerable(Of CloudBlobContainer)
Try
Dim result = blobStorage.ListContainers
Return result

Catch ex As Exception
Throw
End Try
End Function

Basically this method works as a wrapper but it was necessary in a "service" class like the current one. ListContainers returns IEnumerable(Of CloubBlobContainer) and each element in this set represents a container with its properties, as we are going to explain better in moments. For now, let's see how a container can be deleted:

    Public Sub DeleteContainer(ByVal ContainerName As String)
Dim container = blobStorage.GetContainerReference(ContainerName)
container.Delete()
End Sub

The code simply gets the container reference and invokes the Delete instance method (of course it would be a good practice checking that the reference is not null). Now let's see how it is possible to create a new container. Consider the following method:

    Public Overridable Sub CreateContainer(ByVal ContainerName As String, ByVal IsPublic As Boolean)

Try
Dim container = blobStorage.GetContainerReference(ContainerName)
container.CreateIfNotExist()

If IsPublic = True Then
container.SetPermissions(New BlobContainerPermissions With {.PublicAccess = BlobContainerPublicAccessType.Container})
Else
container.SetPermissions(New BlobContainerPermissions With {.PublicAccess = BlobContainerPublicAccessType.Off})

End If

Catch ex As StorageServerException
Throw New StorageServerException
Catch ex As Exception
Throw New Exception(ex.InnerException.Message)
End Try

End Sub

The code:

  1. attempts to get a reference to the container 
  2. if the container does not exist, it is created (CreateIfNotExists)
  3. sets access permissions to the container

With the term "permissions" we mean the possibility of making the container's content public or private; the latter means that the content is available only to the owner of the account. To accomplish this we invoke the SetPermissions method from the CloudBlobContainer class that receives as an argument an instance of the BlobContainerPermissions class. This exposes a property called PublicAccess, which is assigned with one value from the BlobContainerPublicAccess enumeration, such as Off (private) or Container (public). At this point the container is created inside the storage.

If we need to get a reference to such a container later, we just need this:

Dim container = blobStorage.GetContainerReference(ContainerName)

Now it should be easier to understand the way for testing if the supplied credentials are valid: you can just invoke ListContainer from within the constructor, after getting an instance of CloudStorageAccount, and check that if it returns a StorageClientException.

Remember: you pay for accessing the storage based on transactions (other than on space). Each time you create, delete, or access a container, these are all transactions.

End of part one

In this first blog post you saw how to access the storage and how to manage containers. In next post you will see something more interesting, such as managing blobs asynchronously.

Alessandro

Print | posted on sabato 26 marzo 2011 21:39 | Filed Under [ Visual Studio 2010 Visual Basic Windows Azure ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 1 and 6 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET