CRUD Operation on Windows Azure Table Storage as WCF Service

You may have come across the 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 want to architecture your application as below,

CRUD operation on Windows Azure table storage as WCF Service

Assume we have an Azure table called Student as below,

CRUD operation on Windows Azure table storage as WCF Service

There are 5 columns

  1. Partition Key
  2. Row Key
  3. Timestamp
  4. Name
  5. RollNumber


We need to perform CRUD operation on the Student table.

Creating Data Contract

Very first let us create a DataContract representing the Azure table.

    [DataContract]
    [DataServiceEntity]
    public class Student 
    {
        [DataMember]
        public string RollNumber { get ; set;}
        [DataMember]
        public string Name { get ; set;}        
        public string PartitionKey { getset; }   
        public string RowKey { getset; }
    }    


There is two of points to be noted in the above Data Contract

  1. Student class is attributed with DataServiceEntity

  2. Partitionkey and Rowkey are not exposed as Data Members. 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 each corresponding CRUD operation.

Implementing Service

Before implementing the service add the below references to the 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.

a11.jpg

Include below namespaces,

CRUD operation on Windows Azure table storage as WCF Service

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

        
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 a random string as value of partition key and row key.

Random string function is taken from Mahesh Chand article and it is as below,

        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

      
Service1Client proxy = newService1Client();
      
var result = proxy.GetStudents();
      
foreach (var r in result)
       {
          
Console.WriteLine(r.Name);
       }

Insert Student

       Service1Client proxy = newService1Client();

       bool b = proxy.InsertStudent(new Student { RollNumber = "34", Name = "DK" });
       if (b)
           Console.WriteLine("Inserted");
       else
           Console.WriteLine("Sorry");


Update Student

      
Service1Client proxy = newService1Client();
      
bool b2 = proxy.UpdateStudent("34");
      
if (b2)
          
Console.WriteLine("Updated");
      
else
          
Console.WriteLine("Sorry");

DeleteStudent

      
Service1Client proxy = newService1Client();

       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.

Up Next
    Ebook Download
    View all
    Learn
    View all