Create Cloud table and insert data in azure storage table

Working with azure cloud table will be different experience for you, especially if you are a sql developer; storing data in sql table is very different than storing data in azure cloud table.

Here we learn about azure Cosmos table, creating cloud table and inserting data, we need to add the namespace reference of Microsoft.Azure.Cosmos.Table.CloudStorageAccount

Creating a table for inserting customer data, so name it like "customerTable". (Assuming, you have azure storage connection string in your json config file).

using Microsoft.WindowsAzure.Storage;
using CloudStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount;

public async Task<IActionResult> OnPostCreateNewTable()
{
	string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
	
	var storageAccount = CloudStorageAccount.Parse(_storageConnection);
	
	var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
	
	var table = tableClient.GetTableReference("customerTable");
	
	await table.CreateIfNotExistsAsync();
	return Redirect("aztable");
}

We create a simple customer class (with three property firstname, lastname and mobile.. just to keep it simple), to work with azure cloud table, each class must be inherited from TableEntity base class, which comes under namespace Microsoft.Azure.Cosmos.Table, you may need to install the package from numget package manager.

Note: in this example i have used the reference of cosmos table api, which comes under Microsoft.Azure.Cosmos.Table namespace, things are working fine. But, instead of using cosmos table api, we should use the reference of Microsoft.WindowsAzure.Storage.Table namespace while working with storage table, where we have all same functionalities and some additional function while working with complex object in azure storage table.

Create Customer TableEntity

When we inherit from TableEntity, there will be two default property RowKey and PartitionKey, based on this two keys value, we can indentify any unique record in that table.

RowKey has to be unique for each record, you can use GUID value, PartitionKey is like group name of partition name.

using Microsoft.Azure.Cosmos.Table;

namespace WebTrainingRoom
{
    public class Customer : TableEntity
    {
        public Customer()
        { 
        }
                
        //new string  RowKey { get; set; }
        //new string PartitionKey { get; set; }
  
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Mobile { get; set; }              
    }
}

Add one customer data into the table we have created in above code.

Notice, how RowKey and PartitionKey value has been set, RowKey can be like Guid.NewGuid().ToString(), and PartitionKey key value should be some meaningful business terminology related name

public async Task<IActionResult> AddCustomer(Customer cObj)
{
string _message = "Added new customer";
string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
	
var storageAccount = CloudStorageAccount.Parse(_storageConnection);
	
var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
	
try
{
	var customerTable = tableClient.GetTableReference("customerTable");
	string _uniqueRowKey= Guid.NewGuid().ToString();
	Customer _customer = new Customer()
	{
		RowKey = _uniqueRowKey,
		PartitionKey = "thisispartitionkey1234567890keyokay",
		Firstname = cObj.CustomerFirstName,
		Lastname = cObj.CustomerLastName,
		Mobile = cObj.Mobile                   
	};
	   
	var queryInsert = TableOperation.Insert(_customer);
	// just to check what would be the value of TableResult
	TableResult _result =   await customerTable.ExecuteAsync(queryInsert);
}
catch (StorageException e)
{
	_message = e.ToString();
}            
catch (RequestFailedException ex)
{
	_message = ex.ToString();
}           
	
	return Redirect("azTabCustomer");
}

Now if you check the customer table, table is created and data has been added.

Retrieve data from azure cloud table in c#

Instead of checking data in cloud table, let’s read the data from same table in c# code, that way you will also learn how to retrieve data from cloud table.

Create a TableQuery object then, get the customer table reference, and call customerTable.ExecuteQuery(_query)

async Task<List<Customer>> GetAllCustomers()
{
	List<Customer> customerList = new List<Customer>();
	string _message = "Retrieve data from customer table";

	string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
	var storageAccount = CloudStorageAccount.Parse(_storageConnection);

	try
	{
		var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
		var customerTable = tableClient.GetTableReference("custTable");
						
		TableQuery<Customer> _query = new TableQuery<Customer>();
		IEnumerable<Customer> _result= customerTable.ExecuteQuery(_query);
	   
       // customerList = _result.ToList();
	   // or below

		Customer _cust;
		foreach (Customer _c in _result)
		{
			_cust = new Customer();
			_cust.Firstname= _c.Firstname;
			_cust.Lastname = _c.Lastname;
			_cust.Mobile = _c.Mobile;
			_cust.RowKey = _c.RowKey;
			_cust.PartitionKey = _c.PartitionKey;
			customerList.Add(_cust);
		}
	}	
	catch (RequestFailedException ex)
	{
		_message = ex.ToString();
	}
	return await Task.FromResult(customerList);
}

Now call the above method on page load method OnGet(), then set the values to collection property, which can be accessed from razor page

[BindProperty]
public List<Customer> AllCustomers { get; set; }

public void OnGet()
{	
	AllCustomers = GetAllCustomers().Result;
}

Now you can simply loop through the "AllCustomers" property in your razor page, and retrieve each customer value

 
Azure Cloud Tutorial
learn azure cloud development

Let's learn how to use Azure Cloud Storage system from Ap.net core c# application.

Data Analysis
learn Artificial Intelligence
Add / Insert Data to Azure Cloud Table
Learn Azure Cloud Development