Пример #1
0
            public void CheckMessages(object sender, System.Timers.ElapsedEventArgs e)
            {
                Debug.Print("Checking scheduler queue for messages");
                try
                {
                    using (var sqlConnection = new SqlConnection(ConnectionString))
                    {
                        sqlConnection.Open();
                        using (var sqlTransaction = sqlConnection.BeginTransaction())
                        {
                            var rawMessage = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, SchedulerQueue, 10 * 1000);

                            if (rawMessage != null && rawMessage.Body.Length > 0)
                            {
                                Debug.Print("Raw Message: " + ServiceBrokerWrapper.GetString(rawMessage.Body));

                                AppointmentConfirmedEvent appointmentConfirmedEvent = JsonConvert.DeserializeObject <AppointmentConfirmedEvent>(ServiceBrokerWrapper.GetString(rawMessage.Body));

                                DomainEvents.Raise(appointmentConfirmedEvent);
                            }
                            sqlTransaction.Commit();
                        }
                        sqlConnection.Close();
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print("Error checking scheduler queue: " + ex.ToString());
                }
                //Debug.Print("Done checking scheduler queue for messages");
            }
Пример #2
0
        public void Start(IConsumeContext consumeContext = null)
        {
            Guard.InstanceOfType(consumeContext, "consumeContext", typeof(ServiceBrokerConsumeContext));

            SetIsStarted(true);

            var serviceBrokerContext = (ServiceBrokerConsumeContext)consumeContext;

            // ReSharper disable once PossibleNullReferenceException
            using (var sqlConnection = new SqlConnection(serviceBrokerContext.ConnectionString))
            {
                sqlConnection.Open();
                while (GetIsStarted())
                {
                    using (var sqlTransaction = sqlConnection.BeginTransaction())
                    {
                        IEnumerable <Message> messages = null;
                        while (messages == null)
                        {
                            messages = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, serviceBrokerContext.Queue, 1000);
                            foreach (var message in messages)
                            {
                                if (message.MessageTypeName == "VoidMessage")
                                {
                                    var formatter = new BinaryFormatter();
                                    message.BodyStream.Position = 0;
                                    var obj = (T)formatter.Deserialize(message.BodyStream);

                                    if (OnMessageReceived != null)
                                    {
                                        try
                                        {
                                            OnMessageReceived(obj);
                                            ServiceBrokerWrapper.EndConversation(sqlTransaction,
                                                                                 message.ConversationHandle,
                                                                                 serviceBrokerContext.Queue);
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError(ex.Message);
                                        }
                                    }
                                }
                                else
                                {
                                    Trace.WriteLine("Received message: " + message.MessageTypeName + " " +
                                                    message.ConversationHandle);
                                }
                            }
                        }
                        sqlTransaction.Commit();
                    }
                }
            }
        }
        public void ReceiveMessage(SqlTransaction transaction)
        {
            Message message = null;

            try {
                message = ServiceBrokerWrapper.WaitAndReceive(transaction, this.ListenerQueue, waitTimeout);
            } catch (Exception e) {
                Logger.Error("Error in receiving message from queue.", e);
                throw; // Throw to rollback
            } finally {
                transactionWaitPool.Release(1);
                releasedWaitLock = true;
            }

            // No message? That's okay
            if (message == null)
            {
                return;
            }

            Guid conversationHandle = message.ConversationHandle;

            try {
                // Only handle transport messages
                if (message.MessageTypeName == NServiceBusTransportMessage)
                {
                    TransportMessage transportMessage = null;
                    try {
                        transportMessage = TransportMessageSerializer.Deserialize(message.BodyStream, true);
                    } catch (Exception ex) {
                        Logger.Error("Could not extract message data.", ex);
                        OnSerializationFailed(conversationHandle, message, ex);
                        return; // deserialization failed - no reason to try again, so don't throw
                    }

                    // Set the message Id
                    if (string.IsNullOrEmpty(transportMessage.Id))
                    {
                        transportMessage.Id = conversationHandle.ToString();
                    }

                    // Set the correlation Id
                    if (string.IsNullOrEmpty(transportMessage.IdForCorrelation))
                    {
                        transportMessage.IdForCorrelation = transportMessage.Id;
                    }

                    ProcessMessage(message, transportMessage);
                }
            } finally {
                // End the conversation
                ServiceBrokerWrapper.EndConversation(transaction, conversationHandle);
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            using (var sqlConnection = new SqlConnection("connectionString"))
            {
                sqlConnection.Open();

                // Create the Service Broker Service and Queue if they don't exist.
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    ServiceBrokerWrapper.CreateServiceAndQueue(sqlTransaction, @"[\\Example\Service]", "ExampleServiceQueue");
                    sqlTransaction.Commit();
                }

                // Send a single message to a Service endpoint and immediately
                // end this side of the conversation
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    var messageData        = new byte[1000];
                    var conversationHandle =
                        ServiceBrokerWrapper.SendOne(
                            sqlTransaction
                            , @"[\\Example\Service2]"
                            , @"[\\Example\Service]"
                            , "MessageContractName"
                            , "MessageType"
                            , messageData);
                    sqlTransaction.Commit();
                }

                // Wait for a message to be available on the queue. We will
                // wait for some number of milliseconds. If the timeout expires
                // then the method returns "null". Otherwise it will contain
                // the message received from the queue.
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    Message message = null;
                    while (message == null)
                    {
                        message = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, "ExampleServiceQueue", 60 * 60 * 1000);
                    }
                    // ...handle message...

                    // If we rollback the transaction then the message will
                    // return to the queue to be handled again.
                    // If we commit the transaction then we're done.
                    sqlTransaction.Commit();
                }
            }
        }
        private static List <Message> Receive(IDbTransaction trans)
        {
            List <Message> messages = null;

            try
            {
                messages = ServiceBrokerWrapper.WaitAndReceive(trans, "DataChangedEventNotificationQueue", 1000, 2000)
                           .ToList();
            }
            catch (Exception e)
            {
                ErrorLog.Error("接收DML事件通知失败", e);
            }
            return(messages);
        }
Пример #6
0
        private Tuple <Guid, TransportMessage> ReceiveFromQueue(IDbTransaction transaction)
        {
            var ssbMessages = ServiceBrokerWrapper.WaitAndReceive(transaction, _inputQueue,
                                                                  SecondsToWaitForMessage.GetValueOrDefault() * 1000,
                                                                  ReceiveBatchSize.GetValueOrDefault()).ToArray();

            if (ssbMessages.Length == 0)
            {
                return(null);
            }

            var conversationHandle = ssbMessages.First().ConversationHandle;
            var transportMessage   = ExtractTransportMessage(ssbMessages);

            return((transportMessage == null)
                       ? null
                       : Tuple.Create(conversationHandle, transportMessage));
        }
        public void ReceiveMessageOnSchedulerQueue()
        {
            using (var sqlConnection = new SqlConnection(ConnectionString))
            {
                sqlConnection.Open();
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    var rawMessage = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, SchedulerQueue, 10 * 1000);

                    if (rawMessage != null && rawMessage.Body.Length > 0)
                    {
                        Console.WriteLine("Raw Message: " + ServiceBrokerWrapper.GetString(rawMessage.Body));

                        TestMessage message = JsonConvert.DeserializeObject <TestMessage>(ServiceBrokerWrapper.GetString(rawMessage.Body));

                        Console.WriteLine("Message: " + message.Message);
                    }
                    sqlTransaction.Commit();
                }
                sqlConnection.Close();
            }
        }
Пример #8
0
        private void ReceiveFromQueue(SqlTransaction transaction)
        {
            Message message = null;

            try
            {
                message = ServiceBrokerWrapper.WaitAndReceive(transaction, InputQueue, SecondsToWaitForMessage * 1000);
            }
            catch (Exception e)
            {
                Logger.Error("Error in receiving message from queue.", e);
                throw; // Throw to rollback
            }

            // No message? That's okay
            if (message == null)
            {
                return;
            }

            Guid conversationHandle = message.ConversationHandle;

            ServiceBrokerTransport.conversationHandle = message.ConversationHandle.ToString();
            try
            {
                // Only handle transport messages
                if (message.MessageTypeName == NServiceBusTransportMessage)
                {
                    if (HandledMaxRetries(conversationHandle.ToString()))
                    {
                        Logger.Error(string.Format("Message has failed the maximum number of times allowed, ID={0}.", conversationHandle));
                        MoveToErrorService(message);
                        return;
                    }

                    // exceptions here will cause a rollback - which is what we want.
                    if (StartedMessageProcessing != null)
                    {
                        StartedMessageProcessing(this, null);
                    }

                    TransportMessage transportMessage = null;
                    try
                    {
                        // deserialize
                        if (UseXmlTransportSeralization)
                        {
                            transportMessage = ExtractXmlTransportMessage(message.BodyStream);
                        }
                        else
                        {
                            transportMessage = new BinaryFormatter().Deserialize(message.BodyStream) as TransportMessage;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Could not extract message data.", e);
                        MoveToErrorService(message);
                        OnFinishedMessageProcessing(); // don't care about failures here
                        return;                        // deserialization failed - no reason to try again, so don't throw
                    }

                    // Set the correlation Id
                    if (string.IsNullOrEmpty(transportMessage.IdForCorrelation))
                    {
                        transportMessage.IdForCorrelation = transportMessage.Id;
                    }

                    // care about failures here
                    var exceptionNotThrown = OnTransportMessageReceived(transportMessage);
                    // and here
                    var otherExNotThrown = 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 (!(exceptionNotThrown && otherExNotThrown)) //cause rollback
                    {
                        throw new ApplicationException("Exception occured while processing message.");
                    }
                }
            }
            finally
            {
                // End the conversation
                ServiceBrokerWrapper.EndConversation(transaction, conversationHandle);
            }
        }