Day 1 – The Basics of the Basics with Azure Table Storage

In this series we are looking at the basic mechanics of interacting with cloud-based Table Storage from an MVC 5 Application, using the Visual Studio 2013 IDE and Microsoft Azure infrastructure.

Before We Get Going…

Let’s not mince words here, the best way to develop in the cloud is with the best and most up-to-date toolset that we have available. You’re going to want to grab these prerequisites as a minimum foundation for following along in this series:

The Straight-Up Attack: Accessing Table Storage from Your Controller

Follow these quick steps to get started:

  • Create a new solution in Visual Studio using the ASP.NET Web Application project template

  • Right-click on your project in Solution Explorer, then Manage NuGet Packages and add “WindowsAzure.Storage” to your dependencies.
  • Alternatively, you can install the package from the Package Manager Console with the following command:
    Install-Package WindowsAzure.Storage

    The project is now prepped, so now we can add the needed code bits to start building our app. Let’s start by adding the following class to our project in the Models folder:

    public class KittehEntity : TableEntity
    {
    public KittehEntity(string kittehType, string kittehName)
    {

    <span class="kwrd">this</span>.PartitionKey = kittehType;
    <span class="kwrd">this</span>.RowKey = kittehName;
    

    }

    public KittehEntity() {}

    public string ImageUrl { get; set; }
    }

Next, replace the code in the HomeController with the code below. Note that you’ll need to add the namespace for the models to the usings at the top.

public ActionResult Index()
{
    var storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));

    var client = storageAccount.CreateCloudTableClient();

    var kittehTable = client.GetTableReference("PicturesOfKittehs");
    if (!kittehTable.Exists())
    {
        kittehTable.Create();

        var thrillerKitteh = new KittehEntity("FunnyKittehs", "ThrillerKitteh");
        thrillerKitteh.ImageUrl = "http://cdn.buzznet.com/assets/users16/crizz/default/funny-pictures-thriller-kitten-impresses--large-msg-121404159787.jpg";

        var pumpkinKitteh = new KittehEntity("FunnyKittehs", "PumpkinKitteh");
        pumpkinKitteh.ImageUrl = "http://rubmint.com/wp-content/plugins/wp-o-matic/cache/6cb1b_funny-pictures-colur-blind-kitteh-finded-yew-a-pumikin.jpg";

        var batchOperation = new TableBatchOperation();

        batchOperation.Insert(thrillerKitteh);
        batchOperation.Insert(pumpkinKitteh);
        kittehTable.ExecuteBatch(batchOperation);

    }

    var kittehQuery = new TableQuery<KittehEntity>()
        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "FunnyKittehs"));

    var kittehs = kittehTable.ExecuteQuery(kittehQuery).ToList();

    return View(kittehs);
}
Admittedly, this is a bit of a naive approach because we’re mixing concerns here and putting storage access and table seeding in a single controller method, but I want to highlight the premise here without adding too much cruft. Through the rest of the series we’ll extract a service to do the heavy lifting and move back towards best practices.

What we’re doing above is the following: * Reading the connection string from our web.config

  • Configuring the client
  • Getting a reference to a table
  • If the table doesn’t exist (it won’t, first time), we build a batch operation and seed it with some data
  • We fetch all records with a “FunnyKittehs” partition key
  • We pass the data to the view

    Now, replace the code in the Views\Home\Index.cshtml with the following:

    @model IEnumerable<YourNamespace.Models.KittehEntity>
    @{
        ViewBag.Title = "Home Page";
    }
    
    @foreach (var kitteh in Model)
    {
        <div class="jumbotron">
            <h4>@kitteh.RowKey</h4>
            <img src="@kitteh.ImageUrl" />
        </div>
    }
    Note that you’ll need to update the namespace to match your project’s.

    Finally, add a connection string to the AppSettings section of your web.config. This will tell our app to use the local storage emulator provided by the SDK.

    <appSettings>
      <!-- other settings... -->
      <add key="StorageConnectionString" value="UseDevelopmentStorage=true;" />
    </appSettings>

    Finally, run the app! You should see a couple of adorable kittehs in your browser, rendered in a razor view, with data populated by the MVC controller with entities loaded from Azure Storage Tables.

    Next Steps

    In this post we injected a few entities into our table using a seed method, but what about adding new entities from the UI? In the next article, we’ll beef up the views and controller to allow users to add new documents to our storage account.

    (Psst! If you’re just getting started with MVC and want to get your hands real dirty, check out my book on Bootstrap and the MVC Framework).