Home > DeveloperSection > Beginner > Using Table Service Data Model in Windows Azure

Using Table Service Data Model in Windows Azure


Cloud Computing Cloud Computing 
Ratings:
0 Comment(s)
 5182  View(s)
Rate this:

Using Table Service Data Model in Windows Azure

Table Service: In windows azure we can use Table service API to create tables for structured storage, and to insert, update, delete, and query data. The Table service API is a REST API for working with table and the data that they contain.

The Table service API is compliant with the REST API provided by ADO.NET Data Services, with some differences. The Table Service API restricts some functionality that is defined in the ADO.NET Data Services Framework. The API also provides some additional functionality that is not available through ADO.NET Data Services.

The table service offers structured storage in the forms of tables. In this article I am going to explain about table service used in windows azure and how to create and use table for the storage of application data.

Table, Entities, and Properties


Tables store data as collection of entities. Entities are similar to rows. An entity has a primary key and set of properties. A property is a name, typed-value pair, similar to a column.

The table service does not enforce any schema for tables, so two entities in the same table may have different sets of properties. Developers may choose to enforce a schema on the client side. A table may contain any number of entities.

An entity always has the following system properties:

·         PartitionKey property

·         RowKey property

·         Timestamp property

The system properties are automatically included for every entity in a table. The names of these properties are reserved and cannot be changed. The developer is responsible for inserting and updating the values of PartitionKey and RowKey. The server manages the value of Timestamp, which cannot be modified.

Now I am going to explain how to create table and store data in a table in a windows azure application:

·         Open Microsoft Visual Studio 2010 as an administrator.

·         To create a new project FileNewProject.

·         Select Cloud template from the Installed Templates.

·         Select Windows Azure Project and enter the name of the project as AzureTableDemo.

·         Click OK to proceed.

Using Table Service Data Model in Windows Azure

·         To add an asp.net web role to the solution, choose ASP.NET Web Role and then choose the right arrow. The roles are displayed in the Windows Azure solution pane of the dialog box. You can rename it as PersonalInfo.

·         Click OK to add.

Using Table Service Data Model in Windows Azure

After adding web role, delete all the files from the PersonalInfo web role in the solution explorer except References, Properties, WebRole.cs.

·         Add a web form (Default.aspx) in a web role.

·         Add a new web.config file.

Using Table Service Data Model in Windows Azure

Modify the Default.aspx as shown below:

    <div>

        <table>

            <tr>

                <td>

                    <asp:Label ID="lblId" runat="server" Text="Enter Id:"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtId" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblName" runat="server" Text="Enter
                                                      Name:"></
asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td colspan="2" align="center">

                    <asp:Button ID="btnInsert" runat="server" Text="Insert"

                        onclick="btnInsert_Click" />

                </td>

            </tr>

        </table>

    </div>

 

Add a class (DataEntry.cs) in a web role:

Using Table Service Data Model in Windows Azure

Add the following additional namespace in a DataEntry.cs :

using Microsoft.WindowsAzure.StorageClient;

using Microsoft.WindowsAzure;

using System.Data.Services.Client;

 

Modify the DataEntry.cs as shown below:

    public class DataEntry : TableServiceEntity

    {

        private string _strId;

        private string _strName;

 

        public string strId

        {

            get{

                return _strId;

            }

            set{

                _strId = value;

            }

        }

 

        public string strName

        {

            get{

                return _strName;

            }

            set{

                _strName = value;

            }

        }

 

        public DataEntry()

        {

            PartitionKey = "Persons";

            RowKey = DateTime.Now.Ticks.ToString();

        }

    }

 

Create a DataContext class and inherit TableServiceContext  and add the following code:

    public class DataContext : TableServiceContext

    {

 

        public DataContext(string baseAddress, StorageCredentials credentials)

            : base(baseAddress, credentials)

        {

           

        }

 

        public IQueryable<DataEntry> Persons

        {

            get

            {

                return this.CreateQuery<DataEntry>("Persons");

            }

        }

 

        public void AddPerson(DataEntry objData)

        {

            this.AddObject("Persons", objData);

            this.SaveChanges();

        }

    }

 

Now after creating or modifying DataContext and DataEntry class, add the following additional namespace in WebRole.cs :

using Microsoft.WindowsAzure.Diagnostics;

using Microsoft.WindowsAzure.ServiceRuntime;

using Microsoft.WindowsAzure.StorageClient;

 

Modify the OnStart() method of WebRole.cs as shown below:

 public override bool OnStart()

        {

            DiagnosticMonitor.Start("ConnectionString");

            CloudStorageAccount.SetConfigurationSettingPublisher((configName,    
            configSetter) =>

            {

                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

                RoleEnvironment.Changed += (anotherSender, arg) =>

                {

                    if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>
                         ().Any((change) => (change.ConfigurationSettingName ==  
                                             configName)))

                    {

                        RoleEnvironment.RequestRecycle();

                    }

                };

            });

            var Person = CloudStorageAccount.FromConfigurationSetting
                                                               ("ConnectionString");

            CloudTableClient.CreateTablesFromModel(typeof(DataContext), 
                              Person.TableEndpoint.AbsoluteUri, Person.Credentials);

 

            return base.OnStart();

        }

 

Add the following additional namespace in the Default.cs :

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.ServiceRuntime;

 

Add the following code on the click of insert button:

        protected void btnInsert_Click(object sender, EventArgs e)

        {

            // Gets the connection string

            CloudStorageAccount.SetConfigurationSettingPublisher((configName,
                                                           configSettingPublisher) =>

            {

                var connectionString = RoleEnvironment.GetConfigurationSettingValue
                                                                      (configName);

                configSettingPublisher(connectionString);

            });

 

            var details = CloudStorageAccount.FromConfigurationSetting
                                                             ("ConnectionString");

            // Create the datacontext object

            var dataContext = new DataContext(details.TableEndpoint.ToString(),
                                                              details.Credentials);

            // Create the entity object

            DataEntry data = new DataEntry();

            data.strId = txtId.Text;

            data.strName = txtName.Text;

            // Pass the entity object to the datacontext

            dataContext.AddPerson(data);

            //Loop through the records to see if the customer entity is inserted in the
              tables

            foreach (DataEntry obj in dataContext.Persons)

            {

                Response.Write("Person Id: " + obj.strId + ", Person Name: " +
                                                                obj.strName + " <br>");

            }

        }

 

Specify the name of the connection string used in the configuration setting file (ServiceConfiguration.Cloud.csfg) which is used to create and store data.

    <ConfigurationSettings>

      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"
              
value="UseDevelopmentStorage=true" />

      <Setting name="ConnectionString"value="UseDevelopmentStorage=true" />

    </ConfigurationSettings>

 

Now press F5 in order to run your application. The output should something like below:

Using Table Service Data Model in Windows Azure

Enter a string id and name and click on the Insert button. It will display all the person id and name which you have inserted in the table.

Using Table Service Data Model in Windows Azure

In order to see the inserted data, open server explorer (Ctrl + W + L). Expand the Development and Table area and click on the table(Persons). It will display all the stored data in the right side of the window.

Using Table Service Data Model in Windows Azure

In order to reset the table, right click on the windows azure in the notification area and click on Show Storage Emulator UI, itwill display Storage Emulator window, click on Reset button to clear data or reset the structure.

Using Table Service Data Model in Windows Azure

I think after reading this article, you can easily create table and store data in a table in any windows azure application.


Don't want to miss updates? Please click the below button!

Follow MindStick