static async Task ReceiveSessionMessagesAsync() { Console.WriteLine("==================================================================="); Console.WriteLine("Accepting sessions in the reverse order of sends for demo purposes"); Console.WriteLine("==================================================================="); var configuration = new AzureStorageAttachmentConfiguration(StorageConnectionString, containerName: "ovp"); sessionClient.RegisterAzureStorageAttachmentPlugin(configuration); // AcceptMessageSessionAsync(i.ToString()) as below with session id as parameter will try to get a session with that sessionId. // AcceptMessageSessionAsync() without any messages will try to get any available session with messages associated with that session. IMessageSession session = await sessionClient.AcceptMessageSessionAsync(); if (session != null) { Message message = await session.ReceiveAsync(); var stream = new MemoryStream(message.Body); StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); Console.WriteLine($"message body : {text}"); await session.CompleteAsync(message.SystemProperties.LockToken); } }
static async Task ReceiveMessagesWithSessionAsync(int numberOfMessagesToReceiveInBatch, string sessionId) { var messageSession = await messageSessionClient.AcceptMessageSessionAsync(); var messages = await messageSession.ReceiveAsync(numberOfMessagesToReceiveInBatch); if (messages == null) { Console.WriteLine($"Unable to get messages from sessionID {sessionId}");; } while (messages != null && messages.Count > 0) { // Process the message Console.WriteLine($"----------------------------------------------------"); Console.WriteLine($"Received {messages.Count} from sessionID {sessionId}"); Console.WriteLine($"----------------------------------------------------"); foreach (Message message in messages) { // Process the message Console.WriteLine($"Received message: SessionId: {message.SessionId} SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); // Complete the message so that it is not received again await messageSession.CompleteAsync(message.SystemProperties.LockToken); } messages = await messageSession.ReceiveAsync(numberOfMessagesToReceiveInBatch); } }
public async Task Request(Message message, TimeSpan timeout, Func <Message, Task <bool> > replyHandler, bool deadletterOnHandlerFailure = false) { var sasToken = GenerateSasToken($"{_settings[ASBSettings.ServicebusFqdnEndpoint]}{ASBSettings.SessionQueueName}/", _receiveKeyName, _receiveKey, timeout); var _replyBuilder = new ServiceBusConnectionStringBuilder(_settings[ASBSettings.ServicebusFqdnEndpoint], ASBSettings.SessionQueueName, sasToken); var sessionId = Guid.NewGuid().ToString("D"); message.ReplyToSessionId = sessionId; message.ReplyTo = _replyBuilder.GetEntityConnectionString(); message.TimeToLive = timeout; var session = await _receiveClient.AcceptMessageSessionAsync(sessionId); await _sendClient.SendAsync(message); var reply = await session.ReceiveAsync(timeout); if (reply != null) { if (await replyHandler(reply)) { await session.CompleteAsync(reply.SystemProperties.LockToken); } else if (deadletterOnHandlerFailure) { await session.DeadLetterAsync(reply.SystemProperties.LockToken); } } else { throw new Exception("No reply received within the timeout period"); } }
private static void ReceiveMessages(ISessionClient sessionClient) { IMessageSession messageSession = sessionClient.AcceptMessageSessionAsync("Test1").GetAwaiter().GetResult(); Program c = new Program(); try { Message messageReceived = null; do { log.Info("Receiver listening"); messageReceived = messageSession.ReceiveAsync().GetAwaiter().GetResult(); if (messageReceived != null) { Console.WriteLine($"Received message: SequenceNumber:{messageReceived.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(messageReceived.Body)}"); //this command permit to delete messages from the Cloud service, if the connection lost the application retry to download datas messageSession.CompleteAsync(messageReceived.SystemProperties.LockToken).GetAwaiter().GetResult(); } //call of method to move files from a directory to anothe c.ConfigurationSourceDestinationPath("sourcePath", "destinationPath", $"{Encoding.UTF8.GetString(messageReceived.Body)}"); } while (!messageSession.IsClosedOrClosing); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { messageSession.CloseAsync().GetAwaiter().GetResult(); Console.ReadKey(); } }
public async Task <ActionResult <IEnumerable <string> > > Get() { var log = new List <string>(); var sessionId = Guid.NewGuid().ToString(); log.Add($"Creating session {sessionId}"); IMessageSession session = await _sessionClient.AcceptMessageSessionAsync(sessionId); Message response = null; var t = session.ReceiveAsync(new TimeSpan(0, 5, 0)) .ContinueWith(m => response = m.Result) .ContinueWith(m => log.Add($"received response from service for {sessionId}")); var message = new Message(Encoding.UTF8.GetBytes("test message")) { SessionId = sessionId }; await _messageSender.SendAsync(message); log.Add($"Sent work request for {sessionId}"); await t; await session.CompleteAsync(response.SystemProperties.LockToken); log.Add($"Completed session: {sessionId}"); return(log); }
public async Task <List <Message> > ReceiveMessagesAsync() { var messages = new List <Message>(); IMessageSession session = await _sessionClient.AcceptMessageSessionAsync(_serviceBusContext.SessionId); if (session == null) { return(messages); } for (int i = 0; i < _serviceBusContext.MaxConcurrentMessagesToBeRetrieved; i++) { Message message = await session.ReceiveAsync(_serviceBusContext.OperationTimeout); if (message == null) { break; } messages.Add(message); await session.CompleteAsync(message.SystemProperties.LockToken); } await session.CloseAsync(); return(messages); }
public async Task <string> ExecuteRequestReplyOverSyncAsync(object content, bool waitForReply = true) { // Set/lock session string replySessionId = Guid.NewGuid().ToString(); IMessageSession session = await _replySessionClient.AcceptMessageSessionAsync(replySessionId); // lock session try { // Arrange payload string raw = JsonConvert.SerializeObject(content); var message = new Message { Body = Encoding.UTF8.GetBytes(raw), ReplyToSessionId = replySessionId // tell recipient to reply using this session ID }; // Send request using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) await _requestClient.SendAsync(message); // Exit early if you don't want to wait for reply if (waitForReply == false) { return($"Successfully sent request with sessionId: {replySessionId}"); } // Receive reply Message reply = await session.ReceiveAsync(TimeSpan.FromSeconds(10)); // 10s timeout if (reply == null) { return($"Failed to get reply within timeout for session {replySessionId}"); } string response = Encoding.UTF8.GetString(reply.Body); await session.CompleteAsync(reply.SystemProperties.LockToken); return(response); } finally { await session.CloseAsync(); // release exlusive lock } }
static async Task ReceiveSessionMessagesAsync(int numberOfSessions, int messagesPerSession) { Console.WriteLine("==================================================================="); Console.WriteLine("Accepting sessions in the reverse order of sends for demo purposes"); Console.WriteLine("==================================================================="); for (int i = 0; i < numberOfSessions; i++) { int messagesReceivedPerSession = 0; // AcceptMessageSessionAsync(i.ToString()) as below with session id as parameter will try to get a session with that sessionId. // AcceptMessageSessionAsync() without any messages will try to get any available session with messages associated with that session. IMessageSession session = await sessionClient.AcceptMessageSessionAsync(SessionPrefix + i.ToString()); if (session != null) { // Messages within a session will always arrive in order. Console.WriteLine("====================================="); Console.WriteLine($"Received Session: {session.SessionId}"); while (messagesReceivedPerSession++ < messagesPerSession) { Message message = await session.ReceiveAsync(); Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); // Complete the message so that it is not received again. // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default). await session.CompleteAsync(message.SystemProperties.LockToken); } Console.WriteLine($"Received all messages for Session: {session.SessionId}"); Console.WriteLine("====================================="); // Close the Session after receiving all messages from the session await session.CloseAsync(); } } }
private async Task ProcessMessagesFromQueueSession() { try { _processID = System.Diagnostics.Process.GetCurrentProcess().Id; _threadID = Thread.CurrentThread.ManagedThreadId; _instanceID = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"); //_tclient.TrackTrace($"InstanceID:{ _instanceid}"); #region receive the sessions from wo-xml and process the messages _sessionClient.OperationTimeout = new TimeSpan(0, 0, 5); //Console.WriteLine($"Start Receiving Session"); _tclient.TrackTrace($"InstanceID:{ _instanceID}, Start Receiving Session"); session = await _sessionClient.AcceptMessageSessionAsync(); if (session != null) { // Messages within a session will always arrive in order. _tclient.TrackTrace($"InstanceID:{ _instanceID}, Received Session: [{session.SessionId}]"); while (true) { //Read All the messages from sessions Message message = await session.ReceiveAsync(); if (message != null) { MemoryStream woBody = new MemoryStream(message.Body); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(woBody); var wordOrderID = WOCommonUtility.GetNodeValue(xmlDoc, "Source_WO_ID"); var workOrderPriority = WOCommonUtility.GetNodeValue(xmlDoc, "WOPriority"); var workOrderSequence = WOCommonUtility.GetNodeValue(xmlDoc, "QueueSequence"); var workOrderPostedDateTime = WOCommonUtility.GetNodeValue(xmlDoc, "PostedDateTime"); string query = $"Insert into tblQueueLog (ProcessedBy,WorkOrder,Sequence,Priority,PostedTime,ProcessedTime,ProcessID,ThreadID, InstanceId) " + $"values ('PocWebJob9090', '{wordOrderID}', '{workOrderSequence}', '{workOrderPriority}','{workOrderPostedDateTime}' , '{DateTime.UtcNow}','{_processID}','{_threadID }','{_instanceID}')"; await LogMesssagesInDb(query, _commonSettings.Value.SQLDBConnectionString); // Complete the message so that it is not received again. // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default). await session.CompleteAsync(message.SystemProperties.LockToken); } else { break; } } } else { //Console.WriteLine($"No any session available in queue to process from WebJob."); } } catch (ServiceBusTimeoutException timeOutEx) { string query = $"Insert into tblQueueLog (ProcessedBy,ProcessedTime,ProcessID,ThreadID, InstanceId, ExceptionDetails ) " + $"values ('PocWebJob9090', '{DateTime.UtcNow}','{_processID}','{_threadID}','{_instanceID}','Exception Type: ServiceBusTimeoutException, Queue session timed out')"; await LogMesssagesInDb(query, _commonSettings.Value.SQLDBConnectionString); _tclient.TrackException(timeOutEx, new Dictionary <string, string>() { { "ApplicationName", "PocWebJob9090" }, { "ModuleName", "Functions" }, { "Method", "ProcessMessagesFromQueue" }, { "ServiceBusTimeoutException", "Service bus session timeout, No sessions in FIFO order." }, { "InstanceID", _instanceID }, { "Message", timeOutEx.Message } }); } catch (SessionCannotBeLockedException lockedEx) { string query = $"Insert into tblQueueLog (ProcessedBy,ProcessedTime,ProcessID,ThreadID, InstanceId,ExceptionDetails ) " + $"values ('PocWebJob9090', '{DateTime.UtcNow}','{_processID}','{_threadID }','{_instanceID}','Exception Type: SessionCannotBeLockedException, The requested session cannot be accepted. It may be locked by another receiver.')"; await LogMesssagesInDb(query, _commonSettings.Value.SQLDBConnectionString); _tclient.TrackTrace($"The requested session cannot be accepted. It may be locked by another receiver."); _tclient.TrackException(lockedEx, new Dictionary <string, string>() { { "ApplicationName", "PocWebJob9090" }, { "ModuleName", "Functions" }, { "Method", "ProcessMessagesFromQueue" }, { "SessionCannotBeLockedException", "The requested session cannot be accepted. It may be locked by another receiver." }, { "Message", lockedEx.Message }, { "InstanceID", _instanceID } }); } catch (Exception ex) { string query = $"Insert into tblQueueLog (ProcessedBy,ProcessedTime,ProcessID,ThreadID,InstanceId,ExceptionDetails ) " + $"values ('PocWebJob9090', '{DateTime.UtcNow}','{_processID}','{_threadID }','{_instanceID}','Exception Type: Exception, exception Occurred while going to fetch message from queue.')"; await LogMesssagesInDb(query, _commonSettings.Value.SQLDBConnectionString); _tclient.TrackException(ex, new Dictionary <string, string>() { { "ApplicationName", "PocWebJob9090" }, { "ModuleName", "Functions" }, { "Method", "ProcessMessagesFromQueue" }, { "InstanceID", _instanceID }, { "Message", ex.Message } }); } #endregion }