CRUD Operations on Windows Azure table and Azure Storage

No.of Views1404
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 Feb 2010 00:02:57
Tag : WCF , General
CRUD Operations on Windows Azure table and Azure Storage
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

This article will give a walkthrough on how to perform a CRUD operation on Azure table.

Step 1

Create a new Cloud Service Application. To create, File -> New -> Projects -> Cloud Services. Select ASP.Net Web Role. I am giving CRUDSample to the name of the project and CRUDWebRole to the name of the Web Role.

 

Image Loading

After adding project, in solution explorer you can see two projects. One is project to publish in azure and other is simple asp.net project. In our case CRUDSample is project which contains configuration settings for azure and CRUDWebRole is asp.net project for development.

Image Loading

Step 2

Make sure below references are added CRUDWebRole projects. 

System.Data.Service
System.Data.Service.Client
Microsoft.WindowsAzure.Diagnostics
Microsoft.WindowsAzure.ServiceRunTime
Microsoft.WindowsAzure.StorageClient.

Step 3

Creating Entity class

Now right click to asp.net project add a class which will model the table in azure. Give any name to this class. This class will act as entity table.
1. Inherit the class from Microsoft.WindowsAzure.StorageClient.TableServiceEntity
2. Add a default constructor
3. In Default constructor initialize the Row key and Partition key
4. Properties of the class define columns of the table.

Row Key and Partition key
These two keys uniquely define a table and row in azure storage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Services;

namespace CRUDWebRole
{
public class USTEntity : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
{
public USTEntity()
{
RowKey = String.Format("{0:10}_{1}", (DateTime.MaxValue.Ticks - DateTime.Now.Ticks), Guid.NewGuid());
PartitionKey = "UST";
}
public String Name { get; set; }
public String Id { get; set; }
public String Manager { get; set; }
public String Experience { get; set; }
public String Technology { get; set; }
public String Location { get; set; }

}
}

Step 4

Creating Context class
Now right click on asp.net project and add a new class as context class. This class will contain function to perform all the CRUD operation. This class is inherited from TableServiceContext class.

1. In default constructor passes the base address and storage credentials to base class.
2. Since TableServiceContext class performs the operations against a class which is implementing IQueryable interface, so we will implement the interface for the entity class.
3. Just write simple LINQ for other CRUD functions.

Entire class is as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace CRUDWebRole
{
public class USTContext : TableServiceContext
{
public USTContext(string baseAddress, StorageCredentials credentials)
: base(baseAddress, credentials)
{
}
public IQueryable USTEntities
{
get{
return this.CreateQuery("USTEntities");
}
}
public void ADDUSociate(USTClientEntity entity)
{
this.AddObject("USTEntities", new USTEntity {Name = entity.Name ,Manager =entity.Manager,Id =entity.Id,Location=entity.Location,Technology=entity.Technology,Experience=entity.Experience});
this.SaveChanges();
}
public void DELUSociate(string id)
{
USTEntity res = (from r in USTEntities where r.Id == id select r ).First();
this.DeleteObject(res);
this.SaveChanges();
}
public void UPDATEUSociate(USTClientEntity entity)
{
USTEntity res = (from r in USTEntities where r.Id == entity.Id select r).First();
res.Technology = entity.Technology;
res.Location = entity.Location;
res.Manager = entity.Manager;
res.Experience = entity.Experience;

this.UpdateObject(res);
this.SaveChanges();

}
}
}

In above code I have used USTClientEntity class. This class is mapping of Entity class. This class is as below.

USTClientEntity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CRUDWebRole
{
public class USTClientEntity
{
public String Name { get; set; }
public String Id { get; set; }
public String Manager { get; set; }
public String Experience { get; set; }
public String Technology { get; set; }
public String Location { get; set; }

}
}

Step 5

Working with connection strings
We have two options to work with
1. Use local development center
2. Use Azure table from Windows azure

Use Local Development center
This option will use the local storage created by development fabric controller when you install Azure SDK.

1. Go to Azure Project. In this case it is , CRUDSample
2. Click on Roles folder
3. Then click on CRUDWebRole
4. Click on setting tab 

Image Loading

5. Click on Add Setting

Image Loading

 

6. Make sure while adding connection string, you are choosing connection string from the drop down. Give any name to the string setting.
7. Now click on left corner button

Image Loading

8. To use local storage select the radio button Use Development Storage and click on OK button.

Image Loading

9. To use AZURE table setting
Account Name: Give Azure storage account name
Account Key: Give Primary key from azure storage
Leave other setting as default and press ok.

 

Image Loading

For My purpose I have two connection strings in my application.


DiagnosticConnectionString AndCrudString

Image Loading

Step 6

Creating table
1. To create table in ASP.net project click on WebRole.cs class
2. And add below line of code to create class.

var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
CloudTableClient.CreateTablesFromModel(typeof(USTContext), account.TableEndpoint.AbsoluteUri, account.Credentials);

Whole WebRole.Cs class will look like below ,


WebRole.cs

using System.Linq;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Data.Services.Client;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace CRUDWebRole
{
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");

// For information on handling configuration changes// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.RoleEnvironment.Changing += RoleEnvironmentChanging;
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
RoleEnvironment.Changed += (anotherSender, arg) =>
{
if (arg.Changes.OfType()
.Any((change) => (change.ConfigurationSettingName == configName)))
{
if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
{
RoleEnvironment.RequestRecycle();
}
}
};
});

var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
CloudTableClient.CreateTablesFromModel(typeof(USTContext), account.TableEndpoint.AbsoluteUri, account.Credentials);
return base.OnStart();
}

private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
{
// If a configuration setting is changingif (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
{
// Set e.Cancel to true to restart this role instancee.Cancel = true;
}
}
}
}

Here CrudString is name of the connection string.

Step 7

CRUD Operations

1. To add a record

var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
var context = new USTContext(account.TableEndpoint.ToString(), account.Credentials);
USTClientEntity entity = new USTClientEntity(){Id= txtEmployeeID.Text.ToString(),Name = txtEmployeeName.Text.ToString(),Manager=txtManagerName.Text.ToString(),Experience=ddlExperience.Text.ToString(), Technology = ddlTechnology.Text.ToString(),Location = ddlCurrentLocation.Text.ToString()};
context.ADDUSociate(entity);

2. To update a record

entity = new USTClientEntity() {Id=ddlEmployees.SelectedItem.Text , Manager = txtManagerName.Text, Location = ddlCurrentLocation.SelectedItem.Text, Technology = ddlTechnology.SelectedItem.Text, Experience = ddlExperience.SelectedItem.Text };
var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
var context = new USTContext(account.TableEndpoint.ToString(), account.Credentials);
context.UPDATEUSociate(entity);

3. To Delete a record

var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
var context = new USTContext(account.TableEndpoint.ToString(), account.Credentials);
if(!string.IsNullOrEmpty(ddlEmployees.Text.ToString()))
{
context.DELUSociate(ddlEmployees.Text.ToString());
}

4. To View all records

var account = CloudStorageAccount.FromConfigurationSetting("CrudString");
var context = new USTContext(account.TableEndpoint.ToString(), account.Credentials);
List lst = new List();
foreach (USTEntity u in context.USTEntities)
{
if (!string.IsNullOrEmpty(u.Id))
{
lst.Add(new USTClientEntity() { Id = u.Id, Name = u.Name, Manager = u.Manager, Experience = u.Experience, Location = u.Location, Technology = u.Technology });
}
}
this.grdViewAll.DataSource = lst;
this.grdViewAll.DataBind();

In all above cases drodownlist , Textboxes and GridView has been used as input and output control. Now your application Is ready to run. Thanks for reading.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
    This article is part # 2 of Instance Management in WCF. This article will explain Session Full Instance management service. This will explain different Session Mode at Contract level. This will explain Per-session service also. This article will be explaining Session Full Service with a code also.
    Published Date : 02/Aug/2010
    This is first part of multi series articles. This article is giving introduction of Instance Management. This article will explain about Per-Call Instance management technique as well.
    Published Date : 30/Jul/2010
    In this article, I will show you, how we can have multiple contracts in WCF service.
    Published Date : 11/Jun/2010
    Dynamic Service and End Point Discovery feature of WCF 4.0
    Published Date : 16/Feb/2010
    This article will discuss about One Way Operations in WCF. I am also going to explain One Way Operation with Session full service pros and cons.
    Published Date : 16/Feb/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top