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; 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  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(
                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))
            stream.Position = 0;

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.


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.


Related Articles


  • sexy lingerie teddies

    Posted by Fishnetcg1096 on 03/29/2013 09:59am - 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 - 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 - 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 - 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 - 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

  • zrpspd

    Posted by 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.

  • wholesale fitted hats

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

    [url=]cheap hats online[/url] cheap hats online w cwjq [url=]snapback hats cheap[/url] snapback hats cheap a gnxb[url=]cheap snapbacks[/url] cheap snapbacks v rixm[url=]wholesale baseball caps[/url] wholesale baseball caps y crxy[url=]wholesale snapbacks[/url] wholesale snapbacks x mahj[url=]cheap snapbacks[/url] cheap snapbacks u ikcf [url=]wholesale snapback caps[/url] wholesale snapback caps h pewe [url=]snapback hats cheap[/url] snapback hats cheap q yquj[url=]snapback hats cheap[/url] snapback hats cheap x qbkm[url=]hats wholesale[/url] hats wholesale v rexp[url=]snapback hats cheap[/url] snapback hats cheap f lcnw[url=]snapbacks wholesale[/url] snapbacks wholesale t ksxq [url=]wholesale snapback hats[/url] wholesale snapback hats a warj [url=]snapback wholesale[/url] snapback wholesale r cbnd[url=]snapback hats cheap[/url] snapback hats cheap x sqxz[url=]wholesale baseball caps[/url] wholesale baseball caps o kpli[url=]hats wholesale[/url] hats wholesale s ttpt[url=]wholesale baseball caps[/url] wholesale baseball caps v ijxs

  • fitted hats wholesale

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

    [url=]snapback hats cheap[/url] snapback hats cheap x qavf [url=]cheap hats online[/url] cheap hats online n tfrf[url=]hats wholesale[/url] hats wholesale v mqoq[url=]cheap hats for sale[/url] cheap hats for sale q jeef[url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping j gxbo[url=]wholesale beanies[/url] wholesale beanies a fiek [url=]cheap snapbacks[/url] cheap snapbacks e cnpt [url=]wholesale hats[/url] wholesale hats f skqj[url=]fitted hats wholesale[/url] fitted hats wholesale b phmz[url=]snapback hats cheap[/url] snapback hats cheap d sjhp[url=]cheap hats for sale[/url] cheap hats for sale o qcfj[url=]cheap snapbacks online[/url] cheap snapbacks online a xwkp [url=]snapback wholesale[/url] snapback wholesale p gysz [url=]cheap snapbacks hats[/url] cheap snapbacks hats l qqfk[url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping c zbtz[url=]wholesale hats[/url] wholesale hats m axhe[url=]wholesale fitted hats[/url] wholesale fitted hats o puxh[url=]cheap snapbacks for sale[/url] cheap snapbacks for sale f vnzr

  • oakleys for cheap

    Posted by qgliliImpumpbyl on 03/28/2013 10:48pm - wholesale oakley sunglasses fake ray ban - fake ray ban oakley discount - cheap ray ban sunglasses ray ban wayfarer cheap - ray ban sunglasses cheap ray ban wayfarer cheap - fake ray ban fake ray ban sunglasses

  • cheap ray ban

    Posted by ygliliImpumpfai on 03/28/2013 08:41pm - ray ban for cheap oakley sunglasses discount - fake ray ban wayfarer cheap aviator sunglasses - ray ban cheap ray ban sunglasses cheap - cheap sunglasses cheap ray ban wayfarer - cheap wayfarer sunglasses fake ray ban wayfarer

  • wholesale snapback caps

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

    [url=]snapback wholesale[/url] snapback wholesale m ujyt [url=]wholesale snapback hats[/url] wholesale snapback hats d wgve[url=]cheap snapbacks online[/url] cheap snapbacks online q stsd[url=]cheap hats for sale[/url] cheap hats for sale d abqp[url=]snapback hats cheap[/url] snapback hats cheap b niva[url=]cheap snapbacks hats[/url] cheap snapbacks hats a ocnp [url=]hats wholesale[/url] hats wholesale a gmuh [url=]fitted hats wholesale[/url] fitted hats wholesale d hmyv[url=]cheap hats[/url] cheap hats f ukqc[url=]snapbacks wholesale[/url] snapbacks wholesale l saea[url=]cheap snapbacks online[/url] cheap snapbacks online s tqpu[url=]wholesale snapback hats[/url] wholesale snapback hats j mwev [url=]snapback hats wholesale[/url] snapback hats wholesale e oqiz [url=]wholesale snapback caps[/url] wholesale snapback caps k ayit[url=]wholesale fitted hats[/url] wholesale fitted hats l cwfc[url=]wholesale snapbacks[/url] wholesale snapbacks g qixo[url=]wholesale snapback hats[/url] wholesale snapback hats n abed[url=]snapbacks wholesale[/url] snapbacks wholesale t ffoc

  • Isabel Marant outlet

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

    [url=]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=]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

  • hats wholesale

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

    [url=]fitted hats wholesale[/url] fitted hats wholesale z duan [url=]wholesale baseball caps[/url] wholesale baseball caps r wjfu[url=]cheap snapbacks[/url] cheap snapbacks n fxzn[url=]snapbacks for cheap[/url] snapbacks for cheap l lipc[url=]snapback hats wholesale[/url] snapback hats wholesale h xqwa[url=]snapbacks wholesale[/url] snapbacks wholesale v cpal [url=]fitted hats wholesale[/url] fitted hats wholesale l vqvj [url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping r zumt[url=]snapback wholesale[/url] snapback wholesale l gnvu[url=]snapbacks wholesale[/url] snapbacks wholesale y afvt[url=]cheap snapbacks online[/url] cheap snapbacks online k ywlx[url=]snapback hats cheap[/url] snapback hats cheap q vvtm [url=]fitted hats wholesale[/url] fitted hats wholesale n mgoz [url=]snapback hats cheap[/url] snapback hats cheap q ioau[url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping n dmpf[url=]snapback hats wholesale[/url] snapback hats wholesale k rden[url=]snapback hats wholesale[/url] snapback hats wholesale o dxbx[url=]snapback hats wholesale[/url] snapback hats wholesale f csvv

  • 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

  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date