Q78: How to create a table using a simple C# Console application?

Open Visual Studio and create a C# Console application from the standard template.

new project dialog

By default, the created project will not have a reference to the storage library, but we can add that easily using the NuGet package manager. Right-click on the project and select 'Manage NuGet Packages' from the context menu. This will load up the Package Manager UI. Select the 'Online' tab from the Package Manager dialog, and search for 'Azure Storage'. Select the Windows Azure Storage package and click 'Install'.

manage Nuget dialog

After adding references of the Windows Azure Storage Client Library, you need to add the following namespaces. Open the program.cs file and add the following statements to the top of the file.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;

class Program
{
	static void Main(string[] args)
	{
		//Add the following to the Main method:

try
{
	CloudStorageAccount account = CloudStorageAccount.Parse(
			CloudConfigurationManager.GetSetting(“StorageConnectionString”));
    
	CloudTableClient client = account.CreateCloudTableClient();

	CloudTable table = client.GetTableReference(“items”);

	table.CreateIfNotExists();
	Console.WriteLine(table.Uri.ToString());
}

catch (Exception ex)
{
    Console.WriteLine(ex);
}
	Console.WriteLine(“Done... press a key to end.”);
	Console.ReadKey();
}



Explanation of code: Create an instance of CloudStorageAccount. The CloudStorageAccount object is the root object we use to access to any of the storage sub systems: Blobs, Queues and Tables.

CloudStorageAccount account = CloudStorageAccount.Parse(
			CloudConfigurationManager.GetSetting(“StorageConnectionString”));


After creating an object of the storage account, we need to create an instance of the CloudTableClient. We create it as follows:

 
CloudTableClient tableClient = account.CreateCloudTableClient();


The last step in creating the Azure Table is to make a reference of the CloudTable and create it if it does not exist. ‘Items’ is the name of the table that we intend to create here.

CloudTable table = tableClient.GetTableReference("items");
table.CreateIfNotExists();


The code creates a CloudTable object using the GetTableReference method of the CloudTableClient object. The statement table.CreateIfNotExists(), will make a call to the Table service REST API and, if a table named 'items' does not exist within the storage account it will be created. Remember that the Table service is a REST based API. We have created a table, and next, we will add entities to it.