Storing message in table storage

In my previous post I looked at getting started with table storage, in this one we will create a table for our entities and store them. As you’ll see, quite easy!

So, to store an entity in table storage you start by creating a TableServiceEntity derived class (recap from previous post):

public class MessageEntity : TableServiceEntity
{
  public MessageEntity() { }

  public MessageEntity(string partitionKey, string rowKey, string message)
    : base( partitionKey, rowKey )
  {
    Message = message;
  }

  public string Message { get; set; }
}

 

You also need a table class, this time deriving from TableServiceContext:

public class MessageContext : TableServiceContext
{
  public const string MessageTable = "Messages";

  public MessageContext(string baseAddress, StorageCredentials credentials)
    : base(baseAddress, credentials)
  {
  }
}

TableServiceContext requires a base address and credentials, and since our class derives from it we need a constructor taking the same arguments. I also have a const string for the table name.

If the table doesn’t exist yet you should create it. This is easy, just add the code to create the table in the MessageContext’s static constructor:

static MessageContext()
{
  var tableClient =  MyStorageAccount.Instance.CreateCloudTableClient();
  tableClient.CreateTableIfNotExist(MessageTable);
}

A static constructor is automatically called when you use the type. Note that I use the MyStorageAccount class, which uses the same static constructor trick to initialize the storage account.

public static class MyStorageAccount
{
  public static string DataConnection = "DataConnection";

  public static CloudStorageAccount Instance
  {
    get
    {
      return CloudStorageAccount.FromConfigurationSetting(DataConnection);
    }
  }

  static MyStorageAccount()
  {
    CloudStorageAccount.SetConfigurationSettingPublisher(
      (config, setter) =>
      {
        setter(
          RoleEnvironment.IsAvailable ?
            RoleEnvironment.GetConfigurationSettingValue(config)
            :
            ConfigurationManager.AppSettings[config]
        );

        RoleEnvironment.Changing += (_, changes) =>
        {
          if (changes.Changes
                     .OfType<RoleEnvironmentConfigurationSettingChange>()
                     .Any(change => change.ConfigurationSettingName == config))
          {
            if (!setter(RoleEnvironment.GetConfigurationSettingValue(config)))
            {
              RoleEnvironment.RequestRecycle();
            }
          }
        };
      });
  }
}

 

Now we are ready to add the code to create and add a message to our table. Add following code to MessageContext:

public static MessageEntity CreateMessage( string message )
{
  return new MessageEntity(MessageTable, Guid.NewGuid().ToString(), message);
}

public void AddMessage(MessageEntity msg)
{
  this.AddObject(MessageTable, msg);
  this.SaveChanges();
}

 

The CreateMessage method creates a new MessageEntity instance, with the same partition key (I don’t expect to store a lot of messages), a unique Guid as the row key, and of course the message. The AddMessage method adds this entity to the table, and then calls SaveChanges to send the new row to the table. This mechanism uses the same concepts as WCF Data Services.

In the previous post we created a web site with a textbox and a button. Implement the button’s click event as follows:

protected void postButton_Click(object sender, EventArgs e)
{
  string message = messageText.Text;
  var msg = MessageContext.CreateMessage(message);
  context.AddMessage(msg);
}

This will allow you to add messages to storage.

Before you can run this sample, you also need to setup the connection. Double-click the CloudMessages project beneath the Roles folder.

image

This open the project’s configuration window. Select the Settings tab and add a “DataConnection” setting, select “Connection String” as the type and then select your preferred storage account. In the beginning it is best to use development storage, and that is what I did here:

image

After running the web site you are of course wondering if your messages were actually added. So let’s add some code and UI to display the messages in the table.

Start by adding the following property to MessageContext:

public IQueryable<MessageEntity> Messages
{
  get { return CreateQuery<MessageEntity>(MessageTable); }
}

This property returns an IQueryable<MessageEntity>, which is then used by LINQ for writing queries. To actual query is performed in our web page class. But first we need to add some UI to display the messages. Add a repeater control beneath the TextBox and Button:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
  <p>
    <asp:TextBox ID="messageText" runat="server" Width="396px"></asp:TextBox>
    <asp:Button ID="postButton" runat="server" OnClick="postButton_Click" Text="Post message" />
  </p>
  <p>
    <asp:Repeater ID="messageList" runat="server">
      <ItemTemplate>
        <p>
          <%# ((MessagesLib.MessageEntity) Container.DataItem).Message %>
        </p>
      </ItemTemplate>
    </asp:Repeater>
  </p>
</asp:Content>

 

Now that we can display the messages, let’s add a LoadMessages method below the click event handler of the page:

private void LoadMessages()
{
  var query = from msg in context.Messages
                           select msg;
  messageList.DataSource = query.ToList()
                                .OrderBy(m => m.Timestamp)
                                .Take(10);
  messageList.DataBind();
}

Call this method in the Load event of the page:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    LoadMessages();
  }
}

 

And again in the button’s click event:

protected void postButton_Click(object sender, EventArgs e)
{
  string message = messageText.Text;
  var msg = MessageContext.CreateMessage(message);
  context.AddMessage(msg);
  LoadMessages();
}

 

Run. Add some messages, and see them listed (only the first 10 messages will be displayed, change to query as you like).


Comments (6) -

December 6. 2011 07:36 PM

ugg boots outlet

Good idea, I agree with your thoughts! Great features: I really like the Spanish proverb that claims, "A wealthy child usually sits inside a poor mother's lap.(<p><em><a title="cheap ugg boots" href="www.genuineuboots-australia.com/">cheap ugg boots</a></em>
<p><em><a title="ugg boots sale" href="www.genuineuboots-australia.com/">ugg boots sale</a></em>
<p><em><a title="ugg boots" href="www.genuineuboots-australia.com/">ugg boots</a></em>
<p><em><a title="uggs outlet" href="www.outletuggsaustraliasale.org/">uggs outlet</a></em>
<p><em><a title="uggs" href="www.outletuggsaustraliasale.org/.../em>;
<p><em><a title="cheap uggs" href="http://www.outletuggsaustraliasale.org/cheap uggs</a></em>)I wish I could remain at home with my young ones and work at home so I can be with my kids and generate a living,(<em><a title="ugg boots clearance" href="www.discount-uggbootsclearance.org/">ugg boots clearance</a></em>,<p>
<em><a title="ugg boots outlet" href="www.discount-uggboots-outlet.com/">ugg boots outlet</a></em>


) but I don't know in which to begin. Many women get up early, get the youngsters dressed, drop them off at day care, drive in rush-hour targeted visitors, and arrive at perform exhausted, considering, "There needs to be an improved way.Selecting to do the job in the home might be a tricky financial<p>

<em><a title="ugg boots" href="http://www.uggboots-outletonline.net/">ugg boots</a></em><p>
<em><a title="uggs clearance" href="http://www.uggs-salesclearance.com/">uggs clearance</a></em><p>
<em><a title="ugg boots clearance" href="http://www.uggs-salesclearance.com/">ugg boots clearance</a></em>

ugg boots outlet

December 14. 2011 01:20 PM

ugg boots jimmy choo starlit

Our philosophy : UGG boots[<em><a title="1873 uggs " href="www.clearanceuggsbootss.org/.../uggs-bailey-button-triplet-sand-boots-1873-p-2598.html">1873 uggs </a></em>] sold at reasonable prices. Our[<em><a title="uggs mini mel" href="www.clearanceuggsbootss.org/uggs-classic-mini-boots-c-70.html">uggs mini mel</a></em>] goal is to provide our customers mitden world’s best products at an outstanding value UGG[<em><a title="uggs classic tall" href="www.cheapsuggonsales.com/...-58.html">uggs classic tall</a></em>]. Siemayalways find[<em><a title="uggs classic short boot" href="www.cheapsuggonsales.com/...-59.html">uggs classic short boot</a></em>] a luxury one that can catch your eyes, the fact remains that the price is competitive.We are a professional online store discount Uggs[<em><a title="uggs mini on sale" href="www.cheapsuggonsales.com/...-70.html">uggs mini on sale</a></em>] exprienced in dealing in UGG boots. RabattUggs[<em><a title="bailey button uggs on sale" href="www.cheapsuggonsales.com/...0.html">bailey button uggs on sale</a></em>] our Online Store you just paid to all kinds of ugg boots[<em><a title="classic tall uggs on sale" href="www.uggsdiscountsales.net/classic-tall-uggs--c-58.html">classic tall uggs on sale</a></em>] you undstellen sure they can meet the high demands of our[<em><a title="classic short uggs black" href="www.uggsdiscountsales.net/classic-short-uggs--c-59.html">classic short uggs black</a></em>] customers’ needs. As our UGG[<em><a title="mini uggs on sale" href="www.uggsdiscountsales.net/...70.html">mini uggs on sale</a></em>] products fit your budget and your taste, Join us[<em><a title="bailey button triplet uggs cheap" href="www.uggsdiscountsales.net/bailey-button-triplet-uggs-c-78.html">bailey button triplet uggs cheap</a></em>].

ugg boots jimmy choo starlit

January 5. 2012 02:21 PM

Coach Outlet

The easiest way to tell if <a href="http://www.uscoach1941.com/">Coach Outlet</a> is, to look at the symmetry of the print on the bag. Any authentic <A href="http://www.uscoach1941.com/">Coach Online Outlet</A> will have a perfectly symmetrical print on both sides of the <A href="http://www.coachccbag.net/">Coach Factory Outlet</A>, right down the middle. What I see on some <A href="http://www.coachccbag.net/">Cheap Coach Bags</A> is that many times the print is off center, or if you look at the stitching make sure the print is perfectly symmetrical over the stitching. Another mistake is that sometimes they will have a single row of "C"s and then they will be flipped, but on all signature <A href="www.cheapcoltsjerseysnfl.net/">Cheap Colts Jersey</A>, even the op-art design there will always be two rows of "C"s and then two rows of "C"s, even down the side. The reason it is symmetrical is that an authentic <a href="http://www.uggshoes.cc/">UGG Boots Outlet</a> is made from one piece of leather wrapped around, while knockoffs put together <a href="http://www.north-face-outlet-store.com/">; North Face Outlet</a> from whatever pieces they can find to save money.

Coach Outlet

January 10. 2012 01:30 PM

china wholesale

Hi, the article is so wonderful, I am interested in it. I will pay attention to your articles. And I like <a href="http://www.withgoodsale.com/">cheap clothes</a> very much,they are in high quality  and inexpensive, so I think everyone will be interested in it,is it right? I have found a <a href="http://www.withgoodsale.com/">wholesale in china</a> online, there are China wholesaler.The  store was established for a long time.They have a good reputation,there are many <a href="http://www.withgoodsale.com/">cheap shoes</a> on their website.They provide wholesale price  and shipping to worldwide. So no matter where you are now, you also can order your goods at this  website. Especially the <a href="http://www.withgoodsale.com/">cheap clothing</a> ,they are my favorite!

china wholesale

January 10. 2012 01:30 PM

Belstaff Outlet

Do you like motorcycling and have your own motor equiments?You can come here <a href="www.newbelstaffonline.com/">Belstaff Outlet</a> to find your <a href="www.newbelstaffonline.com/">Belstaff Jacket</a>.<a href="www.newbelstaffonline.com/">Belstaff Coat</a> can not little.If your foot is cold,<a href="www.newbelstaffonline.com/">Belstaff Boots</a> is not bad.You can buy a <a href="www.newbelstaffonline.com/">Belstaff Bag</a> to hold those equipments.

Belstaff Outlet

January 11. 2012 12:21 AM

Coach Outlet

[url=http://www.coach-outlet-onlinee.org/]Coach Outlet[/url]
<h1><a href="http://www.coach-outlet-onlinee.org/"; title="Coach Outlet">Coach Outlet</a></h1>
<a href="http://www.coach-outlet-onlinee.org/"; title="Coach Outlet">Coach Outlet</a>
<h1><a href="www.coach-outlet-onlinee.org/">Coach Outlet</a></h1>
<a href="www.coach-outlet-onlinee.org/">Coach Outlet</a>

Coach Outlet

February 20. 2012 12:50 PM

linzhi

Burberry is the fashion brand from london ,england ,but the http://www.burberryonlinesale.org Burberry Bags  and burberry scarf are familar in the whole world. http://www.burberryonlinesale.org Burberry Online Sale official website has become running,you can buy all of burberry product there. Also you can buy something from the  http://www.burberryonlinesale.org Burberry Outlet  website,but they may be selling the copys not real one.

linzhi

May 7. 2012 06:46 PM

NHL hockey hats

For ladies who like the look of a gladiator boot/sandal, the <a href="http://www.rolex-wholesaler.com">rolex men</a> might just be the perfect choice.
<a href="http://www.cheaprolexsale.com">Rolex perpetual</a> has a strappy look about them with a flat bottom and buckles to adjust the straps coming up the leg and providing a great fit.
<a href="http://www.fashionnewera.us">snapback caps</a> has become one of the hottest and latest brands in the fashion industry today.
A favorite among the celebrities, hip hop artists and athletes, <a href="http://www.raybanoutlet.co.uk">rayban glasses</a> has gained tremendous popularity due to its unconventional and unique designs.
The <a href="www.raybanoutlet.co.uk/juicy-sunglasses">Juicy Sunglasses</a> line was a popular tattoo artist.
This brand resulted from the legendary French fashion designer who teamed up with the famous tattoo artist to introduce a high end <a href="www.rolex-wholesaler.com/rolex-day-dateii">Rolex Day DateII</a> brand.

NHL hockey hats

May 16. 2012 01:39 PM

north face denali jacket

<a href="www.northface-jacketoutlet.com/">North Face Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Denali Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Jacket Outlet </a>
  <a href="www.northface-jacketoutlet.com/">NorthFace Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">North Face Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">The North Face Denali Jacket</a>
  <a href="www.northface-jacketoutlet.com/">NorthFace Jackets Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">North Face Denali Jacket</a>
  <a href="www.northface-jacketoutlet.com/">North Face Denali Fleece Jacket</a>
  <a href="www.northface-jacketoutlet.com/">North Face Denali Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">North Face Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Denali Jackets</a>
  <a href="www.northface-jacketoutlet.com/">North Face Denali Fleece Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">NorthFace Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Outlet North Face Jacket</a>
  <a href="www.northface-jacketoutlet.com/">Outlet North Face</a>
  <a href="www.northface-jacketoutlet.com/">Outlet NorthFace</a>
  <a href="www.northface-jacketoutlet.com/">North Face Denali Fleece Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Denali Fleece Jacket Outlet</a>
  <a href="www.northface-jacketoutlet.com/">Wholesale North Face</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Denali Jacket</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Jacket</a>
  <a href="www.northface-jacketoutlet.com/">Cheap North Face Denali Jackets</a>
  <a href="www.northface-jacketoutlet.com/">Outlet Cheap North Face Denali Jacket</a>
  <a href="www.thenorthfacedenalijackets.com/">Cheap NorthFace Denali Jackets</a>
  <a href="www.thenorthfacedenalijackets.com/">Cheap North Face Denali Jackets </a>
  <a href="www.thenorthfacedenalijackets.com/">North Face Denali Fleece Jacket</a>
  <a href="www.thenorthfacedenalijackets.com/">Cheap The North Face Denali Jackets</a>
  <a href="www.thenorthfacedenalijackets.com//">The North Face Denali Jacket</a>
  <a href="www.thenorthfacedenalijackets.com/">NorthFace Denali Jackets</a>
  <a href="www.thenorthfacedenalijackets.com/">Cheap North Face Denali Fleece Jacket</a>
  <a href="www.thenorthfacedenalijackets.com/">North Face Denali Jackets</a>
  <a href="www.thenorthfacedenalijackets.com/">North Face Denali Fleece Jackets</a>
  <a href="www.thenorthfacedenalijackets.com/">North Face Denali Jacket</a>
  <a href="www.thenorthfacedenalijackets.com/">North Face Denali Fleece Jackets Outlets</a>
  <a href="www.thenorthfacedenalijackets.com/">Cheap North Face Denali Jackets</a>
  <a href="www.thenorthfacedenalijackets.com/">NorthFace Denali Fleece Jackets</a>
<a href="www.northfacejacketwholesale.com/">NorthFace Wholesale</a>
  <a href="www.northfacejacketwholesale.com/">Wholesale North Face </a>
  <a href="www.northfacejacketwholesale.com/">Wholesale NorthFace </a>
  <a href="www.northfacejacketwholesale.com/">North Face Jacket Wholesale</a>
  <a href="www.northfacejacketwholesale.com/">NorthFace Jacket Wholesale</a>
  <a href="www.northfacejacketwholesale.com/">Wholesale North Face Jacket</a>
  <a href="www.northfacejacketwholesale.com/">Wholesale NorthFace Jacket</a>
  <a href="www.northfacejacketwholesale.com/">Wholesale North Face Denali Jacket</a>
  <a href="www.northfacejacketwholesale.com/">Cheap North Face Wholesale</a>
  <a href="www.northfacejacketwholesale.com/">Cheap North Face Jacket </a>
  <a href="www.northfacejacketwholesale.com/">Cheap NorthFace Jacket Wholesale</a>
  <a href="www.northfacejacketwholesale.com/">Cheap North Face Jackets Outlet/a>

north face denali jacket

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Download the U2U brochure

Download Brochure

Receive the U2U Newsletter. Submit your email address:
 
 


 


Search

rss  RSS

Archive