Search code examples
azureazureservicebus

Is it possible to send data with ServiceBusMessage and to receive it with BrokeredMessage?


More precisely to send the data using Azure.Messaging.ServiceBus.ServiceBusMessage and to receive it with Microsoft.ServiceBus.Messaging.BrokeredMessage

I develop a brand new .NET Core 8.0 component and our queue subscribers are on .NET Fx 4.8. In the new component I would like to use the currently supported Azure.Messaging.ServiceBus to send messages. Unfortunately I could not find any info on how to send data to listeners that use WindowsAzure.ServiceBus.

For sending data through the queue from Microsoft.Azure.ServiceBus -> WindowsAzure.ServiceBus I already found this, thanks very much! https://github.com/Azure/azure-service-bus-dotnet/issues/239#issuecomment-320820562


Solution

  • Yes, this is possible and is detailed in the Service Bus Interop sample.

    To send from Azure.Messaging.ServiceBus and receive from WindowsAzure.ServiceBus, you would do:

    ServiceBusSender sender = client.CreateSender(queueName);
    
    // When constructing the `DataContractSerializer`, We pass 
    // in the type for the model, which can be a strongly typed 
    // model or some pre-serialized data.
    
    // If you use a strongly typed model here, the model properties
    // will be serialized into XML. Since JSON is more commonly used,
    // we will use it in our example, and specify the type as string, 
    // since we will provide a JSON string.
    
    var serializer = new DataContractSerializer(typeof(string));
    using var stream = new MemoryStream();
    XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream);
    
    // serialize an instance of our type into a JSON string
    string json = JsonSerializer.Serialize(new TestModel 
    {
        A = "Hello world", 
        B = 5, 
        C = true
    });
    
    // serialize our JSON string into the XML envelope using 
    // the DataContractSerializer
    serializer.WriteObject(writer, json);
    writer.Flush();
    
    // construct the ServiceBusMessage using the DataContract serialized JSON
    var message = new ServiceBusMessage(stream.ToArray());
    
    await sender.SendMessageAsync(message);
    

    (verbatim from the linked sample, with minor formatting changes)