Example #1
0
        /// <summary>
        /// Inserts a new queued message into the database
        /// </summary>
        /// <param name="queuedMessage">The queued message to insert</param>
        /// <param name="cancellationToken">(Optional) A cancellation token through which the
        /// caller can request cancellation of the insert operation</param>
        /// <returns>Returns a task that completes when the insert operation completes</returns>
        protected virtual async Task InsertQueuedMessage(QueuedMessage queuedMessage, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message       = queuedMessage.Message;
            var principal     = queuedMessage.Principal;
            var expires       = message.Headers.Expires;
            var connection    = ConnectionProvider.GetConnection();
            var securityToken = await SecurityTokenService.NullSafeIssue(principal, expires);

            var persistedMessage = message.WithSecurityToken(securityToken);

            if (MessageEncryptionService != null)
            {
                persistedMessage = await MessageEncryptionService.Encrypt(message);
            }
            try
            {
                var headers        = persistedMessage.Headers;
                var commandBuilder = CommandBuilders.NewInsertQueuedMessageCommandBuilder();
                commandBuilder.MessageId   = headers.MessageId;
                commandBuilder.QueueName   = QueueName;
                commandBuilder.Origination = headers.Origination?.ToString();
                commandBuilder.Destination = headers.Destination?.ToString();
                commandBuilder.ReplyTo     = headers.ReplyTo?.ToString();
                commandBuilder.Expires     = headers.Expires;
                commandBuilder.ContentType = headers.ContentType;
                commandBuilder.Headers     = SerializeHeaders(headers);
                commandBuilder.Content     = persistedMessage.Content;

                using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var command = commandBuilder.BuildDbCommand(connection))
                    {
                        await command.ExecuteNonQueryAsync(cancellationToken);
                    }
                    scope.Complete();
                }
            }
            finally
            {
                ConnectionProvider.ReleaseConnection(connection);
            }
        }