2

I want to check the azure servicebus/iothub constantly for messages. However, when I do it like this I get the following error

"An exception of type 'Amqp.AmqpException' occurred in mscorlib.dll but was not handled in user code Additional information: Operation 'Receive' is not valid under state: End."

Any ideas how I should implement constant pulling of messages and/or resolve this error?

var connection = new Connection(address);
var session = new Session(connection);
var entity = Fx.Format("/devices/{0}/messages/deviceBound", _deviceId);

var receiveLink = new ReceiverLink(session, "receive-link", entity);
while (true)
{
    await Task.Delay(1000);

    var message = await receiveLink.ReceiveAsync();
    if (message == null) continue;
    //else do things with message
 }
discy
  • 410
  • 3
  • 13
  • How do u authenticate? Do u put CBS token after establishing connection but before opening a session? Check it out: https://github.com/ppatierno/codesamples/blob/master/IoTHubAmqp/IoTHubAmqp/Program.cs – Helikaon Apr 07 '16 at 21:48

1 Answers1

0

From the endpoint you're using it looks like you're talking about receiving cloud-to-device (c2d) messages, in other words, the code you're writing runs on the device, and is meant to receive messages sent through the service to this device, right?

The simplest way of doing this is using the DeviceClient class of the C# SDK. An example of how to use this class is provided in the DeviceClientAmqpSample project.

Once you create your DeviceClient instance using your device connection string, the DeviceClient class has a ReceiveAsync method that can be used to receive messages.

var deviceClient = DeviceClient.CreateFromConnectionString("<DeviceConnectionString>");
while(true)
{
    await Task.Delay(1000);
    var receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
    if (receivedMessage != null)
    {
        var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
        Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
        await deviceClient.CompleteAsync(receivedMessage);
    }
}
  • The official Nuget package only works on Windows as far as I know. He uses AMQP.Net lite which runs on more platforms – Helikaon Apr 07 '16 at 21:50
  • There are Nuget packages for Xamarin now too (PCL). Works on Windows, iOS, Android, UWP and Windows Phone 8. AMQPNetlite indeed has support for even more platforms. – pierreca - MSFT Apr 07 '16 at 23:51
  • Yes, but those PCLs only support HTTP, as far as I know. – Helikaon Apr 08 '16 at 04:17
  • Helikaon is right. The Microsoft Azure libraries are not supported on mono (Raspberry). That's why I need to use AMQP.Net lite. – discy Apr 09 '16 at 10:45