You may have come across requirement of performing CRUD operation on Windows Azure table storage many times. If you have encapsulated functions performing CRUD operation on Azure Table Storage as operation contract of WCF Service then any type of client can work against azure table storage.
You may always want to architecture your application as below,
Assume we have Azure table called Student as below,
There are 5 columns
- Partition Key
- Row Key
- Timestamp
- Name
- RollNumber
We need to perform CRUD operation on Student table.
Creating Data Contract
Very first let us create a DataContract representing Azure table.
[DataContract] [DataServiceEntity] public class Student { [DataMember] public string RollNumber { get ; set;} [DataMember] public string Name { get ; set;} public string PartitionKey { get; set; } public string RowKey { get; set; } }
There is two of points to be noted in above Data Contract
- Student class is attributed with DataServiceEntity
- Partitionkey and Rowkey are not exposed as Data Member. At the service side only we will set its values with random string values.
Creating Operation Contract
[ServiceContract] public interface IService1 { [OperationContract] List<Student> GetStudents(); [OperationContract] bool InsertStudent(Student s); [OperationContract] bool DeleteStudent(string RollNumber); [OperationContract] bool UpdateStudent(string RollNumber); }
We have created four operation contract for corresponding CRUD operation.
Implementing Service
Before implementing the service add below references to project,
- Microsoft.WindowsAzure.DevelopmentStorage.Store.dll
- Microsoft.WindowsAzure.StorageClient.dll
- System.Data.Services.Client.dll
Make sure to put your own connection string to azure storage to parse.
Include below namespaces,
Retrieving records
public List<Student> GetStudents() { CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh="); DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext(); var result = from t in context.CreateQuery<Student>("Student") select t; return result.ToList(); }
This is simple LINQ retrieving all the records
Insert Entity
</span> <pre> public bool InsertStudent(Student s) { try { CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh="); DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext(); s.PartitionKey = RandomString(9, true); s.RowKey = RandomString(9, true); context.AddObject("Student", s); context.SaveChanges(); return true; } catch (Exception ex) { return false; } }
We are putting random string as value of partition key and row key.
Random string function is taken from Mahesh Chand article and it is as below,
</span> <pre> private string RandomString(int size, bool lowerCase) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } if (lowerCase) return builder.ToString().ToLower(); return builder.ToString(); }
Update Entity
public bool UpdateStudent(string RollNumber) { try { CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh="); DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext(); Student result = (from t in context.CreateQuery<Student>("Student") select t).FirstOrDefault(); result.Name = "UpdatedName"; context.UpdateObject(result); context.SaveChanges(); return true; } catch (Exception ex) { return false; } }
We are passing roll number to update. First we are fetching the entity to be updated and then updating it.
Delete Entity
public bool DeleteStudent(string RollNumber) { try { CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh="); DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext(); Student result = (from t in context.CreateQuery<Student>("Student") select t).FirstOrDefault(); context.DeleteObject(result); context.SaveChanges(); return true; } catch (Exception ex) { return false; } }
We are passing roll number to delete. First we are fetching the entity to be deleted and then deleting it.
Consuming at managed client
Get the Students
</span><span class="Apple-style-span" style="color: #222222; font-size: 15px; line-height: 21px; white-space: pre; background-color: #eeeeee;">Service1Client proxy = new Service1Client();</span> <pre> var result = proxy.GetStudents(); foreach (var r in result) { Console.WriteLine(r.Name); }
Insert Student
</span> <pre> Service1Client proxy = new Service1Client(); bool b = proxy.InsertStudent(new Student { RollNumber = "34", Name = "DK" }); if (b) Console.WriteLine("Inserted"); else Console.WriteLine("Sorry");
Update Student
</span> <pre> Service1Client proxy = new Service1Client(); bool b2 = proxy.UpdateStudent("34"); if (b2) Console.WriteLine("Updated"); else Console.WriteLine("Sorry");
Delete Student
Service1Client proxy = new Service1Client(); bool b1 = proxy.DeleteStudent("34"); if (b1) Console.WriteLine("Deleted"); else Console.WriteLine("Sorry");
This is all you have to do to perform CRUD operation on Azure Table. In next post we will consume WCF Service from a Silverlight client.
I hope this post was useful. Thanks for reading
Leave a Reply