Step 1: Create Azure DB
i) Login to Azure Portal
ii) Select Azure Cosmos DB
iii) Click Add
iv) Select subscription and resource group
v) Give name for DB in Account name
vi) Select Azure Table in API dropdown
vii) Select your desired Location
viii) Click on Review + Create
ix) create
x) It will take some time to create DB afer successful creation it will display your deployment is successful message
xi) select created db and select Quick start option
xii) now in quick start you can able to see connection strings which will be used in your project to communicate with Azure db
Step 2: Create new project and add below nuget packages
i)Microsoft.Azure.Cosmos.Table
ii)Microsoft.Extensions.Configuration
iii)Microsoft.Extensions.Configuration.Abstractions
iv)Microsoft.Extensions.Configuration.Binder
v)Microsoft.Extensions.Configuration.FileExtensions
vi)Microsoft.Extensions.Configuration.Json
Step 3: Add Json file
Add Settings.json file to the project
{
"StorageConnectionString": "Connection string available in Azure db",
"TableName": "give your desired table name"
}
Go to .csproj and add below tag
<ItemGroup>
<None Update="Settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Step 4 : Read Settings.json file
Add .cs file to the project and name it as AppSettings and add below code
using Microsoft.Extensions.Configuration;
public class AppSettings
{
public string StorageConnectionString { get; set; }
public string TableName { get; set; }
public static AppSettings LoadAppSettings()
{
IConfigurationRoot configRoot = new ConfigurationBuilder()
.AddJsonFile("Settings.json")
.Build();
AppSettings appSettings = configRoot.Get<AppSettings>();
return appSettings;
}
}
Step 5: Azure table creation code
Add new .cs file to project and name it as AzureTableCreation and add below code in it
using Microsoft.Azure.Cosmos.Table;
public class AzureTableCreation
{
public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)
{
CloudStorageAccount storageAccount;
try
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
}
catch (System.Exception)
{
throw;
}
return storageAccount;
}
public static CloudTable CreateTable(string tableName)
{
string storageConnectionString = AppSettings.LoadAppSettings().StorageConnectionString;
// Retrieve storage account information from connection string.
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString);
// Create a table client for interacting with the table service
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
// Create a table client for interacting with the table service
CloudTable table = tableClient.GetTableReference(tableName);
if (table.CreateIfNotExists())
{
}
return table;
}
}
Step 6 : Create .cs file with name TenantSettingsand add below code
using Microsoft.Azure.Cosmos.Table;
public class TenantSetting : TableEntity
{
public TenantSetting()
{
}
public string DbType { get; set; }
public string ConnectionString { get; set; }
public bool IsDeleted { get; set; }
}
Step 7 : Crud operations
Add .cs file to the project and name it as AzureDbOperations and add below code
using Microsoft.Azure.Cosmos.Table;
public class AzureDbOperations
{
public CloudTable CreateTable()
{
string tableName = AppSettings.LoadAppSettings().TableName;
CloudTable table = AzureTableCreation.CreateTable(tableName);
return table;
}
public async Task<IEnumerable<TenantSetting>> GetAll()
{
TableContinuationToken token = null;
CloudTable table = CreateTable();
List<TenantSetting> tenantSettings = new List<TenantSetting>();
TableQuery<TenantSetting> tenantQuery = new TableQuery<TenantSetting>();
TableQuerySegment<TenantSetting> seg = await table.ExecuteQuerySegmentedAsync<TenantSetting>(tenantQuery, token);
token = seg.ContinuationToken;
foreach (TenantSetting item in seg)
{
if (!item.IsDeleted)
{
TenantSetting tenant = new TenantSetting();
tenant.PartitionKey = item.PartitionKey;
tenant.RowKey = item.RowKey;
tenant.DbType = item.DbType;
tenant.ConnectionString = item.ConnectionString;
tenant.IsDeleted = item.IsDeleted;
tenant.Timestamp = item.Timestamp;
tenantSettings.Add(tenant);
}
}
return tenantSettings;
}
public async Task<TenantSetting> InsertOrMergeEntityAsync(CloudTable table, TenantSetting entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
try
{
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);
TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
TenantSetting insertedCustomer = result.Result as TenantSetting;
return insertedCustomer;
}
catch (StorageException e)
{
throw e;
}
}
public async Task<TenantSetting> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
{
try
{
TableOperation retrieveOperation = TableOperation.Retrieve<TenantSetting>(partitionKey, rowKey);
TableResult result = await table.ExecuteAsync(retrieveOperation);
TenantSetting tenantSetting = result.Result as TenantSetting;
return tenantSetting;
}
catch (StorageException e)
{
throw e;
}
}
public async Task<TableResult> DeleteEntityAsync(CloudTable table, TenantSetting deleteEntity)
{
try
{
if (deleteEntity == null)
{
throw new ArgumentNullException("deleteEntity");
}
TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
TableResult result = await table.ExecuteAsync(deleteOperation);
return result;
}
catch (StorageException e)
{
throw e;
}
}
}
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.