Cross-device/cross-location Pub-Sub (part 2): Using Windows Azure Service Bus Topics & Subscriptions in Windows Phone (7.1)

In the previous post I showed how to use MonoTouch and C# on iOS devices to subscribe to the Windows Azure Service Bus’s topics and subscriptions features.

This time it is a Windows Phone (Mango) client app.

The sending / publishing application is still the same Console application from the last post:

image

And the nice part about the WP app is that Kellabyte already did the major work for wrapping the Service Bus queues, topics, and subscriptions REST API (also check out her awesome Continuous Client demo which uses the Service Bus). Smile

With her code in place the actual subscribing inside my WP app to the messages in my Service Bus subscriptions is a piece of cake:

   1:  public MainPage()
   2:  {
   3:      InitializeComponent();
   4:   
   5:      InitBroker();
   6:  }
   7:   
   8:  private void InitBroker()
   9:  {
  10:      token = new Token(sbNamespace, issuerName, issuerSecret);
  11:      token.Requested += new EventHandler<TokenEventArgs>(token_Requested);
  12:      token.Request();
  13:  }
  14:   
  15:  private void token_Requested(object sender, TokenEventArgs e)
  16:  {
  17:      topic = new Topic(token, topicName);
  18:   
  19:      RegisterMessagesHandler();
  20:  }
  21:   
  22:  private void RegisterMessagesHandler()
  23:  {
  24:      subscription = new Subscription(topic, subscriptionName);
  25:      subscription.MessageRecieved += 
  26:                    new EventHandler<SubscriptionMessageEventArgs>(
  27:                      subscription_MessageRecieved);
  28:      subscription.ReceiveMessage();
  29:  }
  30:   
  31:  private void subscription_MessageRecieved(object sender, SubscriptionMessageEventArgs e)
  32:  {
  33:      var message = e.Message;
  34:   
  35:      try
  36:      {
  37:          if (!String.IsNullOrWhiteSpace(message))
  38:          {
  39:              Dispatcher.BeginInvoke(() =>
  40:              {
  41:                  mainContentPanel.RowDefinitions.Add(
  42:                      new RowDefinition { Height = new GridLength(35) });
  43:   
  44:                  var pos = mainContentPanel.RowDefinitions.Count - 1;
  45:   
  46:                  var txt = new TextBlock();
  47:                  txt.Text = message;
  48:                  mainContentPanel.Children.Add(txt);
  49:                  Grid.SetColumn(txt, 0);
  50:                  Grid.SetRow(txt, pos);
  51:              });
  52:          }
  53:      }
  54:      catch (Exception ex)
  55:      {
  56:          Console.WriteLine(ex);
  57:      }
  58:   
  59:      subscription.ReceiveMessage();
  60:  }


And the (again) super spectacular result is that all the messages are being sucked from my subscription and displayed on the phone:

image

Voila. Sorry – not so exciting as last time. Anyway, here is the download:


Hope this helps.