public void Send(TransportMessage toSend, IEnumerable <string> destinations)
 {
     TransactionWrapper.RunInTransaction(transaction => {
         toSend.TimeSent       = DateTime.UtcNow;
         toSend.ReturnAddress  = this.ReturnAddress;
         var serializedMessage = string.Empty;
         using (var stream = new MemoryStream()) {
             TransportMessageSerializer.Serialize(toSend, stream);
             foreach (var destination in destinations)
             {
                 var conversationHandle = ServiceBrokerWrapper.SendOne(transaction, ReturnAddress, destination, NServiceBusTransportMessageContract, NServiceBusTransportMessage, stream.ToArray());
                 toSend.Id = conversationHandle.ToString();
                 if (Logger.IsDebugEnabled)
                 {
                     Logger.Debug(string.Format("Sending message {0} with ID {1} to destination {2}.\n" +
                                                "ToString() of the message yields: {3}\n" +
                                                "Message headers:\n{4}",
                                                toSend.Body[0].GetType().AssemblyQualifiedName,
                                                toSend.Id,
                                                destination,
                                                toSend.Body[0],
                                                string.Join(", ", toSend.Headers.Select(h => h.Key + ":" + h.Value).ToArray())
                                                ));
                 }
             }
         }
     });
 }
 private void InitServiceBroker()
 {
     TransactionWrapper.RunInTransaction(transaction => {
         // Ensure the service and queue exist
         ServiceBrokerWrapper.CreateServiceAndQueue(transaction, ReturnAddress, ListenerQueue);
     });
 }
        private void Process()
        {
            releasedWaitLock = false;
            needToAbort      = false;
            messageId        = string.Empty;

            try {
                transactionWaitPool.WaitOne();
                TransactionWrapper.RunInTransaction(transaction => {
                    ReceiveMessage(transaction);
                });
                ClearFailuresForMessage(messageId);
            } catch (AbortHandlingCurrentMessageException) {
                //in case AbortHandlingCurrentMessage was called
                //don't increment failures, we want this message kept around.
                return;
            } catch (Exception e) {
                var originalException = e;

                if (e is TransportMessageHandlingFailedException)
                {
                    originalException = ((TransportMessageHandlingFailedException)e).OriginalException;
                }

                IncrementFailuresForMessage(messageId, originalException);
                Logger.Error("Error Procesing Message", originalException);
                OnFailedMessageProcessing(originalException);
            } finally {
                if (!releasedWaitLock)
                {
                    transactionWaitPool.Release(1);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// This is a special helper method which will cause the transport to receive messages as if they came off the bus
        /// </summary>
        public void ReceiveMessages(object[] messages, IEnumerable <HeaderInfo> headers)
        {
            needToAbort = false;
            messageId   = string.Empty;
            try
            {
                TransactionWrapper.RunInTransaction(transaction =>
                {
                    var transportMessage = new TransportMessage()
                    {
                        Id = Guid.NewGuid().ToString(),
                        IdForCorrelation = Guid.NewGuid().ToString(),
                        Body             = messages,
                        TimeSent         = DateTime.UtcNow,
                        MessageIntent    = MessageIntentEnum.Send,
                        Headers          = headers.ToList(),
                    };

                    //care about failures here
                    var exceptionFromMessageHandling = OnTransportMessageReceived(transportMessage);

                    //and here
                    var exceptionFromMessageModules = OnFinishedMessageProcessing();

                    //but need to abort takes precedence - failures aren't counted here,
                    //so messages aren't moved to the error queue.
                    if (needToAbort)
                    {
                        throw new AbortHandlingCurrentMessageException();
                    }

                    if (exceptionFromMessageHandling != null) //cause rollback
                    {
                        throw exceptionFromMessageHandling;
                    }

                    if (exceptionFromMessageModules != null) //cause rollback
                    {
                        throw exceptionFromMessageModules;
                    }
                });
            }
            catch (AbortHandlingCurrentMessageException)
            {
                //in case AbortHandlingCurrentMessage was called
                //don't increment failures, we want this message kept around.
                return;
            }
            catch (Exception e)
            {
                var originalException = e;
                if (originalException is TransportMessageHandlingFailedException)
                {
                    originalException = ((TransportMessageHandlingFailedException)e).OriginalException;
                }
                OnFailedMessageProcessing(originalException);
                throw;
            }
        }
        private void Process()
        {
            messageContext = new MessageReceiveProperties();
            var wrapper = new TransactionWrapper();

            wrapper.RunInTransaction(() => Receive(messageContext), isolationLevel, transactionTimeout);
            ClearFailuresForMessage(messageContext.MessageId);
            messageContext = null;
        }
Esempio n. 6
0
 private void InitSqlServerQueue()
 {
     TransactionWrapper.RunInTransaction(transaction =>
     {
         using (var cmd = transaction.Connection.CreateCommand())
         {
             cmd.Transaction = transaction;
             cmd.CommandText = string.Format(SqlCommands.CreateQueueTable, ListenerQueue.Trim());
             cmd.ExecuteNonQuery();
         }
     });
 }
Esempio n. 7
0
 private void WriteFailedMessage(TransportMessage transportMessage, Exception exception, string originalBody, string originalHeaders)
 {
     try
     {
         // Write a failed message
         TransactionWrapper.RunInTransaction(transaction =>
         {
             using (var command = transaction.Connection.CreateCommand())
             {
                 command.CommandText = SqlCommands.InsertPoisonMessage;
                 var paramQueue      = command.Parameters.AddWithValue("@Queue", this.ListenerQueue);
                 paramQueue.Size     = 255;
                 command.Parameters.AddWithValue("@InsertDateTime", DateTime.UtcNow);
                 command.Parameters.AddWithValue("@Id", Guid.Parse(transportMessage.Id));
                 var paramCorrelationId        = command.Parameters.AddWithValue("@CorrelationId", transportMessage.CorrelationId ?? string.Empty);
                 paramCorrelationId.SqlDbType  = SqlDbType.VarChar;
                 paramCorrelationId.Size       = 255;
                 var paramReplyToAddress       = command.Parameters.AddWithValue("@ReplyToAddress", transportMessage.ReturnAddress);
                 paramReplyToAddress.SqlDbType = SqlDbType.VarChar;
                 paramReplyToAddress.Size      = 255;
                 command.Parameters.AddWithValue("@MessageIntent", (byte)transportMessage.MessageIntent);
                 var paramHeaders  = command.Parameters.AddWithValue("@Headers", originalHeaders ?? string.Empty);
                 paramHeaders.Size = -1;
                 var paramBody     = command.Parameters.AddWithValue("@Body", originalBody ?? string.Empty);
                 paramBody.Size    = -1;
                 if (exception != null)
                 {
                     var paramException  = command.Parameters.AddWithValue("@Exception", FormatErrorMessage(exception));
                     paramException.Size = -1;
                 }
                 else
                 {
                     command.Parameters.AddWithValue("@Exception", DBNull.Value);
                 }
                 command.Transaction = transaction;
                 command.ExecuteNonQuery();
             }
         });
     }
     catch (Exception e)
     {
         Logger.Fatal("Failed to write ServiceBroker Error Message", e);
         // suppress -- don't let this exception take down the process
     }
 }
 private void WriteFailedMessage(Guid messageId, Message serviceBrokerMessage, TransportMessage transportMessage, Exception exception, int status)
 {
     try {
         // Write a failed message
         TransactionWrapper.RunInTransaction(transaction => {
             using (var command = transaction.Connection.CreateCommand()) {
                 command.CommandText = "cw_InsertFailedMessage";
                 command.CommandType = CommandType.StoredProcedure;
                 if (transportMessage != null)
                 {
                     command.Parameters.AddWithValue("@originService", transportMessage.ReturnAddress);
                 }
                 else
                 {
                     command.Parameters.AddWithValue("@originService", string.Empty);
                 }
                 command.Parameters.AddWithValue("@queueName", this.ListenerQueue);
                 command.Parameters.AddWithValue("@queueService", this.ReturnAddress);
                 command.Parameters.AddWithValue("@messageId", messageId);
                 command.Parameters.AddWithValue("@messageStatus", (int)status);
                 command.Parameters.AddWithValue("@messageData", serviceBrokerMessage.Body);
                 if (exception != null)
                 {
                     command.Parameters.AddWithValue("@errorMessage", FormatErrorMessage(exception));
                 }
                 else
                 {
                     command.Parameters.AddWithValue("@errorMessage", DBNull.Value);
                 }
                 command.Transaction = transaction;
                 command.ExecuteNonQuery();
             }
         });
     } catch (Exception e) {
         Logger.Fatal("Failed to write ServiceBroker Error Message", e);
         // suppress -- don't let this exception take down the process
     }
 }
Esempio n. 9
0
 private void Process()
 {
     messageContext = new MessageReceiveProperties();
     try
     {
         var wrapper = new TransactionWrapper();
         wrapper.RunInTransaction(() => Receive(messageContext), isolationLevel, transactionTimeout);
         ClearFailuresForMessage(messageContext.MessageId);
     }
     catch (AbortHandlingCurrentMessageException)
     {
     }
     catch (Exception error)
     {
         log.Error(error);
         IncrementFailuresForMessage(messageContext.MessageId);
         OnFailedMessageProcessing(error);
     }
     finally
     {
         messageContext = null;
     }
 }
Esempio n. 10
0
        public void Send(TransportMessage toSend, IEnumerable <string> destinations)
        {
            var destinationQueue = string.Empty;

            try
            {
                TransactionWrapper.RunInTransaction(transaction =>
                {
                    var id                = Guid.NewGuid();
                    toSend.Id             = id.ToString();
                    toSend.TimeSent       = DateTime.UtcNow;
                    toSend.ReturnAddress  = this.ListenerQueue;
                    var serializedMessage = string.Empty;
                    var messages          = "";
                    var headers           = "";
                    using (var stream = new MemoryStream())
                    {
                        MessageSerializer.Serialize(toSend.Body, stream);
                        messages = Encoding.UTF8.GetString(stream.ToArray());
                    }
                    if (toSend.Headers != null && toSend.Headers.Count > 0)
                    {
                        using (var stream = new MemoryStream())
                        {
                            MessageSerializer.Serialize(toSend.Headers.ToArray(), stream);
                            headers = Encoding.UTF8.GetString(stream.ToArray());
                        }
                    }
                    using (var cmd = transaction.Connection.CreateCommand())
                    {
                        cmd.Transaction = transaction;
                        cmd.Parameters.AddWithValue("@Id", id);
                        var paramCorrelationId        = cmd.Parameters.AddWithValue("@CorrelationId", toSend.CorrelationId ?? string.Empty);
                        paramCorrelationId.SqlDbType  = SqlDbType.VarChar;
                        paramCorrelationId.Size       = 255;
                        var paramReplyToAddress       = cmd.Parameters.AddWithValue("@ReplyToAddress", this.ListenerQueue);
                        paramReplyToAddress.SqlDbType = SqlDbType.VarChar;
                        paramReplyToAddress.Size      = 255;
                        cmd.Parameters.AddWithValue("@MessageIntent", (byte)toSend.MessageIntent);

                        var paramHeaders  = cmd.Parameters.AddWithValue("@Headers", headers);
                        paramHeaders.Size = -1;
                        var paramBody     = cmd.Parameters.AddWithValue("@Body", messages);
                        paramBody.Size    = -1;
                        foreach (var destination in destinations)
                        {
                            destinationQueue = destination;
                            cmd.CommandText  = string.Format(SqlCommands.InsertMessage, destination);
                            cmd.ExecuteNonQuery();
                            if (Logger.IsDebugEnabled)
                            {
                                Logger.Debug(string.Format("Sending message {0} with ID {1} to destination {2}.\n" +
                                                           "ToString() of the message yields: {3}\n" +
                                                           "Message headers:\n{4}",
                                                           toSend.Body[0].GetType().AssemblyQualifiedName,
                                                           toSend.Id,
                                                           destination,
                                                           toSend.Body[0],
                                                           string.Join(", ", toSend.Headers.Select(h => h.Key + ":" + h.Value).ToArray())
                                                           ));
                            }
                        }
                    }
                });
            }
            catch (SqlException ex)
            {
                if (ex.Number == 208)
                {
                    var msg = string.Format("Failed to send message to address: [{0}]", destinationQueue);
                    throw new QueueNotFoundException(toSend, msg, ex);
                }
            }
        }