2
votes

Is there any way (and if so, what is the best method) of subscribing to a service bus queue to receive notifications when a message appears from a Xamarin app?

I've used this sample in a console app and it works well, but dont seem to be able to instantiate a QueueClient in my Xamarin Forms PCL desipite adding a reference to the WindowsAzure.ServiceBug Nuget package without any problem:

Console.WriteLine("Receive critical messages. Ctrl-C to exit.\n");
var connectionString = "{service bus listen string}";
var queueName = "{queue name}";

var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

client.OnMessage(message =>
    {
        Stream stream = message.GetBody<Stream>();
        StreamReader reader = new StreamReader(stream, Encoding.ASCII);
        string s = reader.ReadToEnd();
        Console.WriteLine(String.Format("Message body: {0}", s));
    });

Console.ReadLine();

Is there a preferred way of doing it in Xamarin?

Edit:

To be clear, I don't want to post messages to the queue but subscribe to it and receive notifications efficiently when a message appears. I can use the REST Api, but then I'll have to continually poll for updates which seems quite inefficient.

Edit 2:

I've tried using Long Polling but that doesn't really work with a service bus queue as the poll returns almost immediately with a '204 No Content' which means I'm still hitting the queue continually. Using the SDK I can just wait for a message and get notified via my subscription

Thanks

1
Thanks @Thomas, but I dont want to push a message to the queue. I want to subscribe in the most efficient way possible and ideally without having to continually poll the service bus queue from the client - LDJ
Were you ever able to get this working. I hit the same roadblock. - Scott Nimrod

1 Answers

0
votes

If I understand correctly, the SDK that you mentioned is not suit for the Xamarin platform. Please have a try to use Microsoft.Azure.ServiceBus. It is a prerelease version.

If we want to continually poll the service bus queue from the client, please have a try to use following code :

  var queueClient = new QueueClient(connectionstring, queueName, ReceiveMode.PeekLock);

  // Register a OnMessage callback
  queueClient.RegisterMessageHandler(
        async (message, token) =>
        {
          // Process the message
          string messageBody = Encoding.UTF8.GetString(message.Body);

          // Complete the message so that it is not received again.
          // This can be done only if the queueClient is opened in ReceiveMode.PeekLock mode.
          await queueClient.CompleteAsync(message.SystemProperties.LockToken);
                },new MessageHandlerOptions
                {
                     MaxConcurrentCalls = 1, AutoComplete = false 
                });