Q77. How to create a table in Azure Storage?

Creating a table consists of three basic steps.

Step1: Retrieving the storage account from the connection string
Step2: Creating a table client from the CloudTableClient class
Step3: And finally Creating the table.

The CloudStorageAccount class is the 'gateway' to the blob, table storage and queue APIs.

Use the following code to create the table.

//Retrieving the storage account from the connection string 
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
				CloudConfigurationManager.GetSetting(“StorageConnectionString”));


Explanation
We have used the CloudStorageAccount type to represent the Storage Account information and the CloudConfigurationManager type to retrieve the storage connection string from the Windows Azure service configuration file.

//Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();


Explanation:
Once we obtain a reference to CloudStorageAccount, we need to create an instance of CloudTableClient.

//From the table client, create the table
CloudTable customers = tableClient.GetTableReference(“Customers”);
customers.CreateIfNotExists();
We can use CreateCloudTableClient() method to get a reference of the CloudTableClient class. The last step in creating an Azure Table is to take a reference of CloudTable and create it if it does not exist. 'Customers' is name of the table we intend to create here, and we can call the CreateIfNotExist method to create the table.

How to retrieve the storage account information in the web.config file or app.config file


If the application is running in a Windows Azure Web Site and not as a Cloud Service then we have to use the web.config file to obtain the storage account information.

CloudStorageAccount storageAccount = CloudStorageAccount.Parse
(ConfigurationManager.ConnectionStrings[“StorageConnectionString”].ConnectionString);

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable customers = tableClient.GetTableReference(“Customers”);
customers.CreateIfNotExists();


Creating a table in the storage emulator


The following code creates a table in the storage emulator. You can use the statement CloudStorageAccount.DevelopmentStorageAccount to return a CloudStorageAccount object that references the storage emulator account. The property DevelopmentStorageAccount of the CloudStorageAccount class is useful when we are writing code that uses the Storage Emulator only.

CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable customers = tableClient.GetTableReference(“Customers”);
customers.CreateIfNotExists();