SQL Attachments

Component: Sql Attachments
NuGet Package NServiceBus.Attachments.Sql (1.x)
This is a community maintained project
Target NServiceBus Version: 7.x

Introduction

Uses the SQL Attachments extension to store attachments for messages.

Prerequisites

An instance of SQL Server Express is installed and accessible as .\SqlExpress.

At startup each endpoint will create its required SQL assets including databases, tables and schemas.

The database created by this sample is NsbSamplesSqlAttachments.

Code Walk-through

Add to EndpointConfiguration

Enable attachments for an endpoint. A connection factory and a time to keep are required.

endpointConfiguration.EnableInstallers();
endpointConfiguration.EnableAttachments(
    connectionFactory: OpenConnection,
    timeToKeep: TimeToKeep.Default);

The consuming code is responsible for opening, and handling exceptions, for a SqlConnection

static async Task<SqlConnection> OpenConnection()
{
    var sqlConnection = new SqlConnection(connection);
    try
    {
        await sqlConnection.OpenAsync().ConfigureAwait(false);
        return sqlConnection;
    }
    catch
    {
        sqlConnection.Dispose();
        throw;
    }
}

Send a message with an attachment

var sendOptions = new SendOptions();
sendOptions.RouteToThisEndpoint();
var attachments = sendOptions.Attachments();
attachments.Add(
    name: "attachmentName",
    streamFactory: () =>
    {
        return File.OpenRead("fileToStream.txt");
    });

await endpoint.Send(new MyMessage(), sendOptions)
    .ConfigureAwait(false);

Read an attachment for a received message

public class MyHandler :
    IHandleMessages<MyMessage>
{
    static ILog log = LogManager.GetLogger<MyHandler>();

    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        log.Info("MyMessage received. Attachment will be streamed to the console.");
        var attachments = context.Attachments();
        return attachments.ProcessStream(
            name: "attachmentName",
            action: async stream =>
            {
                using (var reader = new StreamReader(stream))
                {
                    while (true)
                    {
                        var line = await reader.ReadLineAsync()
                            .ConfigureAwait(false);
                        if (line == null)
                        {
                            break;
                        }

                        Console.WriteLine(line);
                    }
                }
            });
    }
}

Last modified