public void WriteReadMessage()
        {
            var ids = new List<string>();
            var mq = new MessageQueue(@".\private$\QMM_");

            
            mq.Send("12345");
            mq.Send("23456");

            var msg = mq.Receive(new TimeSpan(0, 0, 0, 0, 1));
            if (msg != null)
                Console.WriteLine(msg.Body);

            mq.Dispose();
            mq = null;

            mq = new MessageQueue(@".\private$\QMM_");
            
            msg = mq.Receive(new TimeSpan(0, 0, 0, 0, 1));
            if (msg != null)
            {
                msg.Formatter = new XmlMessageFormatter(new Type[] {typeof (string)});
                Console.WriteLine(msg.Body);
            }
        }
Example #2
0
 protected override void Dispose(bool disposing)
 {
     if (disposing && _queue != null)
     {
         _queue.Dispose();
     }
 }
        public void StringMessageFormatter()
        {
            var ids = new List<string>();
            var mq = new MessageQueue(@".\private$\QMM_");

            mq.Formatter = new StringMessageFormatter();
            mq.Send("12345");
            mq.Send("23456");

            mq.Dispose();
            mq = null;

            mq = new MessageQueue(@".\private$\QMM_");

            for (int i = 0; i < 3; i++)
            {
                Message msg = null;
                try
                {
                    msg = mq.Receive(new TimeSpan(0, 0, 0, 0, 1));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                if (msg != null)
                {
                    msg.Formatter = new StringMessageFormatter();
                    Console.WriteLine(msg.Body);
                }
            }
        }
        public static void HandleError(MsmqPoisonMessageException error)
        {
            ProcessorQueue processorQueue = (ProcessorQueue)error.Data["processorQueue"];
            MessageQueue poisonQueue = new System.Messaging.MessageQueue(processorQueue.PoisonQueue);
            MessageQueue errorQueue = new System.Messaging.MessageQueue(processorQueue.ErrorQueue);

            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    // Send the message to the poison and error message queues.
                    poisonQueue.Send((IWorkflowMessage)error.Data["message"], MessageQueueTransactionType.Automatic);
                    errorQueue.Send((WorkflowErrorMessage)error.Data["errorMessage"], MessageQueueTransactionType.Automatic);
                    txScope.Complete();
                }
                catch (InvalidOperationException)
                {

                }
                finally
                {
                    poisonQueue.Dispose();
                    errorQueue.Dispose();
                }
            }
        }
Example #5
0
        /// <summary>
        /// Disconnect from queue
        /// </summary>
        protected void DisconnectInternal()
        {
            MessageQueue?.Close();
            MessageQueue?.Dispose();
            MessageQueue = null;

            Logger.Debug("Disconnect from Message Queue {%Queue}", ToJson());
        }
Example #6
0
 /// <summary>
 /// close the connection to the message queue
 /// </summary>
 public void Close()
 {
     if (mq != null)
     {
         mq.Close();
         mq.Dispose();
     }
 }
Example #7
0
 protected override void Dispose(bool disposing)
 {
     if (disposing && _queue != null)
     {
         _queue.Dispose();
         if (_useTemporaryQueue && msmq.MessageQueue.Exists(Address))
         {
             msmq.MessageQueue.Delete(Address);
         }
     }
 }
Example #8
0
        public static MsmqConnector OpenReceive(MsmqAddress address, bool enlist)
        {
            var queue = new MessageQueue(address.Proprietary, QueueAccessMode.Receive);
            queue.MessageReadPropertyFilter.SetAll();

            Log.Info(Diagnostics.OpeningQueueForReceive, address, enlist);

            if (!enlist || queue.Transactional)
                return new MsmqConnector(queue, address, enlist);

            queue.Dispose();
            Log.Error(Diagnostics.NonTransactionalQueue, address.Canonical);
            throw new EndpointException(string.Format(CultureInfo.InvariantCulture, Diagnostics.NonTransactionalQueue, address.Canonical));
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _receiveQueue.Dispose();
                    _sendQueue.Dispose();
                    _receiveQueue = null;
                    _sendQueue    = null;
                }

                _disposedValue = true;
            }
        }
Example #10
0
 internal static bool SendImpression2(int IDSubScheduleDetail)
 {
     try
     {
         MessageQueue MQ = new MessageQueue(server_msmq2);
         MQ.Send(string.Format("IDSub:{0}:{1:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, DateTime.Now),
             string.Format("IDSub:{0}:{1:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, DateTime.Now));
         MQ.Dispose();
         return true;
     }
     catch
     {
         return false;
     }
 }
Example #11
0
 public static string SendImpression3(int IDSubScheduleDetail)
 {
     try
     {
         MessageQueue MQ = new MessageQueue(server_msmq);
         MQ.Send(string.Format("IDSub:{0}:{1:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, DateTime.Now),
             string.Format("IDSub:{0}:{1:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, DateTime.Now));
         MQ.Dispose();
         MQ.Close();
         return "done";
     }
     catch(Exception ex)
     {
         return ex.Message;
     }
 }
Example #12
0
 public static bool SendClick(string IDSubScheduleDetail, string IDSubpage)
 {
     try
     {
         MessageQueue MQ = new MessageQueue(MQ_CLICK);
         MQ.Send(string.Format("IDSub:{0},{1}:{2:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, IDSubpage, DateTime.Now),
             string.Format("IDSub:{0},{1}:{2:dd/MM/yyyy HH-mm}", IDSubScheduleDetail, IDSubpage, DateTime.Now));
         MQ.Dispose();
         MQ.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            MessageQueue msgQ = new MessageQueue(_msgQRec);

           

            System.Messaging.Message m = new System.Messaging.Message();
            m.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });

            try
            {
                //When we pull the message off from the queue it will be in the form of a 
                //byte array
                m = msgQ.Receive();
                byte[] data = new byte[1024];
                m.BodyStream.Read(data, 0, 1024);
                string strMessage = ASCIIEncoding.ASCII.GetString(data);
                
                //load message into XmlDocument
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(strMessage);
             
                //Deserialize Xml Document into a typed C# object  
                var ser = new XmlSerializer(typeof(WorkOrderRequests));
                var wo = (WorkOrderRequests)ser.Deserialize(new StringReader(xml.OuterXml));
               
                //Populate our GUI
                txtFunctionalLocation.Text = wo.WorkOrderRequest[0].FunctionalLocation;
                txtMachineID.Text = wo.WorkOrderRequest[0].MachinedID;
                txtMaintenanceType.Text = wo.WorkOrderRequest[0].MaintenanceType;
                txtPlant.Text = wo.WorkOrderRequest[0].Plant;
                txtRequestedDate.Text = wo.WorkOrderRequest[0].RequestDate.ToString();
                txtWorkOrderID.Text = wo.WorkOrderRequest[0].WorkOrderID;

                btnCompleteWorkOrder.Visible = true;

                msgQ.Close();
                msgQ.Dispose();  
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("An exception has occurred {0}", ex.ToString()));
            }

        }
        public static void HandleComplete(ProcessorQueue processorQueue, IWorkflowMessage message)
        {
            MessageQueue completedQueue = new System.Messaging.MessageQueue(processorQueue.CompletedQueue);

            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    completedQueue.Send(message, MessageQueueTransactionType.Automatic);
                    txScope.Complete();
                }
                catch (InvalidOperationException)
                {

                }
                finally
                {
                    completedQueue.Dispose();
                }
            }
        }
Example #15
0
 public virtual void Dispose()
 {
     _queue.Dispose();
 }
 /// <summary>
 /// Closes the queue handle.  Cancel pending receive operation by closing the queue handle
 /// To properly dispose of the queue handle, ensure that EnableConnectionCache=false on the
 /// MessageQueue that this listener is configured to use.
 /// </summary>
 protected void CloseQueueHandle(MessageQueue mq)
 {
     lock (messageQueueMonitor)
     {
         mq.Close();
         mq.Dispose();
     }
 }
        // Peeks message (first/application-specified correlationId) from status queue
        private Message PeekFromStatusQueue(string correlationId)
        {
            string statusQueuePath = "FormatName:DIRECT=OS:" + this.queue.MachineName + @"\" + Parameters.STATUS_QUEUE;
            MessageQueue statusQueue = new MessageQueue(statusQueuePath);
            statusQueue.Formatter = new BinaryMessageFormatter();
            statusQueue.MessageReadPropertyFilter.AppSpecific = true;
            statusQueue.MessageReadPropertyFilter.CorrelationId = true;

            Message statusMessage = null;
            try
            {
                if (correlationId == null)
                {
                    statusMessage = statusQueue.PeekByLookupId(MessageLookupAction.First, 0);
                }
                else
                {
                    statusMessage = statusQueue.PeekByCorrelationId(correlationId, TimeSpan.Zero);
                }
            }
            catch (MessageQueueException)
            {
                // If status queue is empty, peek will throw MessageQueueException
                throw new InvalidOperationException();
            }

            statusQueue.Dispose();
            statusQueue.Close();
            return statusMessage;
        }
        // Missing fragments are marked as rejected in a separate transaction and are sent to sender's DLQ on commit.
        private void PerformHouseKeeping(string correlationId)
        {
            string subQueueName = Utilities.GetSubQueueName(correlationId);
            string subQueuePath = "FormatName:DIRECT=OS:" + this.queue.MachineName + @"\" + this.queue.QueueName + ";" + subQueueName;
            MessageQueue subQueue = new MessageQueue(subQueuePath);

            Message messageToReject = null;

            // MarkMessageRejected works only with transaction
            MessageQueueTransaction rejectTransaction = new MessageQueueTransaction();
            rejectTransaction.Begin();

            // ReceiveById to clear the first header fragment whose Id is put in all other fragment's correlation id
            // This is in a separate try-catch so that it proceeds with marking other fragments in case first fragment
            // is the one that is lost
            try
            {
                messageToReject = subQueue.ReceiveById(correlationId, rejectTransaction);
                NativeMethods.MarkMessageRejected(subQueue.FormatName, messageToReject.LookupId);
            }
            catch (MessageQueueException)
            {
                // Don't do anything
            }
            catch (InvalidOperationException)
            {
                // Don't do anything
            }

            // Marks other fragments in subqueue as rejected
            try
            {
                while (true)
                {
                    messageToReject = subQueue.ReceiveByCorrelationId(correlationId, rejectTransaction);
                    NativeMethods.MarkMessageRejected(subQueue.FormatName, messageToReject.LookupId);
                }
            }
            catch (MessageQueueException)
            {
                // Don't do anything and just come out of the loop
            }
            catch (InvalidOperationException)
            {
                // Don't do anything and just come out of the loop
            }

            // Safe reject in case message becomes available in main queue
            try
            {
                messageToReject = this.queue.ReceiveById(correlationId, rejectTransaction);
                NativeMethods.MarkMessageRejected(subQueue.FormatName, messageToReject.LookupId);
            }
            catch (MessageQueueException)
            {
                // Don't do anything
            }
            catch (InvalidOperationException)
            {
                // Don't do anything
            }

            // Mark other fragments in main queue as rejected
            try
            {
                while (true)
                {
                    messageToReject = this.queue.ReceiveByCorrelationId(correlationId, rejectTransaction);
                    NativeMethods.MarkMessageRejected(this.queue.FormatName, messageToReject.LookupId);
                }
            }
            catch (MessageQueueException)
            {
                // Don't do anything and just come out of the loop
            }
            catch (InvalidOperationException)
            {
                // Don't do anything and just come out of the loop
            }
            finally
            {
                subQueue.Dispose();
                subQueue.Close();

                rejectTransaction.Commit();
                rejectTransaction.Dispose();
            }
        }
 /// <summary>
 /// Add a job for the framework to process
 /// </summary>
 /// <param name="jobName">The name of the job in the framework's workflow file</param>
 /// <param name="message">A class containing the message data</param>
 public static void AddFrameworkJob(string jobName, IWorkflowMessage message)
 {
     // Add a message to the Queue
     ProcessorJob processorJob = new ProcessorJob() { JobName = jobName, CreatedDate = DateTime.Now };
     WorkflowConfiguration.LoadFrameworkConfig(processorJob);
     ProcessorQueue processorQueue = GetActiveQueue(processorJob, QueueOperationType.Delivery);
     MessageQueue workflowQueue = new MessageQueue(processorQueue.MessageQueue);
     MessageQueueTransaction transaction = new MessageQueueTransaction();
     try
     {
         if (processorQueue.MessageQueueType == MessageQueueType.Transactional)
         {
             transaction.Begin();
             workflowQueue.Send(message, jobName, transaction);
             transaction.Commit();
         }
         else
         {
             workflowQueue.Send(message, jobName);
         }
     }
     catch (Exception e)
     {
         if (processorQueue.MessageQueueType == MessageQueueType.Transactional &&
             transaction.Status == MessageQueueTransactionStatus.Pending)
             transaction.Abort();
         throw new WorkflowException("Error adding message to Queue", e);
     }
     finally
     {
         transaction.Dispose();
         workflowQueue.Dispose();
     }
 }
 /// <summary>
 /// Activates a subscription by starting
 /// to listen to the specified queue
 /// </summary>
 /// <param name="queue">Queue to activate</param>
 /// <param name="subscription">Subscription to activate</param>
 private void ActivateSubscription(MessageQueue queue, MsmqSubscription subscription)
 {
     try
      {
     _lock.AcquireWriterLock(Timeout.Infinite);
     _subscriptionsByID.Add(subscription.ID, subscription);
     // do we already have suscriptions to this queue?
     Receiver receiver = null;
     if ( !_queueReceivers.ContainsKey(queue.FormatName) )
     {
        receiver = new Receiver(queue, OnMessageReceived);
        _queueReceivers.Add(queue.FormatName, receiver);
     } else
     {
        receiver = _queueReceivers[queue.FormatName];
        receiver.AddRef();
        queue.Dispose();
     }
      } finally
      {
     _lock.ReleaseWriterLock();
      }
 }
Example #21
0
 public void Close()
 {
     _queue.Dispose();
 }
Example #22
0
 /// <summary>
 /// Disposes this instance and the underlying <see cref="System.Messaging.MessageQueue"/> instance.
 /// </summary>
 public void Dispose()
 {
     _Queue?.Dispose();
 }
        // Sends status message to status queue.
        // 0 - subqueue complete, 1 - subqueue ready for delete
        private void SendToStatusQueue(string correlationId, int subQueueStatus, string largeSequenceId)
        {
            string statusQueuePath = "FormatName:DIRECT=OS:" + this.queue.MachineName + @"\" + Parameters.STATUS_QUEUE;
            MessageQueue statusQueue = new MessageQueue(statusQueuePath);
            try
            {
                bool canRead = statusQueue.CanRead;
                bool canWrite = statusQueue.CanWrite;
                if ((!canRead) || (!canWrite))
                {
                    throw new LargeMessageQueueException(null,
                        "Transactional status queue should have both read and write access for this user. Current status is: Read=" +
                        canRead + ", Write=" + canWrite);
                }
            }
            catch (MessageQueueException mqe)
            {
                throw new LargeMessageQueueException("Transactional status queue not available", mqe);
            }

            Message statusMessage = new Message();
            statusMessage.AppSpecific = subQueueStatus;
            statusMessage.Formatter = new BinaryMessageFormatter();
            statusMessage.Body = largeSequenceId;
            if (correlationId != null)
            {
                statusMessage.CorrelationId = correlationId;
            }

            statusQueue.Send(statusMessage, MessageQueueTransactionType.Single);

            statusQueue.Dispose();
            statusQueue.Close();
        }
 /// <summary>
 /// Starts to run the framework
 /// </summary>
 /// <param name="exceptionsBeforeExit">Number of times to try and run the framework</param>
 /// <param name="currentExceptionNumber">Current Exception Number</param>
 /// <param name="pauseFor">Wait between retrys in seconds</param>
 private void RunFramework(int exceptionsBeforeExit, int currentExceptionNumber, int pauseFor)
 {
     try
     {
         MessageQueue workflowQueue = new MessageQueue(ProcessorQueue.MessageQueue);
         Guid QID = workflowQueue.Id;
         workflowQueue.Dispose();
         if (ProcessorQueue.MessageQueueType == MessageQueueType.Transactional)
             if (ProcessorQueue.MessageQueue.StartsWith(@".\"))
                 RunTransactionalFramework();
             else
                 RunRemoteTransactionalFramework();
         else
             RunFramework();
     }
     catch (Exception e)
     {
         currentExceptionNumber++;
         if (currentExceptionNumber <= exceptionsBeforeExit)
         {
             Thread.Sleep(pauseFor * 1000);
             RunFramework(exceptionsBeforeExit, currentExceptionNumber, pauseFor);
         }
         else
             throw new FrameworkFatalException("Fatal Error in the framework: " + e.Message, e);
     }
 }
        // Receives message (first/application-specified correlationId) from status queue
        // On delete flag set to true, the method receives message without transaction context
        private Message ReceiveFromStatusQueue(long lookupId, MessageQueueTransaction transaction, MessageQueueTransactionType transactionType, bool delete)
        {
            bool transactionTypeFlag = (transactionType == MessageQueueTransactionType.Automatic) ? true : false;
            string statusQueuePath = "FormatName:DIRECT=OS:" + this.queue.MachineName + @"\" + Parameters.STATUS_QUEUE;
            MessageQueue statusQueue = new MessageQueue(statusQueuePath);
            try
            {
                bool canRead = statusQueue.CanRead;
                bool canWrite = statusQueue.CanWrite;
                if ((!canRead) || (!canWrite))
                {
                    throw new LargeMessageQueueException(null,
                        "Transactional status queue should have both read and write access for this user. Current status is: Read=" +
                        canRead + ", Write=" + canWrite);
                }
            }
            catch (MessageQueueException mqe)
            {
                throw new LargeMessageQueueException("Transactional status queue not available", mqe);
            }

            statusQueue.Formatter = new BinaryMessageFormatter();
            statusQueue.MessageReadPropertyFilter.AppSpecific = true;
            statusQueue.MessageReadPropertyFilter.CorrelationId = true;

            Message statusMessage = null;
            try
            {
                if (lookupId == 0)
                {
                    if (transactionTypeFlag)
                    {
                        statusMessage = statusQueue.ReceiveByLookupId(MessageLookupAction.First, 0, transactionType);
                    }
                    else
                    {
                        statusMessage = statusQueue.ReceiveByLookupId(MessageLookupAction.First, 0, transaction);
                    }
                }
                else
                {
                    if (delete)
                    {
                        statusMessage = statusQueue.ReceiveByLookupId(lookupId);
                    }
                    else
                    {
                        if (transactionTypeFlag)
                        {
                            statusMessage = statusQueue.ReceiveByLookupId(MessageLookupAction.Current, lookupId, transactionType);
                        }
                        else
                        {
                            statusMessage = statusQueue.ReceiveByLookupId(MessageLookupAction.Current, lookupId, transaction);
                        }
                    }
                }
            }
            catch (MessageQueueException)
            {
                // If status queue is empty, receive will throw MessageQueueException
                throw new InvalidOperationException();
            }

            statusQueue.Dispose();
            statusQueue.Close();
            return statusMessage;
        }