﻿# Azure Storage Queues transport native integration sample

<!-- Version variant: asqn_13; default: [/samples/azure/native-integration-asq/index.md](/samples/azure/native-integration-asq/index.md) -->


## Prerequisites

Ensure an instance of the [Azurite Storage Emulator](https://github.com/Azure/Azurite) is running.


## Azure Storage Queues transport

This sample uses the [Azure Storage Queues transport](/transports/azure-storage-queues/index.md).


## Code walk-through

This sample shows a simple two-endpoint scenario.

 * `NativeSender` sends a `NativeMessage` message to `Receiver`
 * `Receiver` receiving and printing out the contents of the received message.


### Sending a native message

`NativeSender` creates and sends a queue message with a JSON serialized `NativeMessage` payload.

<!-- snippet: send-a-native-message -->

```cs
var nativeMessage = new NativeMessage
{
    NativeMessageId = Guid.NewGuid(),
    Content = $"Hello from native sender @ {DateTimeOffset.Now}"
};

var serializedMessage = JsonSerializer.Serialize(nativeMessage);

await queueClient.SendMessageAsync(serializedMessage);
```

<!-- endsnippet -->


## Receiving a native message

To process a native message, the native `QueueMessage` has to be adapted to the NServiceBus `MessageWrapper` first. To accomplish this, a [custom envelope unwrapper](/transports/azure-storage-queues/native-integration.md) must be registered to provide the following:
1. Message ID to associate with the incoming message
1. Serialized message payload as a byte array
1. Determine the native message type and assign it as an NServiceBus header

<!-- snippet: Native-message-mapping -->

```cs
transport.MessageUnwrapper = message =>
    message.MessageText.Contains("NativeMessageId") &&
    message.MessageText.Contains("Content")
    ? new MessageWrapper
    {
        Id = message.MessageId,
        Body = message.Body.ToArray(),
        Headers = new Dictionary<string, string>
        {
            { Headers.EnclosedMessageTypes, typeof(NativeMessage).FullName }
        }
    }
    : null; // not a raw native message - allow the framework to deal with it
```

<!-- endsnippet -->

> [!NOTE]
> Message type could be determined dynamically by reading the payload if different message types are sent natively.
