Step by Step walkthrough on CRUD operation on Azure Table Part 01

No.of Views3161
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  20 Jul 2010 09:07:42
Tag : Windows Azure , Miscellaneous
In this article, I will show you how we can perform CRUD operation on AZURE table. This article is divided into two parts. In part 1, I am using local development fabric and storage. In next part, I will show you how can use AZURE table from Microsoft data center.
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

In this article, I will show you how we can perform CRUD operation on AZURE table.  This article is divided into two parts.  In part 1, I am using local development fabric and storage. In next part, I will show you how can use AZURE table from Microsoft data center.

Step 1: Create the project

Open visual studio. Create a new project by selecting New from File menu.  Then from AZURE tab select Windows Azure Cloud Service project. 

Image Loading

Give a meaningful name and then select a location for your project.  After giving name and location click ok.  Now select the Role. Select an ASP.Net WEB Role. If you want, you can change the name of selected ASP.Net Web Role but, I am leaving here the default name. 

Image Loading

Now in solution explorer, you can see two projects one is cloud service project and other is ASP.Net Web Role project. 

Image Loading

Step 2: Add the references

Add the below, references in your web role project. To do that, right click on web role project and select add references from context menu. 

Image Loading

Add the below references in the project.

1.    System.DataService
2.    System.DataService.Client
3.    Microsoft.WindowsAzure.Diagnostic
4.    Microsoft.WindowsAzure.RunTime
5.    Microsoft.WindowsAzure.StorageClient
  

Image Loading
Image Loading

Step 3: Create Data Model class

Let us say, we want to create a table in database as of below schema,

Player Table 

Image Loading

1.    Right click on web role project and add a new class.  Give a meaningful name to the class. I am giving name here PlayerModel 

Image Loading
Image Loading

So, now you can see in solution explorer, you have added a new class PlayerModel.cs.
2.    Add the namespaces. Only keep below namespcaes and remove all other namespace. 

Image Loading

3.    Inherit the class from TableServiceEntity class. 

Image Loading

After inheriting class will look like below, 

Image Loading

4.    Define the constructor . In constructor define the row key and partition key. 

Image Loading

You can give any string as partition key.  Now model the column of table as properties of the class. 

Image Loading

So the full source code for model class can be given as below,

PlayerModel.cs

using System;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1
{public class PlayerModel : TableServiceEntity
    {public PlayerModel()
        {
            RowKey = string.Format("{0:10}_{1}",
                           DateTime.MaxValue.Ticks - DateTime.Now.Ticks,
                           Guid.NewGuid());
            PartitionKey = "Player"; 
        }public string PlayerId { get; set; }public string PlayerName { get; set; }public string PlayerSports { get; set; }public string PlayerCountry { get; set; }

    }
}

 Step 4: Create the Entity class

1.       Right click on web role project and add a new class.  Give a meaningful name to the class. I am giving name here PlayerEntity 

Image Loading

 

Image Loading

2. Define the properties

Image Loading

So, the PlayerEntity class will look like

PlayerEntity.cs

namespace WebRole1
{public class PlayerEntity
    {public string playerId { get; set; }public string playerName { get; set; }public string playerSports { get; set; }public string playerCountry { get; set; }
    }
}

 Step 5: Create the Context class

3.    Right click on web role project and add a new class.  Give a meaningful name to the class. I am giving name here PlayerContext

Image Loading

 

Image Loading

4.     Remove all the namespaces and leave the below namespaces 

Image Loading

5.    Inherit the class from TableServiceContext class. 

Image Loading

So, after inheriting class will look like 

Image Loading

6.    Now in the constructor, pass the base address and credentials. 

Image Loading

7.    Create a query to return the data from the table.  Create a property in the context class for this purpose. 

Image Loading

8.    Write the function to add players in the table 

Image Loading

In this function, you need to pass object of PlayerEntity class.  Then using, automatic property initializer, you need to create instance of PlayerModel class.

9.    Write a function to edit the player in the table. 

Image Loading

Here again, you have to pass as parameter object of PlayerEntity class and then retrieve particular player from the table based on playerId. After retrieving the player modify the particular player and do the update object operation.

10.    Write a function to delete a particular Player from the table 

Image Loading

Here, again we are passing playerId of the player to be deleted.
So, for your reference the full source code is given below,

PlayerContext.cs

using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient; 


namespace WebRole1
{public class PlayerContext : TableServiceContext
    {public PlayerContext(string baseAddress, StorageCredentials credentials)
        :base(baseAddress ,credentials)
        {
        }public IQueryable<PlayerModel> Players
        {get{return this.CreateQuery<PlayerModel>("Players");
            }
        }public void AddPlayer(PlayerEntity player)
        {this.AddObject("Players",new PlayerModel{PlayerId= player.playerId , 
                                                       PlayerName = player.playerName,
                                                       PlayerCountry = player.playerCountry ,
                                                      PlayerSports = player.playerSports });this.SaveChanges();


                         
        }public void EditPlayer(PlayerEntity player)
        {
            PlayerModel  playerToModify  = (from r in this.Players 
                                            where r.PlayerId == player.playerId
                                            select r).First();
            playerToModify.PlayerName = player.playerName;
            playerToModify.PlayerSports = player.playerSports;
            playerToModify.PlayerCountry = player.playerCountry;this.UpdateObject(playerToModify);this.SaveChanges();            
            
        }public void DeletePlayer(string playerId)
        {
            PlayerModel playerToDelete = (from r in this.Players
                                          where r.PlayerId == playerId
                                          select r).First();this.DeleteObject(playerToDelete);this.SaveChanges();
        }
    }
}

 Step 5:  Working with Connection strings

Image Loading

Either you can use local development fabric storage or the real azure table you create at Microsoft data center.

Connection string in Using Local development

1.     Click on the Web Role in Cloud project 

Image Loading

2.    Click on the  Setting in the tab. 

Image Loading

3.    The from top click on the Add Settings. 

Image Loading

4.    When you click on Add Setting, a setting will get added. From the drop down select Connectin string as the type. 

Image Loading

5.    After selecting the type. Click on the Value tab.  If you are going to use development storage, you do not need to do anything.  If you are using storage credentials from azure table then you have to provide the credential of azure table.


Note: I will explain about using credentials of real azure table from Microsoft data center in later articles and video 

Image Loading

So, after this step you can see that we have added a connection string. This connection string is going to use the local development storage. We have given name of this connection string as LocalDevConnectionString. So we will be using LocalDevConnectionString (Connection string name, if you want you can change it) in order to connect to DB. 

Image Loading

If you can notice in value column that UseDevelopmentStorage=true value is there. It says, we are going to use local dev storage.

Step 6:  Modifying WebRole class to create table in the storage.

1.    Click on WebRole.cs class in ASP.Net Web Role Project. 

Image Loading

2.     You need to modify this class , first add the below code 

Image Loading

You need to create the table using the below code. Make sure that, you are providing the same connection string name, which you created in previous step. [In our case it is LocalDevConnectionString] 

Image Loading

 So after doing above steps, the WebRole.cs class will look like

WebRole.cs

using System.Linq;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace WebRole1
{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<RoleEnvironmentConfigurationSettingChange>()
                    .Any((change) => (change.ConfigurationSettingName == configName)))
                    {if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                        {
                           RoleEnvironment.RequestRecycle();
                        }
                    }


                };
            }
            );


            var account = CloudStorageAccount.FromConfigurationSetting("LocalDevConnectionString");
            CloudTableClient.CreateTablesFromModel(typeof(PlayerContext ), 
                           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;
            }
        }
    }
}

 Step 7:  Designing the default.aspx page.

1.    I have added four buttons for add, edit and delete operations.
2.    I have added a grid view to show all the players.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebRole1._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head><body><form id="form1" runat="server"><div style="height: 614px"><asp:Button ID="btnAddPlayer" runat="server" Text="Add Player" Width="175"onclick="btnAddPlayer_Click" /><asp:Button ID="btnEditPlayer" runat="server" Text="Edit Player" Width="175px"onclick="btnEditPlayer_Click" /><asp:Button ID="btnDeletePlayer" runat="server" Text="Delete Player"Width="175px" onclick="btnDeletePlayer_Click" /><asp:Button ID="btnDisplayPlayer" runat="server" Text="Display Player"Width="175px" onclick="btnDisplayPlayer_Click" /><asp:GridView ID="grdPlayers" runat="server"></asp:GridView></div></form></body></html>

 Step 8:To add a Player

Image Loading

a.    First need to create account reading connection string.
b.    Create object of PlayerContext .
c.    Call AddPlayer method passing object of PlayerEntity class.

Step 9:To edit a player

Image Loading

a.    First need to create account reading connection string.
b.    Create object of PlayerContext .
c.    Call EditPlayer method passing object of PlayerEntity class.

Step 10 : To delete a player
 

Image Loading

a.    First need to create account reading connection string.
b.    Create object of PlayerContext .
c.    Call DeletePlayer method passing object  playerID.

Step 11 

Image Loading

Here, we are fetching the data and binding the grid view.
So when you run, you will get the below output. 

Image Loading

For your reference the source code is below

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics;
using System.Data.Services;
using System.Data.Services.Client; 

namespace WebRole1
{public partial class _Default : System.Web.UI.Page
    {protected void Page_Load(object sender, EventArgs e)
        {

           

        }protected void btnAddPlayer_Click(object sender, EventArgs e)
        {


            var account = CloudStorageAccount.FromConfigurationSetting("LocalDevConnectionString");
            var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);
            playerContext.AddPlayer(new PlayerEntity { playerId = "1", 
                                                      playerCountry = "India ", 
                                                       playerSports = "Cricket", 
                                                       playerName = "Sachin Tendulakr" });

            playerContext.AddPlayer(new PlayerEntity { playerId = "2",
                                                       playerCountry = "Argentina ", 
                                                       playerSports = "Football", 
                                                       playerName = "Messy" });
         }protected void btnEditPlayer_Click(object sender, EventArgs e)
        {

            var account = CloudStorageAccount.FromConfigurationSetting("LocalDevConnectionString");
            var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);
            playerContext.EditPlayer(new PlayerEntity 
                                      { playerId = "1", 
                                          playerCountry = "India ",
                                          playerSports = "Cricket",
                                          playerName = "Sachin Ramesh Tendulakr" });

        }protected void btnDeletePlayer_Click(object sender, EventArgs e)
        {

            var account = CloudStorageAccount.FromConfigurationSetting("LocalDevConnectionString");
            var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);
            playerContext.DeletePlayer("1");
        }protected void btnDisplayPlayer_Click(object sender, EventArgs e)
        {
            List<PlayerEntity> players = new List<PlayerEntity>();
            var account = CloudStorageAccount.FromConfigurationSetting("LocalDevConnectionString");
            var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);
            var res =  playerContext.Players ;foreach(var r in res )
           {
               players.Add(new PlayerEntity
                                              {
                                                  playerId = r.PlayerId,
                                                  playerName = r.PlayerName,
                                                  playerCountry = r.PlayerCountry,
                                                  playerSports = r.PlayerSports
                                              }
                                );         

           }
           grdPlayers.DataSource = players;
           grdPlayers.DataBind();

        }
    }
}

 I hope this article was useful. Thanks for reading.  Happy coding.

 
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
Comments
By:SajidDate Of Posted:5/15/2012 6:18:38 AM
CRUD Operation on Azure Table with WCF And WCF Rest Services
Hi Dhanajay, Its really very nice and easy to understand article. I really appreciate your efforts. I just want you to write another post which will show the CRUD on Azure Table Storage with WCF or WCF Rest services in detail and step by step. I am awaiting for your reply
By:AnkurDate Of Posted:10/11/2010 5:10:45 AM
Re: Step by step I
Hey dhannajay I have read many articles about cloud computing but this is one of the finest article i have read easy to understand the language you have used is mareblous. Hats of to you. Some things i need to ask about this article lets see you have got time answer the quries
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