Azure Simplified Part 2: Using Azure Tables

Now that we’ve built a “Hello Azure!” application, lets try using Azure tables…

1. Open up VisualStudio 2008 (run as Administrator) and create a new ‘Cloud Service’ project,

image

2. Create an ASP.NET WebRole,

image

3. Add a reference to System.Data.Services.Client to the WebRole1 project.

image 

4. Add a new data connection string. To do this, go to CloudService1 –> Roles –> WebRole1 –> right click Properties –> Settings –> Add Setting. Type in ‘DataConnectionString’ and change the Type column to ‘Connection String’. Then click on the ‘…’ at the far right and choose ‘Use development storage’.

image 

 

5. Nasty hack alert! Add the following code to the WebRole.cs’s OnStart method,

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;

    // This code sets up a handler to update CloudStorageAccount instances when their corresponding
    // configuration settings change in the service configuration file.
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => 
    {
        // Provide the configSetter with the initial value
        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

        RoleEnvironment.Changed += (sender, arg) =>
        {
            if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
                .Any((change) => (change.ConfigurationSettingName == configName))) {
                // The corresponding configuration setting has changed, propagate the value
                if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName))) {
                    RoleEnvironment.RequestRecycle();
                }
            }
        };
    });

    return base.OnStart();
}
 

6. Whew! OK, now we are ready to add our custom code,The first class you need to create is how your table rows will look like. Add a class called ‘MyTableRow.cs’ to the WebRole1 project that contains,

using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1 {
    public class MyTableRow : TableServiceEntity {
        public MyTableRow(string partitionKey, string rowKey) : base(partitionKey, rowKey) { }

        // Rows need a unique partition key – so create a new guid for every row
        public MyTableRow() : this(Guid.NewGuid().ToString(), String.Empty) { }

        // My table row
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

7. Next open up Default.aspx and paste the following simple HTML controls to display the tables,

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label id="Label1" Text="Table name:" runat="server" />
            <asp:TextBox id="tablenameBox" runat="server" />
            <asp:Button ID="Button1" Text="Create Table" runat="server" />
            <br /><br />
            
            <!-- Display tables -->
            <asp:ListBox id="ListBox1" runat="server" Width="200" Height="100" />
            
            <asp:Button ID="Button3" Text="Delete Table" runat="server" />
            <br /><br />
            <asp:Label id="Label2" Text="Name:" runat="server" />
            <asp:TextBox id="rowName" runat="server" />   
            <asp:Label id="Label3" Text="Age:" runat="server" />
            <asp:TextBox id="rowAge" runat="server" />   
            <asp:Button ID="Button2" Text="Insert into Table" runat="server" />
            <br /><br />
            
            <!-- Display table contents -->
            <asp:Repeater id="Repeater1" runat="server">
                <HeaderTemplate>
                    <table border="1">
                        <tr><td><b>Name</b></td><td><b>Age</b></td></tr>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                      <td> <%# DataBinder.Eval(Container.DataItem, "Name") %> </td>
                      <td> <%# DataBinder.Eval(Container.DataItem, "Age") %> </td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </div>    
    </form>
</body>
 

As you see, there’s nothing fancy in the HTML,  just a few buttons, a listbox to display the tables and a Repeater control to display the table contents.

7. Open Default.aspx.cs and insert the code, (you’ll want much more error checking, I’ve removed them for this example),

public partial class _Default : System.Web.UI.Page {
        
    // Manage account information
    CloudStorageAccount storageAccount = null;

    // Runtime data context
    TableServiceContext tableServiceContext = null;

    protected void Page_Load(object sender, EventArgs e) {
        // Init the contexts
        this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        this.tableServiceContext = new TableServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);

        // Hook up the buttons
        this.Button1.Click += new EventHandler(CreateTableClick);
        this.Button2.Click += new EventHandler(InsertTableClick);
        this.Button3.Click += new EventHandler(DeleteTableClick);
    }

    // Create a table
    private void CreateTableClick(Object sender, EventArgs e) {
        // Create an Azure table
        storageAccount.CreateCloudTableClient().CreateTableIfNotExist(tablenameBox.Text);

        // Update the display
        this.ListBox1.Items.Clear();
        foreach (string tableName in this.storageAccount.CreateCloudTableClient().ListTables()) { 
            this.ListBox1.Items.Add(tableName); 
        }
    }

    // Insert into a table
    private void InsertTableClick(Object sender, EventArgs e) {
        // Insert into an Azure table
        this.tableServiceContext.AddObject(this.ListBox1.SelectedItem.Text, new MyTableRow() { Name = rowName.Text, Age = Int32.Parse(rowAge.Text) });
        this.tableServiceContext.SaveChanges();

        // Update the display
        ArrayList values = new ArrayList();
        foreach (MyTableRow tableRow in this.ViewTableDetails(this.ListBox1.SelectedItem.Text)) { 
            values.Add(tableRow); 
        }
        this.Repeater1.DataSource = values;
        this.Repeater1.DataBind();
    }

    // Get rows from a table
    public IEnumerable<MyTableRow> ViewTableDetails(string tableName) {
        var results = from c in this.tableServiceContext.CreateQuery<MyTableRow>(tableName) select c;

        var query = results.AsTableServiceQuery<MyTableRow>();
        var queryResults = query.Execute();
        return queryResults;
    }

    // Delete a table
    private void DeleteTableClick(object sender, EventArgs e) {
        // Delete a table from Azure
        this.storageAccount.CreateCloudTableClient().DeleteTableIfExist(this.ListBox1.SelectedItem.Text);

        // Update the display
        this.ListBox1.Items.Clear();
        foreach (string tableName in this.storageAccount.CreateCloudTableClient().ListTables()) { 
            this.ListBox1.Items.Add(tableName); 
        }
    }
}

8. Now you can run the application,

image 

 

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Azure Simplified Part 2: Using Azure Tables

  1. Pingback: Azure Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: