Exploring C# with Azure Table Storage - Inserting and Retrieving records

By James Kenny
3 min read

Table of Contents

I was working on a project recently and decided to use Azure Table storage. It was a simple link short tool, I wanted to use for other projects.

To help with this I created a simple console app in C# and built in all the basic functions for using Azure Table Storage. The source code here.

This post will cover:

  • Get a Record from Table Storage
  • Get Records from Table Storage

I have a post from before on Setting up Azure Table Storage so I won't go over that instead lets get into it.

TableEntity

In Azure Table Storage records are known as TableEntity, so for my example I have a class called "LinkedEntity" which is a TabelEntity.

  public class LinkEntity : TableEntity
  {
    // Set up Partition and Row Key information
    public LinkEntity(string hostcode, string shortcode)
    {
      this.PartitionKey = hostcode;
      this.RowKey = shortcode;
    }


    public LinkEntity() { }

    public string Short_Code { get; set; }

    public string Raw_URL { get; set; }

  }

In my source code sample I created a new class called "TableQueries" to do the work

To insert our LinkEntity

public async Task<Boolean> InsertURL(string _hostCode, string sURL, string sShortCode)
{
    Boolean bSuccess = false;

    CloudStorageAccount storageAccount =
    new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(_accountName, _accountKey),
        true);
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

    CloudTable _linkTable = tableClient.GetTableReference("TABLENAME");

    _linkTable.CreateIfNotExists();

    // Create a new customer entity.
    LinkEntity _link = new LinkEntity(_hostCode, sShortCode);

    _link.Raw_URL = sURL;
    _link.Short_Code = sShortCode;

    // Create the TableOperation that inserts the customer entity.
    TableOperation insertOperation = TableOperation.InsertOrMerge(_link);

    try
    {

    await _linkTable.ExecuteAsync(insertOperation);

    bSuccess = true;
    }
    catch (Exception e)
    {
    bSuccess = false;
    }
    return bSuccess;
}

This code will call our TableClient and pass our credentials to authorise it. Then create a new LinkEntity with the data we want and insert it into the table storage link entity table.

When we insert the Link we use the hostcode to create the partition and the short code to set the row.

   public async Task<string> GetLink(string _hostCode, string sShortCode)
    {
      string sResult = "";

      CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(_accountName, _accountKey), true);
      CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

      CloudTable _linkTable = tableClient.GetTableReference("TABLENAME");

      _linkTable.CreateIfNotExists();

      // Create a retrieve operation that takes a customer entity.
      TableOperation retrieveOperation = TableOperation.Retrieve<LinkEntity>(_hostCode, sShortCode);

      // Execute the retrieve operation.
      TableResult retrievedResult = await _linkTable.ExecuteAsync(retrieveOperation);


      try
      {
        // Print the phone number of the result.
        if (retrievedResult.Result != null)
          sResult = (((LinkEntity)retrievedResult.Result).Raw_URL);
        else
          sResult = "";


      }
      catch (Exception e)
      {
        sResult = "";
      }

      return sResult;
    }

This code is the same as our Insert expect it doesn't insert the record but does a retrieve.

It will use a short code and check the partition for that record.

    public async Task<List<LinkSummary>> GetLinks(string _hostCode)
    {
      List<LinkSummary> _records = new List<LinkSummary>();

      CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(_accountName, _accountKey), true);
      CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

      CloudTable _linkTable = tableClient.GetTableReference("TABLENAME");

      _linkTable.CreateIfNotExists();

      // Construct the query operation for all customer entities where PartitionKey="Smith".
      TableQuery<LinkEntity> query = new TableQuery<LinkEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, _hostCode));

      // Print the fields for each customer.
      TableContinuationToken token = null;
      do
      {
        TableQuerySegment<LinkEntity> resultSegment = await _linkTable.ExecuteQuerySegmentedAsync(query, token);
        token = resultSegment.ContinuationToken;

        foreach (var entity in resultSegment.Results)
        {
          LinkSummary _summary = new LinkSummary
          {
            Raw_URL = entity.Raw_URL,
            Short_Code = entity.Short_Code
          };

          _records.Add(_summary);
        }
      } while (token != null);


      return _records;
    }
  }

This code does more, it takes our host code and searches for all records in that partition on the table storage,

It then breaks that down and brings it back as a List "LinkSummary" as I call it.

Lets get into the code a bit more shall we.

The common part of the code is this section


CloudStorageAccount storageAccount = new CloudStorageAccount(new 		Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(_accountName, 	   _accountKey), true);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

CloudTable _linkTable = tableClient.GetTableReference("TABLENAME");

_linkTable.CreateIfNotExists();

This code is taking our parameters and creating the table client. It checks each time if the table exists in Azure Storage, if it doesn't it creates it.

Next up I'll have some more deeper posts where I get into this more and look at the updating and other aspects of Table Storage.

Tagged in:

Azure Table Storage

Last Update: October 21, 2019

About the Author