Exemple #1
0
        protected async void cmdSend1_Click(object sender, EventArgs e)
        {
            byte[]          dataArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            BrokeredMessage msg     = new BrokeredMessage(dataArr);

            msg.Properties.Add("suma", 1);
            msg.Properties.Add("srednia", 1);
            msg.ReplyToSessionId = Guid.NewGuid().ToString("N");
            await m_tc.SendAsync(msg);

            MessageSession         session = m_qc.AcceptMessageSession(msg.ReplyToSessionId, TimeSpan.FromSeconds(60));
            List <BrokeredMessage> lst     = new List <BrokeredMessage>();

            while (lst.Count < 3)
            {
                msg = await session.ReceiveAsync();

                //Potem można: session.ReceiveAsync(msg.SequenceNumber + 1)
                if (msg != null)
                {
                    lst.Add(msg);
                    await msg.CompleteAsync();
                }
            }
            lblInfo.Text = "";
            foreach (var item in lst)
            {
                lblInfo.Text += item.GetBody <string>();
            }
        }
        static void SendMessages(QueueClient requestClient, QueueClient responseClient)
        {
            // Send request messages to queue:
            Console.WriteLine("Sending request messages to queue {0}", requestClient.Path);
            Console.WriteLine("Receiving response messages on queue {0}", responseClient.Path);

            MessageSession receiver = responseClient.AcceptMessageSession(ReplyToSessionId);

            for (int i = 0; i < SampleManager.NumMessages; ++i)
            {
                // send request message
                BrokeredMessage message = CreateRequestMessage(i);
                requestClient.Send(message);
                SampleManager.OutputMessageInfo("REQUEST: ", message);

                // receive response message
                BrokeredMessage receivedMessage = receiver.Receive(TimeSpan.FromSeconds(ResponseMessageTimeout));
                if (receivedMessage != null)
                {
                    SampleManager.OutputMessageInfo("RESPONSE: ", message);
                    receivedMessage.Complete();
                }
                else
                {
                    Console.WriteLine("ERROR: Response timed out.");
                }
            }
            receiver.Close();

            Console.WriteLine();
        }
        public static void ReceiveQ()
        {
            Console.WriteLine("In Receive method().");

            TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(QReceiver.IssuerName, QReceiver.IssuerKey);
            Uri           serviceUri  = ServiceBusEnvironment.CreateServiceUri("sb", QReceiver.ServiceNamespace, string.Empty);

            MessagingFactory factory = null;

            factory = MessagingFactory.Create(serviceUri, credentials);

            QueueClient sessionQueueClient = factory.CreateQueueClient(QReceiver.QueueName);

            //Create sessionQueueClient and subscribe to SessionIDs that have a value of "Mike"
            MessageSession  sessionReceiver = sessionQueueClient.AcceptMessageSession("92610", TimeSpan.FromSeconds(60));
            BrokeredMessage receivedMessage;

            while ((receivedMessage = sessionReceiver.Receive(TimeSpan.FromSeconds(60))) != null)
            {
                Console.WriteLine("Received Messages.");
                var data = receivedMessage.GetBody <FireEvent>(new DataContractSerializer(typeof(FireEvent)));
                //Console.WriteLine(String.Format("Customer Name: {0}", data.CustomerName));
                Console.WriteLine("SessionID: {0}", receivedMessage.SessionId);
                //remove message from Topic
                receivedMessage.Complete();
            }

            Console.WriteLine("All received on this session...press enter to exit");
            Console.Read();
        }
        /// <summary>
        /// Get all messages with a specific session
        /// </summary>
        /// <param name="client">QueueClient</param>
        private void GetAllMessagesWithSession(QueueClient client)
        {
            foreach (MessageSession sessions in client.GetMessageSessions())
            {
                try
                {
                    MessageSession ses = client.AcceptMessageSession(sessions.SessionId);

                    BrokeredMessage item = ses.Receive(properties.ReceiveTimeout);

                    while (true)
                    {
                        if (item == null)
                        {
                            break;
                        }

                        if (SubmitMessage(item) == false)
                        {
                            ses.Abort();
                            break;
                        }
                        //allow setting timeout
                        item = ses.Receive(properties.ReceiveTimeout);
                    }
                }
                catch (Exception)
                {
                    break;
                }
            }
        }
        /// <summary>
        /// Get all messages that has a session
        /// </summary>
        /// <param name="client">QueueClient</param>
        private void GetSessionMessages(QueueClient client)
        {
            try
            {
                MessageSession ses = client.AcceptMessageSession(properties.Session);

                BrokeredMessage item = ses.Receive(properties.ReceiveTimeout);

                while (true)
                {
                    if (item == null)
                    {
                        break;
                    }

                    if (SubmitMessage(item) == false)
                    {
                        ses.Abort();
                        break;
                    }

                    //allow setting timeout
                    item = ses.Receive(properties.ReceiveTimeout);
                }
            }
            catch (Exception)
            {
                //probably lock
            }
        }
        private static void ReceiveMessages()
        {
            Console.WriteLine("\nReceiving message from Queue...");
            BrokeredMessage message = null;

            var sessions = queueClient.GetMessageSessions();

            foreach (var browser in sessions)
            {
                Console.WriteLine(string.Format("Session discovered: Id = {0}", browser.SessionId));
                var session = queueClient.AcceptMessageSession(browser.SessionId);

                while (true)
                {
                    try
                    {
                        message = session.Receive(TimeSpan.FromSeconds(5));

                        if (message != null)
                        {
                            Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>()));

                            if (session.SessionId == SessionId2)
                            {
                                // if this is the second session then let's send to the dead letter for fun
                                message.DeadLetter();
                            }
                            else
                            {
                                // Further custom message processing could go here...
                                message.Complete();
                            }
                        }
                        else
                        {
                            //no more messages in the queue
                            break;
                        }
                    }
                    catch (MessagingException e)
                    {
                        if (!e.IsTransient)
                        {
                            Console.WriteLine(e.Message);
                            throw;
                        }
                        else
                        {
                            HandleTransientErrors(e);
                        }
                    }
                }
            }
            queueClient.Close();
        }
Exemple #7
0
        public FileMessage ReceiveLargeMessage(CancellationTokenSource cancel)
        {
            var            largeMessageStream = new MemoryStream();
            MessageSession session            = _queueClient.AcceptMessageSession();

            _logger.LogMessage($"Message session Id: {session.SessionId}");
            _logger.LogMessage("Receiving sub messages");

            bool   isFirst  = true;
            string fileName = "";

            while (true)
            {
                BrokeredMessage subMessage = session.Receive(TimeSpan.FromSeconds(5));

                if (subMessage != null)
                {
                    if (cancel.IsCancellationRequested)
                    {
                        break;
                    }
                    try
                    {
                        if (isFirst)
                        {
                            //receive filename
                            fileName = subMessage.GetBody <string>();
                            isFirst  = false;
                        }
                        else
                        {
                            //receive filestream
                            Stream subMessageStream = subMessage.GetBody <Stream>();
                            subMessageStream.CopyTo(largeMessageStream);
                        }
                        subMessage.Complete();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex);
                    }
                }
                else
                {
                    _logger.LogMessage("Done!");
                    break;
                }
            }
            BrokeredMessage largeMessage = new BrokeredMessage(largeMessageStream, true);

            return(new FileMessage(fileName, largeMessage));
        }
        public async Task <ActionResult> Add(int a = 5, int b = 12)
        {
            int   result = 0;
            Param p      = new Param {
                A = a, B = b
            };
            BrokeredMessage msg = new BrokeredMessage(p);

            msg.Properties.Add("operation", 1);
            msg.ReplyToSessionId = Guid.NewGuid().ToString("N");
            await m_tc.SendAsync(msg);

            MessageSession session = m_qc.AcceptMessageSession(msg.ReplyToSessionId, TimeSpan.FromSeconds(60));

            msg = await session.ReceiveAsync();

            if (msg != null)
            {
                result = msg.GetBody <int>();
            }
            return(View(result));
        }
Exemple #9
0
        static void Main(string[] args)
        {
            ParseArgs(args);

            // Create MessageReceiver for queue which does not require session
            Console.Title = "MessageReceiver";
            QueueClient sessionlessQueueClient = CreateQueueClient(SampleManager.SessionlessQueueName);

            Console.WriteLine("Ready to receive messages from {0}...", sessionlessQueueClient.Path);

            lastReceive = DateTime.Now;
            ReceiveMessages(sessionlessQueueClient);

            // Create SessionReceiver for queue requiring session
            Console.Title = "SessionReceiver";
            QueueClient sessionQueueClient = CreateQueueClient(SampleManager.SessionQueueName);

            Console.Clear();
            Console.WriteLine("Ready to receive messages from {0}...", sessionQueueClient.Path);

            bool allSessionsAccepted = false;

            while (!allSessionsAccepted)
            {
                try
                {
                    // Please note that AcceptMessageSession(sessionId) can be used if sessionId is already known. This sample
                    // demonstrates where it is unknown.
                    Console.WriteLine("Checking for session...");
                    MessageSession sessionReceiver = sessionQueueClient.AcceptMessageSession(TimeSpan.FromSeconds(acceptSessionReceiverTimeout));

                    ReceiveSessionMessages(sessionReceiver);
                    Console.WriteLine("All received on this session");
                }
                catch (TimeoutException)
                {
                    Console.WriteLine("Got TimeoutException, no more sessions available");
                    allSessionsAccepted = true;
                }
            }

            Console.WriteLine("\nReceiver complete.");
            Console.ReadLine();
        }
        public void ProcessSessionQueue(QueueClient sourceClient, QueueClient destinationClient)
        {
            _activityLogger.Log($"[{sourceClient.Path}] - Processing queue requiring a session", 0, 1);

            var totalMessagesForwarded = 0;

            var messageSessions = sourceClient.GetMessageSessions();

            if (messageSessions.Any())
            {
                var sessionIds = new List <string>();

                // obtain session IDs and then close these sessions, as they are browse-only
                foreach (var messageSession in messageSessions)
                {
                    sessionIds.Add(messageSession.SessionId);
                    messageSession.Close();
                }

                foreach (var sessionId in sessionIds)
                {
                    _activityLogger.Log($"[{sourceClient.Path}] - Processing queue session ID: {sessionId} ");

                    var messagesRemaining = true;

                    while (messagesRemaining)
                    {
                        var messageSession = sourceClient.AcceptMessageSession(sessionId, _serverWaitTime);
                        var messages       = messageSession.ReceiveBatch(_messagesToHandle, _serverWaitTime);

                        var messageCount = messages.Count();
                        if (messageCount > 0)
                        {
                            _activityLogger.Log($"Batch of {messageCount} message(s) received for processing", 1);

                            var messagesForwarded = 0;

                            foreach (var message in messages)
                            {
                                // log message
                                _messageLogger?.Log($"Queue: [{sourceClient.Path}]\n{message.GetSingleLineContent()}\n");

                                destinationClient.Send(message.Clone());

                                messagesForwarded++;
                                totalMessagesForwarded++;

                                message.Complete();
                            }

                            _activityLogger.Log($"Processing complete: {messagesForwarded} message(s) forwarded", 1);
                        }
                        else
                        {
                            messagesRemaining = false;
                            _activityLogger.Log($"No {(totalMessagesForwarded > 0 ? "more " : "")}messages to process in this session", 1);
                        }

                        messageSession.Close();
                    }
                }
            }
            else
            {
                _activityLogger.Log("No sessions exist - no messages to forward", 1);
            }

            _activityLogger.Log($"[{sourceClient.Path}] - Completed processing queue - {totalMessagesForwarded} message(s) forwarded");
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Checkout Console");



            // Create the NamespaceManager
            NamespaceManager namespaceMgr =
                //new NamespaceManager(serviceBusUri, credentials);
                NamespaceManager.CreateFromConnectionString(AccountDetails.ConnectionString);

            // Create the MessagingFactory
            MessagingFactory factory =
                //MessagingFactory.Create(serviceBusUri, credentials);
                MessagingFactory.CreateFromConnectionString(AccountDetails.ConnectionString);

            // Delete the queue if it exists.
            if (namespaceMgr.QueueExists(AccountDetails.QueueName))
            {
                namespaceMgr.DeleteQueue(AccountDetails.QueueName);
            }



            // Create a description for the queue.
            QueueDescription rfidCheckoutQueueDescription =
                new QueueDescription(AccountDetails.QueueName)
            {
                // Comment in to require duplicate detection
                RequiresDuplicateDetection          = true,
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10),

                // Comment in to require sessions
                RequiresSession = true
            };



            // Create a queue based on the queue description.
            namespaceMgr.CreateQueue(rfidCheckoutQueueDescription);

            // Use the MessagingFactory to create a queue client for the
            // specified queue.
            QueueClient queueClient = factory.CreateQueueClient(AccountDetails.QueueName);

            Console.WriteLine("Receiving tag read messages...");
            while (true)
            {
                int    receivedCount = 0;
                double billTotal     = 0.0;

                // Comment in to use a session receiver
                Console.ForegroundColor = ConsoleColor.Cyan;
                var messageSession = queueClient.AcceptMessageSession();
                Console.WriteLine("Accepted session: " + messageSession.SessionId);


                Console.ForegroundColor = ConsoleColor.Yellow;


                while (true)
                {
                    // Receive a tag read message.

                    // Swap comments to use a session receiver
                    //var receivedTagRead = queueClient.Receive(TimeSpan.FromSeconds(5));
                    var receivedTagRead = messageSession.Receive(TimeSpan.FromSeconds(5));

                    if (receivedTagRead != null)
                    {
                        // Process the message.
                        RfidTag tag = receivedTagRead.GetBody <RfidTag>();
                        Console.WriteLine("Bill for {0}", tag.Product);
                        receivedCount++;
                        billTotal += tag.Price;

                        // Mark the message as complete
                        receivedTagRead.Complete();
                    }
                    else
                    {
                        break;
                    }
                }

                if (receivedCount > 0)
                {
                    // Bill the customer.
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine
                        ("Bill customer ${0} for {1} items.", billTotal, receivedCount);
                    Console.WriteLine();
                    Console.ResetColor();
                }
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            string connStr = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            Console.WriteLine("Client");
            try
            {
                var payload = new Messages.Message();
                payload.MyMessage = "Hello world";

                var messageId = Guid.NewGuid().ToString();
                Console.WriteLine($"My Mesasge ID is {messageId}");
                BrokeredMessage bm = new BrokeredMessage(payload);
                bm.ReplyToSessionId = messageId;

                NamespaceManager ns = NamespaceManager.CreateFromConnectionString(connStr);


                if (!ns.QueueExists("MyQueueRequest"))
                {
                    QueueDescription queue = new QueueDescription("MyQueueRequest");
                    queue.EnablePartitioning = false;
                    queue.RequiresSession    = false;

                    ns.CreateQueue(queue);
                }
                if (!ns.QueueExists("MyQueueResponse"))
                {
                    QueueDescription queue = new QueueDescription("MyQueueResponse");
                    queue.EnablePartitioning = false;
                    queue.RequiresSession    = true;

                    ns.CreateQueue(queue);
                }

                // Sending to a queue
                QueueClient qClient = QueueClient.CreateFromConnectionString(connStr, "MyQueueRequest");
                qClient.Send(bm);
                Console.WriteLine("Sent Message!");


                // Listen for a session based message.
                QueueClient qClientResponse = QueueClient.CreateFromConnectionString(connStr, "MyQueueResponse");
                var         messageSession  = qClientResponse.AcceptMessageSession(messageId);
                messageSession.OnMessage(message =>
                {
                    Console.WriteLine("I've Received a Message.");

                    Console.WriteLine($"Message ID: {message.MessageId} - {message.SessionId}");

                    var receivedPayload = message.GetBody <Messages.Message>();

                    Console.WriteLine($"Message from service - {receivedPayload.MyMessage}");
                },
                                         new OnMessageOptions());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }