Using Azure Table Storage in ASP.NET Core Applications

Azure Table Storage is a NoSQL database implementation for storing various types of data that might be useful to an ASP.NET Core Application. To use the Table Storage service of Azure Storage, at first a storage account needs to be set up.

AzureStorage1.png

Figure 1: Accessing the storage account in Azure Portal

 

Once the Storage Account has been set up, its details can be accessed from the Azure Portal as shown in the screenshots presented in the previous as well as this page. In this scenario, we have set up a storage account named pretzelonline. Right side of the blade shows the four services available from the Azure storage account – Blobs, Files, Tables, and Queues, and for our purpose of storing and retrieving Session State data, we are going to use Tables or “Table Storage” service.

AzureStorage2.png

Figure 2: Different Types of Azure Storage Services

Data is stored in Azure Storage tables as Entities. So, to push any data there from the C# backend code, we first need to have an Entity class. For that purpose, in this scenario, we are creating the following EmployeeSessionEntity class. PartitionKey and Rowkey are mandatory fields for every entity that gets stored in an Azure Storage Table, because they together help identify a record.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table; 
namespace PretzelInternational.Model.AzureTableStorage
{
    public class EmployeeSessionEntity : TableEntity
    {
        public EmployeeSessionEntity()
        {
        } 
        public EmployeeSessionEntity(int id, string name, double sal)
        {
            Id = id;
            Name = name;
            Salaray = sal; 
            PartitionKey = id.ToString();
            RowKey = name;
        } 
        public int Id { get; set; }
        public string Name { get; set; }
        public double  Salaray { get; set; }
    }
}

 

Now, to store some actual EmployeeSessionEntity object into the Azure Storage, following lines of code need to be used inside any Controller class. The ConnectionString that CloudStorageAccount.Parse() uses as parameter can be found from the “access keys” section of storage account details in the Azure Portal (Refer to Figure 3) . Needless to say, we can always keep this ConnectionString inside appsettings.json file as well and just read from there using the json key.

//Pushing an instance of Employee Entity to Azure Table Storage

CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=pretzelonline;AccountKey=qZC7nBhnetRidrxcaRKAl06Spr+Ncjs9YGhAVtWhSAGKX19IpLXWEYX6T+0B/96vTSYN+6/BjwqvXJ8DOjV+zA==;EndpointSuffix=core.windows.net");

CloudTableClient client = storageAccount.CreateCloudTableClient();

CloudTable table = client.GetTableReference("employee");

table.CreateIfNotExistsAsync();

var emp = new EmployeeSessionEntity(1, "BillG", 123456.33);

TableOperation insertOp = TableOperation.Insert(emp);

table.ExecuteAsync(insertOp);

 

Now, with the data moved there, we next need to retrieve the data to make our session related decisions in the Controllers’ code. In this sample scenario, we have stored the salary information of an employee named “BillG” with id of “1”. So, in the following scenario, we can then read the EmployeeSessionEntity back inside About action method. Once the 

public IActionResult About()

{

            ViewData["Message"] = "Your application description page.";

            EmployeeSessionEntity empE = RetrieveEmployee();

                 if(empE != null)

            return View();

                 else

                        return View(“NoAccess”);

}

private EmployeeSessionEntity RetrieveEmployee()

{

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=pretzelonline;AccountKey=qZC7nBhnetRidrxcaRKAl06Spr+Ncjs9YGhAVtWhSAGKX19IpLXWEYX6T+0B/96vTSYN+6/BjwqvXJ8DOjV+zA==;EndpointSuffix=core.windows.net");

            CloudTableClient client = storageAccount.CreateCloudTableClient();

            CloudTable table = client.GetTableReference("employee");

            bool b = table.ExistsAsync().Result;

            TableOperation retOp = TableOperation.Retrieve("1", "BillG");

            TableResult tr = table.ExecuteAsync(retOp).Result;

            return tr.Result as EmployeeSessionEntity;

}

 

AzureStorage3.png

Figure 3: Fetching the Azure Storage Account’s Connection String from Azure Portal

Comparison against against Redis Cache for Data Storage

Before comparing the two main, let us look at what the some main details of both the services from Azure.

  • Table Storage is a durable, key/value store. As such, content doesn't expire. You'll be responsible for clearing out data.
  • Table Storage scales to 500TB.
  • Redis is scalable horizontally across multiple nodes (or, scalable via Redis Service). In contrast, Table Storage will provide up to 2,000 transactions / sec on a partition, 20,000 transactions / sec across the storage account, and to scale beyond, you'd need to utilize multiple storage accounts.
  • Table Storage will have a significantly lower cost footprint than a VM or Redis service.
  • Both Table Storage and Redis Cache are accessible via an endpoint, with many language-specific SDK wrappers around the API's.

Following are the pricing details for Redis Cache vs Azure Table Storage for a standard service in North Europe for 1 GB. As can be clearly seen, Azure Table Storage costs are significantly cheaper. However, please also note that there’s a per transaction component to its pricing, which means if the Application is sufficiently Transaction-Heavy, it’s total cost might near or even cross the cost of a Redis Cache service. 

AzureStorage4.png

Figure 4: Pricing Details of Redis Cache

AzureStorage5.png

Figure 5: Pricing Details of SQL Storage

Overall, it can be concluded that Redis Cache makes way for a much faster performance as compared against the Azure Storage service, however also at a significantly higher cost footprint when the application is not massively transaction-heavy. Therefore, for a large enterprise application with possibly 100s of thousands of concurrent users, where turnaround time and number of transactions must be prioritized, Redis Cache is the recommended option. However, for applications with much smaller need of Transactions and Performance, Azure Table Storage remains the perfect solution! 

  • Erstellt am .
Copyright by Orange Networks GmbH