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"); }
public void SendMessageFromNotifierToScheduler() { var message = new TestMessage("Test: From Notifier to Scheduler."); using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { // Always begin and end a conversation var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, NotifierService, SchedulerService, Contract); // Set the time from the source machine when the message was sent message.TimeSent = DateTime.UtcNow; // Serialize the transport message string json = JsonConvert.SerializeObject(message, Formatting.None); ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, MessageType, ServiceBrokerWrapper.GetBytes(json)); ServiceBrokerWrapper.EndConversation(sqlTransaction, conversationHandle); sqlTransaction.Commit(); } sqlConnection.Close(); } }
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); }); }
public void Publish <T>(IEnumerable <T> messages, IPublishContext context = null) { Guard.ArgumentNotNull(messages, "message"); Guard.InstanceOfType(context, "context", typeof(ServiceBrokerContext)); var serviceBrokerContext = (ServiceBrokerContext)context; // ReSharper disable once PossibleNullReferenceException using (var sqlConnection = new SqlConnection(serviceBrokerContext.ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, serviceBrokerContext.InitiatorService, serviceBrokerContext.TargetService, serviceBrokerContext.MessageContract, false); foreach (var message in messages) { byte[] buffer; using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, message); buffer = stream.GetBuffer(); stream.Close(); } ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, serviceBrokerContext.MessageType, buffer); } sqlTransaction.Commit(); } } }
private void MoveToErrorService(Message message) { GetSqlTransactionManager().RunInTransaction(transaction => { var conversationHandle = ServiceBrokerWrapper.BeginConversation(transaction, ReturnService, ErrorService, NServiceBusTransportMessageContract); ServiceBrokerWrapper.Send(transaction, conversationHandle, NServiceBusTransportMessage, message.Body); ServiceBrokerWrapper.EndConversation(transaction, conversationHandle); }); }
/// <summary> /// Returns the number of messages in the queue. /// </summary> /// <returns></returns> public int GetNumberOfPendingMessages() { int count = -1; GetSqlTransactionManager().RunInTransaction(transaction => { count = ServiceBrokerWrapper.QueryMessageCount(transaction, InputQueue, NServiceBusTransportMessage); }); return(count); }
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); } }
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); }
public void CountMessagesInNotifierQueue() { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { int messageCount = ServiceBrokerWrapper.QueryMessageCount(sqlTransaction, NotifierQueue, MessageType); Console.WriteLine("Message Count: " + messageCount); sqlTransaction.Commit(); } sqlConnection.Close(); } }
public void Work() { var connection = GetConnection(); connection.Open(); var transaction = connection.BeginTransaction(); var conversationHandle = ServiceBrokerWrapper.BeginConversation(transaction, "SBSendService", "SBReceiveService", "SBContract"); ServiceBrokerWrapper.Send(transaction, conversationHandle, "SBMessage", Encoding.Unicode.GetBytes("Test Message")); transaction.Commit(); connection.Close(); }
private void MoveToErrorService(TransportMessage message) { string initiator; if (!message.Headers.TryGetValue(ServiceBrokerTransportHeaderKeys.InitiatorService, out initiator)) { initiator = InitiatorService; } new ServiceBrokerTransactionManager(ConnectionString).RunInTransaction( xaction => { var handle = ServiceBrokerWrapper.BeginConversation(xaction, initiator, _errorService, Constants.NServiceBusTransportMessageContract); ServiceBrokerWrapper.Send(xaction, handle, Constants.NServiceBusTransportMessage, message.Body); ServiceBrokerWrapper.ForceEndConversation(xaction, handle); }); }
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 Publish(IApplicationEvent applicationEvent) { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, SchedulerService, NotifierService, Contract); string json = JsonConvert.SerializeObject(applicationEvent, Formatting.None); ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, MessageType, ServiceBrokerWrapper.GetBytes(json)); ServiceBrokerWrapper.EndConversation(sqlTransaction, conversationHandle); sqlTransaction.Commit(); } sqlConnection.Close(); } }
/// <summary> /// Sends a message to the specified destination. /// </summary> /// <param name="m">The message to send.</param> /// <param name="destination">The address of the destination to send the message to.</param> public void Send(TransportMessage m, Address destination) { string initiator; if (!m.Headers.TryGetValue(ServiceBrokerTransportHeaderKeys.InitiatorService, out initiator)) { initiator = InitiatorService; } new ServiceBrokerTransactionManager(ConnectionString).RunInTransaction( transaction => { // Always begin and end a conversation to simulate a monologe var conversationHandle = ServiceBrokerWrapper. BeginConversation( transaction, initiator, destination.ToString(), Constants.NServiceBusTransportMessageContract); // Use the conversation handle as the message Id m.Id = conversationHandle.ToString(); // Set the time from the source machine when the message was sent m.SetHeader(ServiceBrokerTransportHeaderKeys.UtcTimeSent, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)); // Serialize the transport message var xml = SerializeToXml(m); ServiceBrokerWrapper.Send( transaction, conversationHandle, Constants.NServiceBusTransportMessage, Encoding.Unicode.GetBytes(xml)); ServiceBrokerWrapper.ForceEndConversation(transaction, conversationHandle); }); }
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(); } }
private void SendTestTwitterMessages() { Console.WriteLine("Sending Twitter RT Message..."); var message = new TelerikTweetRetweeted() { ActivityId = Guid.Empty, ProfileId = Guid.Empty, OccurredOnUtc = DateTime.UtcNow, Details = "@ardalis RT'd @telerik: https://twitter.com/Telerik/status/373442658691477504" }; var connection = GetConnection(); connection.Open(); var transaction = connection.BeginTransaction(); var conversationHandle = ServiceBrokerWrapper.BeginConversation(transaction, "SBSendService", "SBReceiveService", "SBContract"); ServiceBrokerWrapper.Send(transaction, conversationHandle, "SBMessage", Encoding.Unicode.GetBytes(message.ToJson())); transaction.Commit(); connection.Close(); }
/// <summary> /// Sends a message to the specified destination. /// </summary> /// <param name="m">The message to send.</param> /// <param name="destination">The address of the destination to send the message to.</param> public void Send(TransportMessage m, string destination) { GetSqlTransactionManager().RunInTransaction(transaction => { // Always begin and end a conversation to simulate a monologe var conversationHandle = ServiceBrokerWrapper.BeginConversation(transaction, ReturnService, destination, NServiceBusTransportMessageContract); // Use the conversation handle as the message Id m.Id = conversationHandle.ToString(); // Set the time from the source machine when the message was sent m.TimeSent = DateTime.UtcNow; using (var stream = new MemoryStream()) { // Serialize the transport message SerializeTransportMessage(m, stream); ServiceBrokerWrapper.Send(transaction, conversationHandle, NServiceBusTransportMessage, stream.GetBuffer()); } ServiceBrokerWrapper.EndConversation(transaction, conversationHandle); }); }
private void EndConversation(IDbTransaction transaction, Guid conversationHandle) { ServiceBrokerWrapper.EndConversation(transaction, conversationHandle, _inputQueue, false); }
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); } }