public override MessageContext ReceiveOnTopic(MessageContext inputcontext, IMessageAdapter adapter) { var entity = EntityNameHelper.FormatSubscriptionPath(inputcontext.ToReplyPath, inputcontext.ToReplySubscription); var client = new SessionClient(inputcontext.ToReplyConnectionString, entity); var messagesession = client.AcceptMessageSessionAsync(inputcontext.ReplyToRequestId).GetAwaiter().GetResult(); var message = inputcontext.ToReplyTimeOut != 0 ? messagesession.ReceiveAsync(TimeSpan.FromSeconds(inputcontext.ToReplyTimeOut)).GetAwaiter().GetResult() : messagesession.ReceiveAsync().GetAwaiter().GetResult(); MessageContext outputcontext = null; if (message != null) { outputcontext = adapter.Read(message, inputcontext.ResultType); messagesession.CompleteAsync(message.SystemProperties.LockToken); } messagesession.CloseAsync().GetAwaiter().GetResult(); client.CloseAsync().GetAwaiter().GetResult(); return(outputcontext); }
async Task PeekSessionAsyncTest(string queueName, int messageCount = 10) { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { var messageId1 = "test-message1"; var sessionId1 = "sessionId1"; await sender.SendAsync(new Message { MessageId = messageId1, SessionId = sessionId1 }); TestUtility.Log($"Sent Message: {messageId1} to Session: {sessionId1}"); var messageId2 = "test-message2"; var sessionId2 = "sessionId2"; await sender.SendAsync(new Message { MessageId = messageId2, SessionId = sessionId2 }); TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}"); // Peek Message, Receive and Delete with SessionId - sessionId 1 await this.PeekAndDeleteMessageAsync(sessionClient, sessionId1, messageId1); // Peek Message, Receive and Delete with SessionId - sessionId 2 await this.PeekAndDeleteMessageAsync(sessionClient, sessionId2, messageId2); } finally { await sender.CloseAsync().ConfigureAwait(false); await sessionClient.CloseAsync().ConfigureAwait(false); } }
async Task SessionLockLostExceptionTest() { var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName); try { var messageId = "test-message1"; var sessionId = Guid.NewGuid().ToString(); await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId }); TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}"); var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}"); var message = await sessionReceiver.ReceiveAsync(); Assert.True(message.MessageId == messageId); TestUtility.Log($"Received Message: MessageId: {message.MessageId}"); // Let the Session expire with some buffer time TestUtility.Log($"Waiting for session lock to time out..."); await Task.Delay((sessionReceiver.LockedUntilUtc - DateTime.UtcNow) + TimeSpan.FromSeconds(10)); await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.ReceiveAsync()); await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.RenewSessionLockAsync()); await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.GetStateAsync()); await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.SetStateAsync(null)); await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken)); await sessionReceiver.CloseAsync(); TestUtility.Log($"Closed Session Receiver..."); //Accept a new Session and Complete the message sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}"); message = await sessionReceiver.ReceiveAsync(); TestUtility.Log($"Received Message: MessageId: {message.MessageId}"); await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); await sessionReceiver.CloseAsync(); } finally { await sender.CloseAsync(); await sessionClient.CloseAsync(); } }
public async Task ReceiveDeferredMessageForSessionTest(string qName) { var sessionId = Guid.NewGuid().ToString("N").Substring(0, 8); var messageId = Guid.NewGuid().ToString("N").Substring(0, 8); var sender = new MessageSender(TestUtility.NamespaceConnectionString, qName); await sender.SendAsync(new Message() { SessionId = sessionId, MessageId = messageId }); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, qName); var messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); var msg = await messageSession.ReceiveAsync(); var seqNum = msg.SystemProperties.SequenceNumber; await messageSession.DeferAsync(msg.SystemProperties.LockToken); var msg2 = await messageSession.ReceiveDeferredMessageAsync(seqNum); Assert.Equal(seqNum, msg2.SystemProperties.SequenceNumber); Assert.Equal(messageId, msg2.MessageId); await sender.CloseAsync(); await sessionClient.CloseAsync(); await messageSession.CloseAsync(); }
private async Task ReceiveResponse(string sessionId) { try { SessionClient sessionClient = new SessionClient(_connectionString, _queueServerName); IMessageSession messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); Message messagePayload = await messageSession.ReceiveAsync(); if (messagePayload != null) { string message = Encoding.UTF8.GetString(messagePayload.Body); ReplyListBox.Items.Add(ConstructMessageListBox(sessionId, message, false)); } else { ReplyListBox.Items.Add(ConstructMessageListBox(sessionId, "Failed getting response", false)); } await messageSession.CloseAsync(); await sessionClient.CloseAsync(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
async Task SessionRenewLockTest(string queueName) { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); try { var messageId = "test-message1"; var sessionId = Guid.NewGuid().ToString(); await sender.SendAsync(new Message() { MessageId = messageId, SessionId = sessionId }); TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}"); var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); TestUtility.Log($"Session LockedUntilUTC: {sessionReceiver.LockedUntilUtc} for Session: {sessionReceiver.SessionId}"); Message message = await sessionReceiver.ReceiveAsync(); TestUtility.Log($"Received Message: {message.MessageId} from Session: {sessionReceiver.SessionId}"); Assert.True(message.MessageId == messageId); TestUtility.Log("Sleeping 10 seconds..."); await Task.Delay(TimeSpan.FromSeconds(10)); // For session it looks like when the session is received, sometimes the session LockedUntil UTC // is turning out slightly more than the Default Lock Duration(lock is for 1 minute, but the session was locked // for 1 min and 2 seconds. We will need to look at if this is an issue on service or some kind of time SKU. // Temporarily changing this test to look at the renew request time instead. DateTime renewRequestTime = DateTime.UtcNow; await sessionReceiver.RenewSessionLockAsync(); DateTime firstLockedUntilUtcTime = sessionReceiver.LockedUntilUtc; TestUtility.Log($"After Renew Session LockedUntilUTC: {firstLockedUntilUtcTime} for Session: {sessionReceiver.SessionId}"); Assert.True(firstLockedUntilUtcTime >= renewRequestTime + TimeSpan.FromSeconds(10)); TestUtility.Log("Sleeping 5 seconds..."); await Task.Delay(TimeSpan.FromSeconds(5)); renewRequestTime = DateTime.UtcNow; await sessionReceiver.RenewSessionLockAsync(); TestUtility.Log($"After Second Renew Session LockedUntilUTC: {sessionReceiver.LockedUntilUtc} for Session: {sessionReceiver.SessionId}"); Assert.True(sessionReceiver.LockedUntilUtc >= renewRequestTime + TimeSpan.FromSeconds(5)); await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); TestUtility.Log($"Completed Message: {message.MessageId} for Session: {sessionReceiver.SessionId}"); await sessionReceiver.CloseAsync(); } finally { await sender.CloseAsync().ConfigureAwait(false); await sessionClient.CloseAsync().ConfigureAwait(false); } }
public async Task TransactionalSessionDispositionTest(string queueName) { var sender = new MessageSender(ConnectionString, queueName); var sessionClient = new SessionClient(ConnectionString, queueName); IMessageSession receiver = null; try { string body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()) { SessionId = body }; await sender.SendAsync(message).ConfigureAwait(false); receiver = await sessionClient.AcceptMessageSessionAsync(body); var receivedMessage = await receiver.ReceiveAsync(ReceiveTimeout); Assert.NotNull(receivedMessage); Assert.Equal(body, receivedMessage.Body.GetString()); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); ts.Dispose(); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); ts.Complete(); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); await Assert.ThrowsAsync <SessionLockLostException>(async() => await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken)); } finally { await sender.CloseAsync(); await sessionClient.CloseAsync(); if (receiver != null) { await receiver.CloseAsync(); } } }
public async Task GetAndSetSessionStateTest(bool partitioned, bool sessionEnabled) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); try { var messageId = "test-message1"; var sessionId = Guid.NewGuid().ToString(); await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId }); TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}"); var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); var message = await sessionReceiver.ReceiveAsync(); TestUtility.Log($"Received Message: {message.MessageId} from Session: {sessionReceiver.SessionId}"); Assert.True(message.MessageId == messageId); var sessionStateString = "Received Message From Session!"; var sessionState = Encoding.UTF8.GetBytes(sessionStateString); await sessionReceiver.SetStateAsync(sessionState); TestUtility.Log($"Set Session State: {sessionStateString} for Session: {sessionReceiver.SessionId}"); var returnedSessionState = await sessionReceiver.GetStateAsync(); var returnedSessionStateString = Encoding.UTF8.GetString(returnedSessionState); TestUtility.Log($"Get Session State Returned: {returnedSessionStateString} for Session: {sessionReceiver.SessionId}"); Assert.Equal(sessionStateString, returnedSessionStateString); // Complete message using Session Receiver await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); TestUtility.Log($"Completed Message: {message.MessageId} for Session: {sessionReceiver.SessionId}"); sessionStateString = "Completed Message On Session!"; sessionState = Encoding.UTF8.GetBytes(sessionStateString); await sessionReceiver.SetStateAsync(sessionState); TestUtility.Log($"Set Session State: {sessionStateString} for Session: {sessionReceiver.SessionId}"); returnedSessionState = await sessionReceiver.GetStateAsync(); returnedSessionStateString = Encoding.UTF8.GetString(returnedSessionState); TestUtility.Log($"Get Session State Returned: {returnedSessionStateString} for Session: {sessionReceiver.SessionId}"); Assert.Equal(sessionStateString, returnedSessionStateString); await sessionReceiver.CloseAsync(); } finally { await sender.CloseAsync(); await sessionClient.CloseAsync(); } }); }
async Task <long> DoPurgeSessionEntity(long messagesToPurgeCount) { long totalMessagesPurged = 0; ISessionClient sessionClient = new SessionClient( serviceBusHelper.ConnectionString, GetEntityPath(deadLetterQueue: false), null, receiveMode: ReceiveMode.ReceiveAndDelete, retryPolicy: RetryPolicy.Default, prefetchCount: 10, transportType: serviceBusHelper.TransportType); var consecutiveSessionTimeOuts = 0; try { const int enoughZeroReceives = 3; while (consecutiveSessionTimeOuts < enoughZeroReceives && totalMessagesPurged < messagesToPurgeCount) { IMessageSession session = await sessionClient.AcceptMessageSessionAsync(); var consecutiveZeroBatchReceives = 0; while (consecutiveZeroBatchReceives < enoughZeroReceives && totalMessagesPurged < messagesToPurgeCount) { var messages = await session.ReceiveAsync(1000, TimeSpan.FromMilliseconds(1000)) .ConfigureAwait(false); if (messages != null && messages.Any()) { Interlocked.Add(ref totalMessagesPurged, messages.Count()); consecutiveZeroBatchReceives = 0; } else { ++consecutiveZeroBatchReceives; } } await session.CloseAsync().ConfigureAwait(false); } } catch (TimeoutException) { ++consecutiveSessionTimeOuts; } finally { await sessionClient.CloseAsync().ConfigureAwait(false); } return(totalMessagesPurged); }
static async Task Main(string[] args) { Console.WriteLine("Client Console"); while (true) { Console.WriteLine("Enter text:"); string text = Console.ReadLine(); // Create a session identifier for the response message string responseSessionId = Guid.NewGuid().ToString(); // Create a message using text as the body. var requestMessage = new Message(Encoding.UTF8.GetBytes(text)); // Set the appropriate message properties. //Send the first message to the first queue with the // responseID set requestMessage.ReplyToSessionId = responseSessionId; var stopwatch = Stopwatch.StartNew(); // Send the message on the request queue. await RequestQueueClient.SendAsync(requestMessage); // Create a session client // wait for the server to responsd with the same SessionId // by creating a session client var sessionClient = new SessionClient("ConnectionString", "QueueName"); // Accept a message session var messageSession = await sessionClient.AcceptMessageSessionAsync(responseSessionId); // Receive the response message. var responseMessage = await messageSession.ReceiveAsync(); stopwatch.Stop(); // Close the session, we got the message. await sessionClient.CloseAsync(); // Deserialise the message body to echoText. string echoText = Encoding.UTF8.GetString(responseMessage.Body); Console.WriteLine(echoText); Console.WriteLine("Time: {0} ms.", stopwatch.ElapsedMilliseconds); Console.WriteLine(); } }
public async Task <Dictionary <string, string> > CheckMessagesReceived(string subscriptionName, string tokenID) { List <Message> message = new List <Message>(); Dictionary <string, string> topicAndSubscriptionFound = new Dictionary <string, string>(); var topicsRegistered = await new ManageAzurePortal().CheckTopics(subscriptionName); if (topicsRegistered.Count > 0) { Action <object> delegateCheck = (topic) => { ISessionClient sessionClient = new SessionClient(appOptions.BusConnectionString, EntityNameHelper.FormatSubscriptionPath(topic.ToString(), subscriptionName), ReceiveMode.PeekLock); IMessageSession session = sessionClient.AcceptMessageSessionAsync(tokenID).GetAwaiter().GetResult(); if (session != null) { message = (List <Message>)session.ReceiveAsync(1, new TimeSpan(0, 0, 20)).GetAwaiter().GetResult(); if (message == null) { session.CloseAsync().GetAwaiter().GetResult(); sessionClient.CloseAsync().GetAwaiter().GetResult(); } else { topicAndSubscriptionFound.Add(topic.ToString(), subscriptionName); session.CloseAsync().GetAwaiter().GetResult(); sessionClient.CloseAsync().GetAwaiter().GetResult(); } } }; Task[] taskArray = new Task[topicsRegistered.Count]; for (int i = 0; i < taskArray.Length; i++) { taskArray[i] = Task.Factory.StartNew(delegateCheck, topicsRegistered[i]); } Task.WaitAll(taskArray); } return(topicAndSubscriptionFound); }
async Task SessionTest(string queueName) { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); try { var messageId1 = "test-message1"; var sessionId1 = "sessionId1"; await sender.SendAsync(new Message() { MessageId = messageId1, SessionId = sessionId1 }).ConfigureAwait(false); TestUtility.Log($"Sent Message: {messageId1} to Session: {sessionId1}"); var messageId2 = "test-message2"; var sessionId2 = "sessionId2"; await sender.SendAsync(new Message() { MessageId = messageId2, SessionId = sessionId2 }).ConfigureAwait(false); TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}"); // Receive Message, Complete and Close with SessionId - sessionId 1 await this.AcceptAndCompleteSessionsAsync(sessionClient, sessionId1, messageId1).ConfigureAwait(false); // Receive Message, Complete and Close with SessionId - sessionId 2 await this.AcceptAndCompleteSessionsAsync(sessionClient, sessionId2, messageId2).ConfigureAwait(false); // Receive Message, Complete and Close - With Null SessionId specified var messageId3 = "test-message3"; var sessionId3 = "sessionId3"; await sender.SendAsync(new Message() { MessageId = messageId3, SessionId = sessionId3 }).ConfigureAwait(false); await this.AcceptAndCompleteSessionsAsync(sessionClient, null, messageId3).ConfigureAwait(false); } finally { await sender.CloseAsync().ConfigureAwait(false); await sessionClient.CloseAsync().ConfigureAwait(false); } }
async Task OperationsOnMessageSessionAfterCloseShouldThrowObjectDisposedExceptionTest() { var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName); IMessageSession sessionReceiver = null; try { var messageId = "test-message1"; var sessionId = Guid.NewGuid().ToString(); await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId }); TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}"); sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}"); await sessionReceiver.CloseAsync(); await Assert.ThrowsAsync <ObjectDisposedException>(async() => await sessionReceiver.ReceiveAsync()); await Assert.ThrowsAsync <ObjectDisposedException>(async() => await sessionReceiver.GetStateAsync()); await Assert.ThrowsAsync <ObjectDisposedException>(async() => await sessionReceiver.SetStateAsync(null)); sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); TestUtility.Log($"Reaccept Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}"); var message = await sessionReceiver.ReceiveAsync(); Assert.True(message.MessageId == messageId); TestUtility.Log($"Received Message: MessageId: {message.MessageId}"); await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); await sessionReceiver.CloseAsync(); } finally { await sender.CloseAsync(); await sessionClient.CloseAsync(); } }
public List <Message> ReceiveMessages(Dictionary <string, string> topicAndSubscriptionReceived, string tokenID) { if (topicAndSubscriptionReceived.Count < 1) { return(null); } List <Message> listMessage = new List <Message>(); Action <object> delegateGetMessages = (topicSubscriptionMessage) => { var messageFound = (KeyValuePair <string, string>)topicSubscriptionMessage; ISessionClient sessionClient = new SessionClient(appOptions.BusConnectionString, EntityNameHelper.FormatSubscriptionPath(messageFound.Key, messageFound.Value), ReceiveMode.PeekLock); IMessageSession session = sessionClient.AcceptMessageSessionAsync(tokenID).GetAwaiter().GetResult(); while (true) { Message message = session.ReceiveAsync(new TimeSpan(0, 0, 20)).GetAwaiter().GetResult(); if (message == null) { session.CloseAsync().GetAwaiter().GetResult(); sessionClient.CloseAsync().GetAwaiter().GetResult(); break; } else { session.CompleteAsync(message.SystemProperties.LockToken).GetAwaiter().GetResult(); listMessage.Add(message); } } }; Task[] taskArray = new Task[topicAndSubscriptionReceived.Count]; List <KeyValuePair <string, string> > lstTopicAndSubscriptionReceived = new List <KeyValuePair <string, string> >(); foreach (KeyValuePair <string, string> topicAndSubscription in topicAndSubscriptionReceived) { lstTopicAndSubscriptionReceived.Add(topicAndSubscription); } for (int i = 0; i < taskArray.Length; i++) { taskArray[i] = Task.Factory.StartNew(delegateGetMessages, lstTopicAndSubscriptionReceived[i]); } Task.WaitAll(taskArray); return(listMessage); }
public async Task <T> RecibeMensajeSesion(string cadenaConexion, string nombreCola, string sesionId, int segundos, int intentos) { int contador = 0; T respuesta = default(T); var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(cadenaConexion); var serviceBusConnection = new ServiceBusConnection(serviceBusConnectionStringBuilder); var sessionClient = new SessionClient(serviceBusConnection, nombreCola, ReceiveMode.PeekLock, null, 0); var messageSession = await sessionClient.AcceptMessageSessionAsync(sesionId, TimeSpan.FromMinutes(1)); if (messageSession != null) { while (contador < intentos) { Message message = await messageSession.ReceiveAsync(TimeSpan.FromSeconds(5)); if (message != null) { var bodyText = System.Text.Encoding.UTF8.GetString(message.Body); respuesta = JsonConvert.DeserializeObject <T>(bodyText); await messageSession.CompleteAsync(message.SystemProperties.LockToken); contador = intentos; } else { await Task.Delay(segundos * 1000); } contador++; } } await messageSession.CloseAsync(); await sessionClient.CloseAsync(); await serviceBusConnection.CloseAsync(); return(respuesta); }
public async Task QueueSessionEventsAreNotFiredWhenDiagnosticsIsDisabled() { await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : true, async queueName => { var messageSender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); var messageSession = default(IMessageSession); var eventQueue = this.CreateEventQueue(); try { using (var listener = this.CreateEventListener(queueName, eventQueue)) using (var subscription = this.SubscribeToEvents(listener)) { listener.Disable(); var sessionId = Guid.NewGuid().ToString(); await messageSender.SendAsync(new Message { MessageId = "messageId", SessionId = sessionId }); messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); await messageSession.SetStateAsync(new byte[] { 1 }); await messageSession.GetStateAsync(); await messageSession.SetStateAsync(new byte[] { }); await messageSession.ReceiveAsync(); Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally { await Task.WhenAll( messageSession?.CloseAsync(), messageSender.CloseAsync(), sessionClient.CloseAsync()); } }); }
public async Task AcceptSessionThrowsSessionCannotBeLockedException() { var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName); var someSessionId = "someSessionId"; IMessageSession session = null; try { session = await sessionClient.AcceptMessageSessionAsync(someSessionId); await Assert.ThrowsAsync <SessionCannotBeLockedException>(async() => session = await sessionClient.AcceptMessageSessionAsync(someSessionId)); } finally { await sessionClient.CloseAsync().ConfigureAwait(false); await session?.CloseAsync(); } }
public async Task AcceptSessionThrowsSessionCannotBeLockedException() { await ServiceBusScope.UsingQueueAsync(partitioned : true, sessionEnabled : true, async queueName => { var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); var someSessionId = "someSessionId"; IMessageSession session = null; try { session = await sessionClient.AcceptMessageSessionAsync(someSessionId); await Assert.ThrowsAsync <SessionCannotBeLockedException>(async() => session = await sessionClient.AcceptMessageSessionAsync(someSessionId)); } finally { await sessionClient.CloseAsync(); await session?.CloseAsync(); } }); }
public override MessageContext ReceiveOnQueue(Channel channel, MessageContext context, IMessageAdapter adapter) { var client = new SessionClient(channel.ToReplyConnectionString, channel.ToReplyPath); var messagesession = client.AcceptMessageSessionAsync(context.Identity.ReplyToRequestId).GetAwaiter().GetResult(); var message = channel.ToReplyTimeOut != 0 ? messagesession.ReceiveAsync(TimeSpan.FromSeconds(channel.ToReplyTimeOut)).GetAwaiter().GetResult() : messagesession.ReceiveAsync().GetAwaiter().GetResult(); MessageContext outputcontext = null; if (message != null) { outputcontext = adapter.Read(message, context.ResultType, context.EndPoint.UseClaimCheck); messagesession.CompleteAsync(message.SystemProperties.LockToken); } messagesession.CloseAsync().GetAwaiter().GetResult(); client.CloseAsync().GetAwaiter().GetResult(); return(outputcontext); }
static async Task ReceiveMessage(string sessionId) { try { SessionClient sessionClient = new SessionClient(_connectionString, _queueServerName); IMessageSession messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); Message message = await messageSession.ReceiveAsync(); if (message != null) { string messageText = Encoding.UTF8.GetString(message.Body); Console.WriteLine($"[{DateTime.Now}] Reply from server: {messageText}"); } await messageSession.CloseAsync(); await sessionClient.CloseAsync(); } catch (Exception ex) { Console.WriteLine($"[x] Error: {ex.Message}"); } }
public async Task ReceiveDeferredMessageForSessionTest(bool partitioned, bool sessionEnabled) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sessionId = Guid.NewGuid().ToString("N").Substring(0, 8); var messageId = Guid.NewGuid().ToString("N").Substring(0, 8); var sender = default(MessageSender); var sessionClient = default(SessionClient); var messageSession = default(IMessageSession); try { sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); await sender.SendAsync(new Message() { SessionId = sessionId, MessageId = messageId }); sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); var msg = await messageSession.ReceiveAsync(); var seqNum = msg.SystemProperties.SequenceNumber; await messageSession.DeferAsync(msg.SystemProperties.LockToken); var msg2 = await messageSession.ReceiveDeferredMessageAsync(seqNum); Assert.Equal(seqNum, msg2.SystemProperties.SequenceNumber); Assert.Equal(messageId, msg2.MessageId); } finally { await sender?.CloseAsync(); await sessionClient?.CloseAsync(); await messageSession?.CloseAsync(); } }); }
public async Task PeekSessionAsyncTest(bool partitioned, bool sessionEnabled) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { var messageId1 = "test-message1"; var sessionId1 = "sessionId1"; await sender.SendAsync(new Message { MessageId = messageId1, SessionId = sessionId1 }); TestUtility.Log($"Sent Message: {messageId1} to Session: {sessionId1}"); var messageId2 = "test-message2"; var sessionId2 = "sessionId2"; await sender.SendAsync(new Message { MessageId = messageId2, SessionId = sessionId2 }); TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}"); // Peek Message, Receive and Delete with SessionId - sessionId 1 await this.PeekAndDeleteMessageAsync(sessionClient, sessionId1, messageId1); // Peek Message, Receive and Delete with SessionId - sessionId 2 await this.PeekAndDeleteMessageAsync(sessionClient, sessionId2, messageId2); } finally { await sender.CloseAsync(); await sessionClient.CloseAsync(); } }); }
async Task GetAndSetSessionStateTest(string queueName) { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName); try { var messageId = "test-message1"; var sessionId = Guid.NewGuid().ToString(); await sender.SendAsync(new Message() { MessageId = messageId, SessionId = sessionId }); TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}"); var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); Assert.NotNull(sessionReceiver); var message = await sessionReceiver.ReceiveAsync(); TestUtility.Log($"Received Message: {message.MessageId} from Session: {sessionReceiver.SessionId}"); Assert.True(message.MessageId == messageId); var sessionStateString = "Received Message From Session!"; var sessionState = new MemoryStream(Encoding.UTF8.GetBytes(sessionStateString)); await sessionReceiver.SetStateAsync(sessionState); TestUtility.Log($"Set Session State: {sessionStateString} for Session: {sessionReceiver.SessionId}"); var returnedSessionState = await sessionReceiver.GetStateAsync(); using (var reader = new StreamReader(returnedSessionState, Encoding.UTF8)) { var returnedSessionStateString = await reader.ReadToEndAsync(); TestUtility.Log($"Get Session State Returned: {returnedSessionStateString} for Session: {sessionReceiver.SessionId}"); Assert.Equal(sessionStateString, returnedSessionStateString); } // Complete message using Session Receiver await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); TestUtility.Log($"Completed Message: {message.MessageId} for Session: {sessionReceiver.SessionId}"); sessionStateString = "Completed Message On Session!"; sessionState = new MemoryStream(Encoding.UTF8.GetBytes(sessionStateString)); await sessionReceiver.SetStateAsync(sessionState); TestUtility.Log($"Set Session State: {sessionStateString} for Session: {sessionReceiver.SessionId}"); returnedSessionState = await sessionReceiver.GetStateAsync(); using (var reader = new StreamReader(returnedSessionState, Encoding.UTF8)) { var returnedSessionStateString = await reader.ReadToEndAsync(); TestUtility.Log($"Get Session State Returned: {returnedSessionStateString} for Session: {sessionReceiver.SessionId}"); Assert.Equal(sessionStateString, returnedSessionStateString); } await sessionReceiver.CloseAsync(); } finally { await sender.CloseAsync().ConfigureAwait(false); await sessionClient.CloseAsync().ConfigureAwait(false); } }
public async Task AcceptSetAndGetStateGetFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : true, async queueName => { var messageSender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); var messageSession = default(IMessageSession); var eventQueue = this.CreateEventQueue(); try { using (var listener = this.CreateEventListener(queueName, eventQueue)) using (var subscription = this.SubscribeToEvents(listener)) { listener.Enable(); var sessionId = Guid.NewGuid().ToString(); await messageSender.SendAsync(new Message { MessageId = "messageId", SessionId = sessionId }); messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); await messageSession.SetStateAsync(new byte[] { 1 }); await messageSession.GetStateAsync(); await messageSession.SetStateAsync(new byte[] { }); await messageSession.ReceiveAsync(); Assert.True(eventQueue.TryDequeue(out var sendStart)); AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); Assert.True(eventQueue.TryDequeue(out var sendStop)); AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); Assert.True(eventQueue.TryDequeue(out var acceptStart)); AssertAcceptMessageSessionStart(queueName, acceptStart.eventName, acceptStart.payload, acceptStart.activity); Assert.True(eventQueue.TryDequeue(out var acceptStop)); AssertAcceptMessageSessionStop(queueName, acceptStop.eventName, acceptStop.payload, acceptStop.activity, acceptStart.activity); Assert.True(eventQueue.TryDequeue(out var setStateStart)); AssertSetSessionStateStart(queueName, setStateStart.eventName, setStateStart.payload, setStateStart.activity); Assert.True(eventQueue.TryDequeue(out var setStateStop)); AssertSetSessionStateStop(queueName, setStateStop.eventName, setStateStop.payload, setStateStop.activity, setStateStart.activity); Assert.True(eventQueue.TryDequeue(out var getStateStart)); AssertGetSessionStateStart(queueName, getStateStart.eventName, getStateStart.payload, getStateStart.activity); Assert.True(eventQueue.TryDequeue(out var getStateStop)); AssertGetSessionStateStop(queueName, getStateStop.eventName, getStateStop.payload, getStateStop.activity, getStateStop.activity); Assert.True(eventQueue.TryDequeue(out var setStateStart2)); Assert.True(eventQueue.TryDequeue(out var setStateStop2)); Assert.True(eventQueue.TryDequeue(out var receiveStart)); AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity); Assert.True(eventQueue.TryDequeue(out var receiveStop)); AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, sendStart.activity); Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally { await Task.WhenAll( messageSession.CloseAsync(), messageSender.CloseAsync(), sessionClient.CloseAsync()); } }); }
public async Task <IActionResult> Post([FromBody] Order order) { bool listenForResponse = Boolean.TryParse(Request.Headers["ImplementAsyncRequestResponseMessaging"], out listenForResponse); var topicClient = new TopicClient(_appSettings.ServiceBusConnectionString, _appSettings.OrderTopicName); try { if (order == null) { return(BadRequest()); } var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order))); message.MessageId = Guid.NewGuid().ToString(); if (listenForResponse) { var responseSessionID = order.Id.ToString(); var tenantId = _appSettings.TenantId; var clientId = _appSettings.ClientId; var clientSecret = _appSettings.ClientSecret; var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}"); var result = await context.AcquireTokenAsync( "https://management.core.windows.net/", new ClientCredential(clientId, clientSecret)); var creds = new TokenCredentials(result.AccessToken); var sbClient = new ServiceBusManagementClient(creds) { SubscriptionId = _appSettings.SubscriptionId }; var queueParams = new SBQueue() { DeadLetteringOnMessageExpiration = true, RequiresSession = true, DefaultMessageTimeToLive = TimeSpan.FromMilliseconds(20000) }; await sbClient.Queues.CreateOrUpdateAsync(_appSettings.ResourceGroupName, _appSettings.ServiceBusNamespace, responseSessionID, queueParams); var sessionClient = new SessionClient(_appSettings.ServiceBusConnectionString, responseSessionID); var session = await sessionClient.AcceptMessageSessionAsync(responseSessionID); await topicClient.SendAsync(message); var responseMessage = await session.ReceiveAsync(); if (responseMessage != null) { var orderResponse = JsonConvert.DeserializeObject <OrderResponse>(Encoding.UTF8.GetString(responseMessage.Body)); await session.CompleteAsync(responseMessage.SystemProperties.LockToken); await sbClient.Queues.DeleteAsync(_appSettings.ResourceGroupName, _appSettings.ServiceBusNamespace, responseSessionID); await sessionClient.CloseAsync(); return(new JsonResult(orderResponse)); } } await topicClient.SendAsync(message); return(Ok()); } catch (Exception ex) { return(StatusCode(500)); } finally { await topicClient.CloseAsync(); } }