HI WELCOME TO KANSIRIS

Azure Cosmos Table API Example using .Net Core 2.2

Leave a Comment


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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.