Skip to Content
  • Development

A Simple Guide to Azure Table Storage in C#

coding on two screens and glasses image description

This week I had to store a small amount of data, far too little to be worth creating a whole database, for a development project. To save a bit of money and hassle, I decided to get my hands dirty with Azure’s Table Storage.

After a bit of searching, I had come up with a couple of guides to help work out how to read and write to the table, but nothing clearly laid out and explained what I was doing and why, so this is a simple step by step guide to Azure table storage.

For this guide we will use the example of storing an email and username, making sure that usernames aren’t repeated.

Step 1: Download Azure Storage Explorer 6

This is a really useful tool to manage your storage. You can get it here.

Add your storage account with the name of the storage account and the access key (which can be found in the azure portal). Once you have done that you can create the table you want to use using Storage Explorer. Note: There are a few rules associated with naming your table, so keep the name as simple as possible

Step 2: Install Nuget Package

Whether you want to create a new project or just a new class in your existing project, open up your package manager console and run “Install-Package WindowsAzure.Storage”. This will give you all the providers to access the blobs and tables in your storage account.

Step 3: Authenticate to your storage account

To authenticate to your storage you just need the same account details you got for the Storage Explorer, your account name and the account access key.

Create a new class to manage your storage methods. Then add this method to it.

private static CloudTable AuthTable()
        {
            string accountName = "YOUR ACCOUNT NAME HERE";
            string accountKey = "YOUR ACCOUNT KEY HERE";
            try
            {
                StorageCredentials creds = new StorageCredentials(accountName, accountKey);
                CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);

                CloudTableClient client = account.CreateCloudTableClient();

                CloudTable table = client.GetTableReference("TARGET TABLE NAME");

                return table;
            }
            catch
            {
                return null;
            }
        }

Step 4: Create your table entity

In Azure Tables an entity is equivalent to a record. Each one requires a rowkey and a partition key. The row key must be unique to the entity, however the partition key does not, and allows an easy way to sort the table.

In addition to this, any additional attributes can be added as extra fields when defining the entity class

For this example, we will be making the username the row key, and adding the email as an extra attribute.

public class UsernameEntity : TableEntity
    {
        public UsernameEntity() { }

        public string Email { get; set; }
    }

Step 5: Table Operations

Table operations are what allow you to define your query type before executing it. For this example, we will be using Insert and Retrieve.

Step 5a: Inserting a new entity

Creating a new entity is really easy. Simply instantiate your entity and cast it into your Table Operation. For this example, I have wrapped it in a method that returns the outcome of the insert as a Boolean.

private static bool CreateEntity(string email, string username, CloudTable table)
        {
            var newEntity = new UsernameEntity()
            {
                PartitionKey = "Username",
                RowKey = username,
                Email = email
            };

            TableOperation insert = TableOperation.Insert(newEntity);
            try
            {

                table.Execute(insert);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

Step 5b: Retrieving an entity

Retrieving a specific entity is as easy as knowing the row key and partition key. Create a new Table operation and pass in the values and then evaluate the result Similar to the insert, I have wrapped this in a method to return whether the username already exists as a Boolean

private static bool DoesUsernameExist(string username, CloudTable table)
        {
            TableOperation entity = TableOperation.Retrieve("Username", username);

            var result = table.Execute(entity);

            if (result.Result != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

Step 6: Put it all together

Once you have all these methods ready to go, just put them all together in a publicly accessible method to be accessed anywhere on your project.

public static string ValidateUsername(string username, string email)
        {
            var table = AuthTable();

            var exists = DoesUsernameExist(username, table);

            if (exists)
            {
                return "Username Taken";
            }

            var success = CreateEntity(email, username, table);

            if (success)
            {
                return "Username Registered";
            }
            else
            {
                return "Error";
            }

        }

 

Hopefully, this basic example will set you on the right path to mastering the azure table storage providers.

 

***

Mudbath is a 40+ person digital product agency based in Newcastle, NSW. We research, design and develop products for industry leaders.

Looking for a new challenge in your Development career? View open roles.