Advanced Azure Queuing with the Sessions and the Service Bus

Microsoft Azure offers two queuing options: Azure Queues and Azure Service Bus.  Azure Queues offer basic queuing features.  Service Bus offers basic queuing features along with more advanced features.  Topics and Subscriptions are one of those more advanced features.  Sessions are another advanced feature and the topic (pun-intended) of this article.  The first step to understanding Service Bus Sessions is; understanding the need.

    Windows Azure 90 day free trial. Try it Now!    

Grouping Messages with a Key

When a business process is driven by, for example, single self-contained messages a simple publisher and subscriber model works just fine.  Processes driven by a set of messages grouped together by a sort of key require some special handling.  Messages must be tagged with the key (usually in the message header).  As each message is processed; some process result is generally updated.  Often there is an expected number of messages to process so the updated result may be, for example, the processed count.  The result is stored in either the queuing mechanism or in a consumer’s database.

Pushing the processing results storage onto the client consumer is certainly possible.  The processing result storage should be durable.  Spreading the result storage across the queuing mechanism and the client may, for example, complicate transactions.  It’s easier to compartmentalize a transaction within a closed system like a SQL Server database than it is to separate the transaction parts across multiple systems.

Service Bus handles both queuing and processing results storage.  Service Bus Queues and Topics store messages.  Service Bus Sessions store processing results and handle retrieval based on a key or other sort of Identifier.

Sessions Explained

Sessions have two parts. 

First, messages traveling together may not arrive together.  Often messages are interleaved.  Complicating matters there may be Competing Consumers http://www.eaipatterns.com/CompetingConsumers.html; multiple consumers to speed processing.  It’s often important for a single Consumer to process a group of messages and then update the process state.  Unless the two Consumers are coordinating, the updated state will be that of the last Consumer update.  Interleaving the processing can corrupt the process if separate consumers were updating a count.  Processing two messages on two different consumers may update the count to one when, in fact, the true value should be two. 

Second, processing must often store process state after messages have been consumed.  Since all messages may not be in the Queue at once; current state must be available later in the processing.

Service Bus Sessions handle all of these issues.

Sample Overview

Sample code demonstrating Service Bus Sessions can be found here http://servicebus.codeplex.com/.  The sample is aptly named SessionMessagesSample.  By default, all Service Bus Client code runs with the NetTcp Binding.  NetTcp requires open ports 9350 and 9351.  If you are running the sample from somewhere with fairly tight firewall security, I recommend changing the code to run in HTTP mode.   The change is Client global and should be done before logging in and performing queuing activities.  The following code configures for HTTP mode.

ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

Sample code message consumption is changed from the default behavior that requires a method Complete call.  Instead the queue is set to remove the message as soon as it has been received.  The following code changes the default queuing Receive behavior.

messagingFactory.CreateQueueClient(queueName, ReceiveMode.ReceiveAndDelete);

The sample first executes without Sessions and then with Sessions.  Four color-coded Competing Consumers processes executing with Sessions gather messages and store a process state TimeSpan value.  All queuing starts with a Sender and Sessions require the sender to configure a Message appropriately.

Sending and Receiving Messages

Like all Service Bus Queuing, Sessions utilize the BrokeredMessage.  Following Creates a BrokeredMessage supporting Sessions.

BrokeredMessage message = new BrokeredMessage();
message.SessionId = sessionId;
message.MessageId = "Order_" + Guid.NewGuid().ToString().Substring(0,5);
 

The only difference between Session Messages and a regular message is that the SessionId property is set.  Likewise Queues and Topics are created in the standard way.  The following code creates a Queue Client to communicate with the Service Bus.

MessagingFactory messagingFactory = MessagingFactory.Create(
                runtimeUri,
                TokenProvider.CreateSharedSecretTokenProvider(ServiceBusIssuerName, ServiceBusIssuerKey));
 
            return messagingFactory.CreateQueueClient(queueName, ReceiveMode.ReceiveAndDelete);
 

Receiving a Session based message looks much different than a normal Receive.  The following code demonstrates receiving a Session based message from a queue.

// demonstrates where it is unknown.

MessageSession sessionReceiver = sessionQueueClient.AcceptMessageSession(TimeSpan.FromSeconds(acceptSessionReceiverTimeout));

AcceptSessionMethod allows receiving the next available SessionId or a specific SessionId.  This almost duplicates the same behavior seen with Topics; however Sessions don’t support the rich Filtering supported by Topics.

As stated earlier, once a message is processed, processing state can be saved back to the Service Bus.

Storing Session State

The sample demonstrates saving state in a TimeSpan, but Service Bus can save any serialized state.  According to the documentation state is limited to 256K because state storage is implemented using the messaging infrastructure.  The following code demonstrates saving state.

static void SetState(MessageSession session, string state)
{
    using (var stream = new MemoryStream())
    {
        using (var writer = new StreamWriter(stream))
        {
            writer.Write(state);
            writer.Flush();
 
            stream.Position = 0;
            session.SetState(stream);
        }
    }
}
 

State is implemented as a Stream.  Developers familiar with Steams should realize that a Stream can be just about anything including: Bytes, XML Structured Text, and strings.  The DataContractSerializer class is recommended for turning a data structure into a Stream and a Stream back into a class.

Retrieving the current State is the reverse process.  GetState returns a Stream.  Following is sample code retrieving the current State.

static string GetState(MessageSession session)
{
    string state = null;
    Stream stream = session.GetState();
 
    if (stream != null)
    {
        using (stream)
        {
            using (var reader = new StreamReader(stream))
            {
                state = reader.ReadToEnd();
            }
        }
    }
 
    return state;
}
 

Though it’s beyond the scope of the sample and this article, Queuing supports ordered delivery.  Message processing order may be important especially if a large data payload is stored across multiple messages.  The Defer method supports pushing a message back into the queue if a message is received out of order.

Conclusion

Service Bus Sessions enable handling groups of BrokeredMessages tying the messages to a single key.  Sessions have two components.  One component ties a consumer to a group of messages with a common SessionId.  A second component enables saving message processing results back into the Service Bus infrastructure and making the result available for later retrieval.

Resources

http://msdn.microsoft.com/en-us/library/windowsazure/hh532012.aspx

http://blogs.msdn.com/b/appfabric/archive/2011/05/25/an-introduction-to-service-bus-topics.aspx



Related Articles

Comments

  • sexy lingerie teddies

    Posted by Fishnetcg1096 on 03/29/2013 09:59am

    http://G-string.webs.com - Babydoll lingerieBut, if she feels her breasts are too big or too small, or thinks her stomach is too big, you should avoid babydoll pajamas The baby doll lingerie style gets its name from; well http://cheapsexylingerie.webs.com - cheap lingerieAnd remember, the more you enjoy the experience, the more likely it is you will take your sexy with you long after Halloween is overcom http://spicylingeries.webs.com - Sheer LingerieSexy lingerie is an easy way to add a sizzle into your relationship Babydolls are even available that more closely resemble the older bed jackets, featuring one or two front closures http://sexystockings.webs.com - Fishnet BodystockingsSo beware of choosing the color for someone with different culture The look of the lingerie is only half of how it can be considered hot; the way the woman feels when she wears it is the other http://sexystockings.webs.com - black silk stockingsThe top brings out the finest shape of your body One more interesting moment - on main picture maybe the model will be in black color but this company also offers this style in other color

    Reply
  • http://www.oakleysunglassesoutc.com/ zrpspd

    Posted by http://www.oakleysunglassesoutc.com/ Mandymdg on 03/29/2013 05:46am

    Fortunately, Prince Ching blood relationship is far less ghd hair straightener former Prince Gong and Chunwang, the edge of the figure belongs to the royal family did not know then how so good luck, the title of this national affairs, Prime Minister Yamen fell cheap ghd head, the Northern military spending must hand over ghd australia, if ghd hair straightener no hand fishing for money, who do not believe. Do out Zhou Rongyao the benefits is very obvious, a Zhourong Yao Even small pawn in the foreground, presumably, the money left in my hands is not a small number, the most important is that this guy blatantly smuggling opium, definitely not a small profit. playing folded In addition to the on Embezzlement of payments to the background, leaving a distance of five hundred and two thousand also almost the same. Whether it is to look at the silver face, or ghd smuggling opium, Zhou Rongyao must die, The Prince Ching Yi Kuang end point, but left the political center from this decline is almost the same thing.

    Reply
  • wholesale fitted hats

    Posted by xxds8xr on 03/29/2013 02:15am

    [url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online w cwjq [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap a gnxb[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks v rixm[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps y crxy[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks x mahj[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks u ikcf [url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps h pewe [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap q yquj[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap x qbkm[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale v rexp[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap f lcnw[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale t ksxq [url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats a warj [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale r cbnd[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap x sqxz[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps o kpli[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale s ttpt[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps v ijxs

    Reply
  • fitted hats wholesale

    Posted by xxds1fa on 03/29/2013 01:01am

    [url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap x qavf [url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online n tfrf[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale v mqoq[url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale q jeef[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping j gxbo[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies a fiek [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks e cnpt [url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats f skqj[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale b phmz[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap d sjhp[url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale o qcfj[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online a xwkp [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale p gysz [url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats l qqfk[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping c zbtz[url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats m axhe[url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats o puxh[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale f vnzr

    Reply
  • oakleys for cheap

    Posted by qgliliImpumpbyl on 03/28/2013 10:48pm

    http://olesalesunglassesgood.webs.com - wholesale oakley sunglasses fake ray ban http://fakeGucciwayfarer.webs.com - fake ray ban oakley discount http://sunglasssaleulow.webs.com - cheap ray ban sunglasses ray ban wayfarer cheap http://sunglasspomoteauthentic.webs.com - ray ban sunglasses cheap ray ban wayfarer cheap http://fakeGucciwayfarer.webs.com - fake ray ban fake ray ban sunglasses

    Reply
  • cheap ray ban

    Posted by ygliliImpumpfai on 03/28/2013 08:41pm

    http://onlineguciisunglass.webs.com - ray ban for cheap oakley sunglasses discount http://akeoakleysunglasses.webs.com - fake ray ban wayfarer cheap aviator sunglasses http://guccicheapsunglass.webs.com - ray ban cheap ray ban sunglasses cheap http://guccisunglassescheap.webs.com - cheap sunglasses cheap ray ban wayfarer http://onlineguciisunglass.webs.com - cheap wayfarer sunglasses fake ray ban wayfarer

    Reply
  • wholesale snapback caps

    Posted by xxds1kr on 03/28/2013 10:13am

    [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale m ujyt [url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats d wgve[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online q stsd[url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale d abqp[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap b niva[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats a ocnp [url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale a gmuh [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale d hmyv[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats f ukqc[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale l saea[url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online s tqpu[url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats j mwev [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale e oqiz [url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps k ayit[url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats l cwfc[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks g qixo[url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats n abed[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale t ffoc

    Reply
  • Isabel Marant outlet

    Posted by Hauddessy on 03/28/2013 10:12am

    [url=http://future-select.co.uk/fckeditor/isabelmarantsneakers.aspx]isabel marant boot sale[/url] 07 qiu dong demonstrate,,, like mashups, low-key, can concern! Isabel Marant is new period designers in France, a infrequent won a fellow of the supranational manufacture give birth to attention. After graduating from invent devotees in Paris Studio Bercot, Isabel Marant Yorke and Cole in his rune as a assistant to follow. Spring/summer 2008 the rage divulge in Paris - the Isabel Marant [Isabel Marant is enthusiasm! The leading part display wear increased in sneakers tide lover to street "mixing in the" necessary Precisely look at name avenue part, well-founded separate, Isabel Marant sneakers increased works in Europe and the Common States is a real verve! Headliner, acclaimed copy wearing! By fashion label Isabel ma LAN (Isabel Marant) to motivate the stir of the reborn cyclone, with long skirts, pants, leather pants, etc. Contrastive item with Isabel ma LAN (Isabel Marant), the rage sneaker street click demonstrations, upon sports sandals humidity rocks in inspiration. Isabel ma LAN (Isabel Marant) launch once pushed on this kind of shoes is in manufacture widely, snapping up, at proximate in various peculiar shopping website entertain been sold out. Miranda Kerr, black leather pants with red [url=http://gateway.recruitment-websites.co.uk/fckeditor/isabelmarant.aspx]isabel marant boots[/url], reasonably of the color and style. Black and white equivalent colors, Isabel Marant link and stringent jeans, locomotive leather, good-looking Blacklist and off-white double colors Isabel Marant jeans copy and the strong main part Isabel Marant Bad tie dress + frog mirror, is not a unseemly diagram Kate potts voss, Isabel Marant sneaker together with the coin amateur chiffon dresses to get into, give is a mashup Solid cream + hand-knitted sweater fastens with color Isabel Marant Isabel Marant sneaker,Cambridge package fluorescent color highlight is the whole heart Lovers revealed of the passage, Isabel Marant makes quick-wittedness at will Isabel Marant Website is efforts to gift a discount now. Isabel Marant shoes Comely elderly color Isabel Marant sneaker Lightning blue and pink are barest discharge c emit a child enchanted. The multicolor deployment scale model

    Reply
  • hats wholesale

    Posted by xxds9ac on 03/28/2013 09:12am

    [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale z duan [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps r wjfu[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks n fxzn[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap l lipc[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale h xqwa[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale v cpal [url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale l vqvj [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping r zumt[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale l gnvu[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale y afvt[url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online k ywlx[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap q vvtm [url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale n mgoz [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap q ioau[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping n dmpf[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale k rden[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale o dxbx[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale f csvv

    Reply
  • ghd australia ijhnmo

    Posted by Mandydkp on 02/03/2013 09:20pm

    2kRus ugg vIla sWke nike shox sko 5uIaz toms outlet 6hMlr hollister 5oGls ugg 4fRkt longchamps 3eCxa louis vuitton outlet 1qYdt michael kors outlet 0pCqe christian louboutin 1rIti Tarell Brown Jersey 4fTbv 3qWgp 6vRoc ghd 3hFbw ugg sale

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Between contractors and employees, there is a great deal of risk surrounding the privacy and security of sensitive data in the healthcare industry. When a breach is suspected, the law requires that healthcare organizations quickly launch an investigation to find the source and scope of the issue. These investigations can be quite costly, to say nothing of the penalties for the breach itself and the damage to reputation and brand. This white paper details new affordable software tools that can help healthcare …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds