Azure-Using_Windows_Azure_Tables by yvtong

VIEWS: 7 PAGES: 13

									Microsoft Virtual Labs
             ®



    Using Windows Azure Tables
Using Windows Azure Tables


Table of Contents
Using Windows Azure Tables ...................................................................................................... 1
Exercise 1 Working with Tables ....................................................................................................................................2
Using Windows Azure Tables


Using Windows Azure Tables

Objectives                   After completing this lab, you will be better able to:
                               Use Windows Azure Table Storage
                               Use ADO.NET Data Services client library to access Table Storage

Scenario                     Storage services provide persistent, durable storage in the Windows Azure fabric.
                             In this lab, you will examine the basic process of working with Windows Azure
                             Table Storage on the local development fabric, and explore some of the features
                             that are available to developers.
                             The Windows Azure SDK development environment includes Development
                             Storage, a utility that simulates the Table Storage services available in the cloud.
                             You can use it to test hosted applications that employ storage services against a
                             local development storage environment.

Estimated Time to            60 Minutes
Complete This Lab

Computers used in this
Lab                                   MSDNWAZLab



                             The password for the Administrator account on all computers in this lab is:
                             Passsword




                                              Page 1 of 11
Using Windows Azure Tables

Exercise 1
Working with Tables

Scenario
In this exercise, you use the Windows Azure Table Storage API to create a simple application that stores and
retrieves data in structured storage. It consists of a simple chat Web application that can save, retrieve and display
messages stored in a Windows Azure table.
Windows Azure tables store data as collections of entities. Entities are similar to rows. An entity has a primary key
and a set of properties. A property is a name/value pair, similar to a column.
To access Windows Azure Table Storage, you use a REST API that is compatible with the ADO.NET Data Services
Framework. This exercise uses the .NET Client Library (ADO.NET Data Services Framework) to read and write
data to table storage.


Tasks                         Detailed Steps
Complete the following        Note: In this task, you configure the settings required to make a connection to the
tasks on:                     Table Storage Service.
                              a. Log in as user “WAUser” with password “Password”
      MSDNWAZLab              b. Open Microsoft Visual Studio 2008 elevated as Administrator from Start | All
1.   Configuring Storage          Programs | Microsoft Visual Studio 2008 by right-clicking Microsoft Visual
     Account Settings             Studio 2008 and choosing Run as Administrator.
                              c. Open the begin.sln solution file located in
                                  C:\AzureServicesKit\Labs\UsingWindowsAzureTables\Ex01-
                                  WorkingWithTables\begin.




                                                    Page 2 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps




                         Note: The solution contains a WebRole project and the StorageClient library project.
                         The StorageClient library contains helper classes and methods to access Windows
                         Azure storage that you can use to abstract the REST API. It is included as a sample in
                         the Windows Azure SDK and provided as part of the lab material for your
                         convenience.
                         d. Update the service definition file to define the configuration settings required to
                             access Windows Azure Table storage. In Solution Explorer, double-click
                             ServiceDefinition.csdef to open this file in the text editor and inside the WebRole
                             element, insert the ConfigurationSettings element shown below (shown in bold
                             text.)
                         ServiceDefinition.csdef
                         <?xml version="1.0" encoding="utf-8"?>
                         <ServiceDefinition name="Red_Dog_Chat"
                         xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/Servi
                         ceDefinition">
                           <WebRole name="WebRole">
                             <InputEndpoints>
                               <InputEndpoint name="HttpIn" protocol="http" port="8080"
                         />
                             </InputEndpoints>
                             <ConfigurationSettings>
                               <Setting name="AccountName" />
                               <Setting name="AccountSharedKey" />
                               <Setting name="TableStorageEndpoint" />



                                               Page 3 of 11
Using Windows Azure Tables
Tasks                      Detailed Steps
                               </ConfigurationSettings>
                             </WebRole>
                           </ServiceDefinition>

                           Note: The StorageClient library uses these settings to access Windows Azure Storage.
                           AccountName: specifies the name of your Windows Azure account. The account
                           name is one of the components used to construct the URI of a store resource.
                           AccountSharedKey: specifies the key used to authenticate a request made against
                           Windows Azure storage. To authenticate a request, it must be signed with the key for
                           the account that is making the request.
                           TableStorageEndpoint : specifies the base URI of the table storage service.
                           e. Next, update the service configuration file to set the value of the properties defined
                              in the previous step. Open the ServiceConfiguration.cscfg file, locate the
                              ConfigurationSettings section and insert the following Setting elements (shown
                              in bold text.) Note that the AccountSharedKey value is present in the file
                              C:\AzureServicesKit\Labs\UsingWindowsAzureTables\Ex01-
                              WorkingWithBlobs\end\RDImageGallery\ServiceConfiguration.cscfg, if you
                              wish to copy/paste the value instead of typing it.
                           ServiceConfiguration.cscfg
                           <?xml version="1.0"?>
                           <ServiceConfiguration serviceName="RdChat"
                           xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"
                           >
                            <Role name="WebRole">
                             <Instances count="1"/>
                             <ConfigurationSettings>
                              <Setting name="AccountName" value="devstoreaccount1"/>
                              <Setting name="AccountSharedKey"
                           value="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVE
                           rCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="/>
                              <Setting name="TableStorageEndpoint" value="http://127.0.0.1:10002"/>
                             </ConfigurationSettings>
                            </Role>
                           </ServiceConfiguration>
                           Note: The development storage supports only a single fixed account and a well-known
                           authentication key whose purpose is to allow you to test the functionality of your client
                           authentication code.
                           f.   Save the ServiceDefinition.csdef and ServiceConfiguration.cscfg files.
2.   Creating Classes to   Note: When working locally against the development storage service for Table
     Model the Table       Storage, you use the ADO.NET client library to work with tables that have a fixed
     Schema                schema.
                           The Table Storage service in the cloud does not require table configuration and
                           supports the creation of entities with varying numbers and types of properties within
                           the same table.
                           To create a database table for use with development storage, you construct a class
                           that models the desired schema. In addition to the properties required by your model,
                           the class must include a Timestamp, a PartitionKey and a RowKey property and it
                           must be decorated with a DataServiceKey(“PartitionKey”, “RowKey”) custom
                           attribute.


                                                 Page 4 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps
                         You create the SQL database and the tables required by your application when it is
                         executed against the local development storage from within Visual Studio. To support
                         this, you provide one or more DataServiceContext-derived classes in your client code
                         where for each of the tables, you expose a property of type
                         IQueryable<SchemaClass>, where SchemaClass is the class that models the schema
                         for that table.
                         In this task, you create the development storage database and initialize the schema for
                         the table that stores messages for the Chat application.
                         a. Add a reference to the ADO.NET client library to the Web role project. In
                              Solution Explorer, right-click the RdChat_WebRole project node and select
                              Add Reference…. In the .NET tab, select the System.Data.Services.Client
                              assembly and click OK.
                         b. Add a class to the Web role project to model the message table. To do this, in
                              Solution Explorer, right-click the RdChat_WebRole project node, point to Add
                              and select Class…. In the Add New Item dialog, set the Name to Message.cs and
                              click Add.
                         c. Update the declaration of the Message class to derive from the
                              Microsoft.Samples.ServiceHosting.StorageClient.TableStorageEntity class.
                         C#
                         public class Message:
                         Microsoft.Samples.ServiceHosting.StorageClient.TableStorageEntit
                         y
                         {
                         }

                         Note: The TableStorageEntity class is included as part of the StorageClient library. It
                         defines the PartititionKey, RowKey and TimeStamp system properties required by
                         every entity stored in a Windows Azure table.
                         Together, the PartitionKey and RowKey define the DataServiceKey that uniquely
                         identifies every entity within a table.
                         d. Add a default constructor to the Message class that initializes its PartitionKey and
                              RowKey properties.
                         C#
                         public Message()
                         {
                           PartitionKey = "a";
                           RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks -
                         DateTime.Now.Ticks, Guid.NewGuid());
                         }

                         Note: For the purposes of this exercise, you assign a fixed value to the PartitionKey
                         property. In a more realistic scenario, you would choose a value that ensures load
                         balancing across storage nodes.
                         e. Add two string properties to the Message class, Name and Body, to hold
                              information about the chat message.
                         C#
                         public string Name { get; set; }
                         public string Body { get; set; }

                         f.   Save the Message.cs file.
                         g. Next, add a class to the Web role project to define the ADO.NET


                                                Page 5 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps
                              DataServiceContext required to access the Messages table. To do this, in
                              Solution Explorer, right-click the RdChat_WebRole project node, point to Add
                              and select Class…. In the Add New Item dialog, set the Name to
                              MessageDataServiceContext.cs and click Add.
                         h. In the new class file, add the following using namespace directive.
                         C#
                         using Microsoft.Samples.ServiceHosting.StorageClient;

                         i.   Replace the declaration of the new class to derive from the
                              TableStorageDataServiceContext class and include a default constructor to
                              initialize the base class with the storage account information.
                         C#
                         namespace RdChat_WebRole
                         {
                           public class MessageDataServiceContext :
                         TableStorageDataServiceContext
                           {
                             public MessageDataServiceContext(StorageAccountInfo
                         accountInfo)
                                 : base(accountInfo)
                             {
                             }
                           }
                         }

                         j.   Now, add a property to the MessageDataServiceContext class to return a data
                              service query for the Messages table.
                         C#
                         public IQueryable<Message> Messages
                         {
                           get
                           {
                             return this.CreateQuery<Message>("Messages");
                           }
                         }

                         Note: Visual Studio identifies classes that derive from DataServiceContext in the
                         solution and locates any properties that return an IQueryable<T>, where the generic
                         parameter T identifies the class that models the table schema. For each such property,
                         it creates a table in local development storage named after the property and defines its
                         schema using the public properties in the model class.
                         k. Finally, add a method to the MessageDataServiceContext class to insert new
                              messages into the table. You will use this method later when implementing the
                              chat functionality.
                         C#
                         public void AddMessage(string name, string body)
                         {
                           this.AddObject("Messages", new Message { Name = name, Body =
                         body });
                           this.SaveChanges();




                                                Page 6 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps
                         }

                         l.   In the Build menu, select Build Solution.
3.   Creating the        Note: In this task, you create the development storage database and initialize the
     Development         schema of the tables using the table definition classes created in the previous task.
     Storage Tables      a. In Solution Explorer, right-click the RdChat cloud service project node, and
                              select Create Test Storage Tables.




                         b. Visual Studio creates a new database, which it names after the name of the cloud
                              services project (RdChat), and a Messages table using the schema you created in
                              the previous task.




                                                Page 7 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps




4.   Creating the Chat   Note: In this task, you add the code necessary to store messages in a Windows Azure
     User Interface      table and display them on the Web page.
                         a. Open the code-behind file for the Web page that contains the UI for the chat
                              application. Expand the RDChat_WebRole node in Solution Explorer, then
                              right-click Default.aspx and select View Code.
                         b. Add the following using namespace directive to the Default.aspx.cs file.
                         C#
                         using System.Data.Services.Client;

                         c. Locate the Page_Load method and insert the following code to retrieve messages
                              from Table Storage and display them on the page.
                         C#
                         protected void Page_Load(object sender, EventArgs e)
                         {
                           string statusMessage = String.Empty;
                           try
                           {
                             StorageAccountInfo accountInfo =
                         StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorage
                         Endpoint");

                               // dynamically create the tables

                         TableStorage.CreateTablesFromModel(typeof(MessageDataServiceCont
                         ext), accountInfo);

                             MessageDataServiceContext context = new
                         MessageDataServiceContext(accountInfo);
                             this.messageList.DataSource = context.Messages.Take(10);
                             this.messageList.DataBind();
                           }
                           catch (DataServiceRequestException ex)
                           {
                             statusMessage = "Unable to connect to the table storage
                         server. Please check that the service is running.<br>"
                                             + ex.Message;
                           }
                           status.Text = statusMessage;
                         }

                         Note: When executed in the cloud, the code creates the required tables from the model

                                               Page 8 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps
                         defined by the MessageDataServiceContext class created earlier. Note that in the
                         local development storage, you do not create the tables dynamically but instead, you
                         do so in advance using the Windows Azure Tools for Visual Studio, as was shown in
                         the previous task.
                         To retrieve and display messages, the method creates an instance of the
                         MessageDataServiceContext class and initializes it from account information
                         available in the service configuration file (ServiceConfiguration.cscfg). It binds the
                         Messages property, which returns a data service query for the Messages table, to a
                         ListView control on the page for display.
                         Objects of type StorageAccountInfo represent a storage account and contains the
                         settings required to make a connection to the Storage Service. Associated with a
                         storage account is the account name, the URI of the account and a shared key, which
                         the TableStorage helper class uses for its initialization. These settings are obtained
                         from ServiceConfiguration.cscfg.
                         d. Locate the SubmitButton_Click event handler and insert the following code into
                              the method body to save messages entered by the user to Table Storage. The
                              method uses the AddMessage method, which you created earlier in the lab, to
                              insert a new Message entity into the table.
                         C#
                         protected void SubmitButton_Click(object sender, EventArgs e)
                         {
                           StorageAccountInfo accountInfo =
                         StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorage
                         Endpoint");
                           MessageDataServiceContext context = new
                         MessageDataServiceContext(accountInfo);
                           context.AddMessage(this.nameBox.Text, this.messageBox.Text);
                         }

                         e. Save the Default.aspx.cs file.

5.   Verification        a. In Visual Studio, press F5 to build and run the application. The development fabric
                              starts and a new tenant containing the RdChat Web Role initializes. A browser
                              window opens to display the Windows Azure Chat Web page.




                         Note: When you start the program in the debugger, Visual Studio automatically starts


                                                Page 9 of 11
Using Windows Azure Tables
Tasks                    Detailed Steps
                         Development Storage Services. If the Chat application is unable to access the table
                         storage server, you will see an error as shown in the figure below. To examine the
                         status of the service, right-click the icon in the system tray (it looks like a server) and
                         select Show Development Storage UI.




                         Note: The very first time you run Development Storage Services, the Table service will
                         not be configured to use the same RdChat table configuration you created earlier in
                         the lab. To correct this, open the UI. Next, turn on the checkbox in front of
                         Table(RdChat), and turn off the other two checkboxes (in front of Blob and Queue).
                         Then, click Start. You will be prompted for which database to use, with RdChat pre-
                         selected. Click OK, and the service will start. The web page will refresh
                         automatically after a short time and you will be ready to continue your testing.
                         b. Now, test the Chat application by entering a few messages. Type your name and
                             the text of your message and click Submit. The page uses AJAX calls to
                             constantly poll the server and retrieve new messages. Wait a few seconds for the
                             browser window to update and show your message.
                         c. In Internet Explorer, press Ctrl + N to open a second browser window. Enter a
                             different name and type a few more messages. Notice how both windows update to
                             show the conversation.




                                                Page 10 of 11
Using Windows Azure Tables
Tasks                      Detailed Steps




                           Note: In this lab, you have learned how to work with tables in Windows Azure Storage
                           and how to use the ADO.NET Data Services client library to access the information
                           they contain.



Related Resources:
Windows Azure Tools for Microsoft Visual Studio
Windows Azure Platform Subscription
Azure SDK Download
Free Windows Azure Platform Trial Download




                                                  Page 11 of 11

								
To top