AZURE, WCF

CRUD operation on Windows Azure table storage as WCF Service

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,

image

Assume we have Azure table called Student as below,

image

There are 5 columns

  1. Partition Key
  2. Row Key
  3. Timestamp
  4. Name
  5. 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

  1. Student class is attributed with DataServiceEntity
  2. 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,

  1. Microsoft.WindowsAzure.DevelopmentStorage.Store.dll
  2. Microsoft.WindowsAzure.StorageClient.dll
  3. System.Data.Services.Client.dll

Make sure to put your own connection string to azure storage to parse.

image

Include below namespaces,

image

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 Smile

About Dhananjay Kumar

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Discussion

6 Responses to “CRUD operation on Windows Azure table storage as WCF Service”

  1. Hmmm, where is RollNumber used in UpdateStudent() and DeleteStudent() ???

    Posted by Anonymous | September 7, 2011, 1:45 am
  2. Hi Dhananjay,

    I cant create [DataServiceEntity] …what might be the problem?…Does this require any reference?…

    Posted by Navarajan | March 5, 2012, 9:39 pm
  3. Your article are really awesome. Actually I was in search for some good articles on DML and DQL using Table Service in Windows Azure and finally I got one.
    The most important is the simplicity which will be very helpful for the beginners. Check this links too it helped me lot in completing task….
    http://www.mindstick.com/Articles/0c3ac0b4-4294-4443-897d-c9947533f006/?DML%20and%20DQL%20using%20Table%20Service%20in%20Windows%20Azure

    http://msdn.microsoft.com/en-us/library/windowsazure/dd179463.aspx

    Posted by Manoj Bhatt | March 15, 2012, 9:23 pm
  4. Can you provide me the compete source code for thise article? I really appreciate this good work. But I want to do the same thing with WCF Rest Services. How will I do that? I need some standard architecture which I need to follow.
    Please suggest something.

    Posted by Sajid | May 15, 2012, 1:26 pm

Trackbacks/Pingbacks

  1. Pingback: Windows Azure and Cloud Computing Posts for 9/3/2011+ - Windows Azure Blog - September 5, 2011

  2. Pingback: Monthly Report September 2011: Total Posts 28 « debug mode…… - October 1, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,380 other followers

Tweets

Categories

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2012