Azure Simplified Part 3: Using Azure Blob Storage

We’ll take a look at Azure’s Blob storage today. A Blob can store either text for binary data. Within your storage account, you can have multiple containers and each container can have multiple blobs. There are two type of blobs: block blobs optimized for streaming and page blobs optimized for read/write. Let’s make a sample application,

1. Open up VisualStudio 2008 (run as Administrator) and create a new ‘Cloud Service’ project,

image

2. Create an ASP.NET WebRole,

image

3. Add a new data connection string. To do this, go to CloudService1 –> Roles –> WebRole1 –> right click Properties –> Settings –> Add Setting. Type in ‘DataConnectionString’ and change the Type column to ‘Connection String’. Then click on the ‘…’ at the far right and choose ‘Use development storage’.

image 

4. Nasty hack alert! Add the following code to the WebRole.cs’s OnStart method,

public override bool OnStart() {
    DiagnosticMonitor.Start("DiagnosticsConnectionString");

    // For information on handling configuration changes
    // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
    RoleEnvironment.Changing += RoleEnvironmentChanging;

    // This code sets up a handler to update CloudStorageAccount instances when their corresponding
    // configuration settings change in the service configuration file.
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => {
        // Provide the configSetter with the initial value
        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

        RoleEnvironment.Changed += (sender, arg) => {
            if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
                .Any((change) => (change.ConfigurationSettingName == configName))) {
                    // The corresponding configuration setting has changed, propagate the value
                    if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName))) {
                        RoleEnvironment.RequestRecycle();
                    }
            }
        };
    });
    return base.OnStart();
}
 

5. Add the following HTML to the Default.aspx file,

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label id="Label1" Text="Insert this text as blob:" runat="server" />
            <asp:TextBox id="TextBox1" runat="server" />   
            <asp:Button ID="Button1" Text="Insert text blob" runat="server" />
            <br />
            <br />
            <asp:Label id="Label2" Text="Insert file as binary data:" runat="server" />
            <asp:FileUpload ID="fileUploadControl" runat="server" />
            <asp:Button ID="Button2" Text="Insert binary data" runat="server" />
            <br />
            <br />
            <asp:Label id="Label3" Text="Delete this blob (uri):" runat="server" />
            <asp:TextBox id="TextBox2" runat="server" />   
            <asp:Button ID="Button3" Text="Delete blob" runat="server" />
            <br />
            <br />
            <asp:Repeater id="Repeater1" runat="server">
                <HeaderTemplate>
                    <table border="1">
                        <tr><td><b>Blob Uri</b></td></tr>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                      <td> <asp:HyperLink runat="server" Text="<%# Container.DataItem %>" NavigateUrl="<%# Container.DataItem %>" /> </td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </div>    
    </form>
</body>

 

6. Add the following code to the Default.aspx.cs file,

public partial class _Default : System.Web.UI.Page {
    // Manage account information
    CloudStorageAccount storageAccount = null;

    // Blob container
    CloudBlobContainer blobContainer = null;

    // Blob client
    CloudBlobClient blobClient = null;

    protected void Page_Load(object sender, EventArgs e) {
        // Init the contexts
        this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        this.blobClient = storageAccount.CreateCloudBlobClient();

        // Get and create the container
        this.blobContainer = this.blobClient.GetContainerReference("publicfiles");
        this.blobContainer.CreateIfNotExist();

        // Hook up the buttons
        this.Button1.Click += new EventHandler(InsertTextBlob);
        this.Button2.Click += new EventHandler(InsertBinaryBlob);
        this.Button3.Click += new EventHandler(DeleteBlob);

        this.DisplayBlobs();
    }

    // Delete a blob using the uri as key
    private void DeleteBlob(object sender, EventArgs e)
    {
        var blob = this.blobContainer.GetBlobReference(this.TextBox2.Text);
        blob.DeleteIfExists();

        this.DisplayBlobs();
    }

    // Insert a blob of text
    private void InsertTextBlob(object sender, EventArgs e)
    {
        CloudBlob blob = this.blobContainer.GetBlobReference(Guid.NewGuid().ToString());
        blob.UploadText(this.TextBox1.Text);

        this.DisplayBlobs();
    }

    // Insert binary data
    private void InsertBinaryBlob(object sender, EventArgs e) {

        // Adding the extension helps the browser use the right application to open the blob
        string extension = System.IO.Path.GetExtension(fileUploadControl.FileName);
        CloudBlob blob = this.blobContainer.GetBlobReference(Guid.NewGuid().ToString() + extension);
        blob.UploadFromStream(fileUploadControl.FileContent);

        this.DisplayBlobs();
    }

    // Display all blobs in the current container
    private void DisplayBlobs() {
        // Get a list of the blobs
        var blobs = this.blobContainer.ListBlobs();
        var blobList = new List<string>();

        foreach (var blob in blobs) {
            var cloudBlob = this.blobContainer.GetBlobReference(blob.Uri.ToString());
            cloudBlob.FetchAttributes();

            blobList.Add(blob.Uri.ToString());
        }

        // Bind to the repeater
        this.Repeater1.DataSource = blobList;
        this.Repeater1.DataBind();
    }
}

The code is simple, create a BlobClient and a container, and then upload data using UploadText or UploadFromStream (there are other methods like UploadFile too). The blobs are identified using the unique Uri assigned to them.


7. Running the app you should get,

image

Clicking on the URIs will open the text blob in the browser, and try to download the binary data.

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Azure Simplified Part 3: Using Azure Blob Storage

  1. Pingback: Azure Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: