private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string queueName = ConfigurationManager.AppSettings["MSMQLocation"];

            MessageQueue rmTxnQ = new MessageQueue(queueName);

            rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) });

            foreach (ListBoxItem itm in files.Items)
            {
                MessageQueueTransaction msgTx = new MessageQueueTransaction();
                msgTx.Begin();
                try
                {
                    string argument = "-i \"{0}\" -o \"{1}\" --preset \"" + ConfigurationManager.AppSettings["HandbrakePreset"] + "\"";

                    string destination = txtDestination.Text + "\\" + System.IO.Path.GetFileNameWithoutExtension(itm.ToolTip.ToString()) + ".m4v";

                    ProcessMessage p = new ProcessMessage() { CommandLine = argument, DestinationURL = destination, OrignalFileURL = itm.ToolTip.ToString() };

                    rmTxnQ.Send(p, msgTx);
                    results.Items.Insert(0, string.Format("{0} added to queue", p.OrignalFileURL));

                    msgTx.Commit();
                }
                catch (Exception ex)
                {
                    results.Items.Insert(0, ex.Message);
                    msgTx.Abort();
                }
            }
        }
		public override void GetMessageFromQueue(string messageId, MessageQueue queue, Action<Message> processMethod)
		{
			using (var transaction = new MessageQueueTransaction())
			{
				transaction.Begin();
				Logger.DebugFormat("Transaction for {0} started.", messageId);

				Message message;
				try
				{
					message = queue.ReceiveById(messageId, TimeSpan.FromSeconds(30), transaction);
					Logger.DebugFormat("Message with id {0} received.", messageId);
				}
				catch (Exception ex)
				{
					transaction.Abort();
					Logger.Error(
						string.Concat("Failed to receive message with id ", messageId, "transactions aborted.")
						, ex);
					return;
				}

				if (message != null)
				{
					processMethod(message);
				}

				if (transaction.Status != MessageQueueTransactionStatus.Aborted)
					transaction.Commit();
			}
		}
Beispiel #3
0
        static void Run()
        {
            MessageQueue queue = null;
            MessageQueueTransaction trans = null;
            try
            {
                queue = new MessageQueue();
                queue.Path = Constants.QUEUE_PATH;
                queue.DefaultPropertiesToSend.Recoverable = true;

                trans = new MessageQueueTransaction();
                trans.Begin();

                MyOrder order = new MyOrder();
                order.ID = DateTime.Now.Ticks.ToString();
                order.Name = "Order_" + order.ID;

                Message msg = new Message(order);

                queue.Send(msg, trans);
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Abort();
            }
            finally
            {
                queue.Close();
            }

            Console.WriteLine("message sent..");
        }
        /// <summary>
        /// 启动消息侦程序线程
        /// </summary>
        private void Start(MessageListener listener)
        {
            ThreadPool.STPStartInfo stp = new ThreadPool.STPStartInfo();
            stp.MaxStackSize = MaxThreads;
            stp.MaxWorkerThreads = MaxThreads;
            ThreadPool.SmartThreadPool smartThreadpool = new ThreadPool.SmartThreadPool(stp);

            while (true)
            {
                MQMessage message = null;
                if (messageQueue.QueueConfig.isTransactional)
                {
                    MessageQueueTransaction tran = new MessageQueueTransaction();
                    message = new MQMessage(tran);
                    message.Begin();
                    message.messageContent = messageQueue.Receive(tran).Body.ToString();
                }
                else
                {
                    message = new MQMessage(null);
                    message.messageContent = messageQueue.Receive().Body.ToString();
                }
                System.Threading.Interlocked.Increment(ref Counter);
                while (Counter >= MaxThreads)
                {
                    System.Threading.Thread.Sleep(100);
                }
                smartThreadpool.QueueWorkItem(CallBack, message);
            }
        }
Beispiel #5
0
        static void _orderQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            var orderQueue = (MessageQueue)sender;

            var transaction = new MessageQueueTransaction();
            transaction.Begin();

            Order order;

            try
            {
                var receivedMessage = orderQueue.Receive(transaction);
                receivedMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                order = Order.DeserializeXml(receivedMessage.Body.ToString());

                using (var db = new OrderContext())
                {
                    db.Orders.Add(order);
                    db.SaveChanges();
                }

                transaction.Commit();
            }
            catch
            {
                // TODO: Log something
                transaction.Abort();
            }
            finally
            {
                orderQueue.BeginPeek();
            }
        }
Beispiel #6
0
        private void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            if (OnMessageReceived == null) return;

            var transaction = new MessageQueueTransaction();
            transaction.Begin();

            try
            {
                var queueMessage = inputQueue.Receive(transaction);
                var headers = GetMessageHeaders(queueMessage);
                var message = new ChannelMessage(queueMessage.BodyStream);
                message.AddHeader(headers);
                OnMessageReceived(this, new MessageReceivedEventArgs { Message = message });
                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Abort();
                throw;
            }
            finally
            {
                inputQueue.BeginPeek();
            }
        }
Beispiel #7
0
        void Run()
        {
            MessageQueueTransaction transaction = new MessageQueueTransaction();
            while (!shouldStop)
            {
                try
                {
                    transaction.Begin();
                    Message message = requestQueue.Receive(new TimeSpan(0, 0, 1), transaction);

                    responseQueue.Send(message, transaction);
                    transaction.Commit();

                    synchronizedInvoke.BeginInvoke(addMessage, new object[] { requestQueueName, message });
                }
                catch (MessageQueueException e)
                {
                    if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                        Console.WriteLine("Receive failure on " + requestQueueName + " " + e.StackTrace,
                            System.Diagnostics.EventLogEntryType.Error);
                }
                finally
                {
                    if (transaction.Status == MessageQueueTransactionStatus.Pending)
                    {
                        transaction.Abort();
                    }
                }
            }
        }
Beispiel #8
0
        protected override MSMQ.Message RecieveCore(MSMQ.MessageQueueTransaction txn)
        {
            var msg = txn == null?_queue.Receive(TimeSpan.Zero, _cursor) : _queue.Receive(TimeSpan.Zero, _cursor, txn);

            Debug.Assert(IsInterestingSubject(msg), $"peeking said this message was interesting, but the received message label of '{msg.Label}' is not!");
            return(msg);
        }
        public void Send(Object message)
        {
            // Open the queue.
            using (var queue = new MessageQueue(_queueName.GetQueueFormatName()))
            {
                // Set the formatter to JSON.
                queue.Formatter = new MsmqMessageFormatter();

                // Since we're using a transactional queue, make a transaction.
                using (MessageQueueTransaction mqt = new MessageQueueTransaction())
                {
                    mqt.Begin();

                    // Create a simple text message.
                    Message myMessage = new Message(message, new MsmqMessageFormatter());
                    myMessage.Label = message.GetType().FullName;
                    myMessage.ResponseQueue = new MessageQueue(_queueName.GetQueueFormatName());

                    // Send the message.
                    queue.Send(myMessage, mqt);

                    mqt.Commit();
                }
            }
        }
Beispiel #10
0
 public void Dispatch(Commit commit)
 {
     try
     {
         Task.Run(() =>
         {
             foreach (var ev in commit.Events.Select(@event => Converter.ChangeTo(@event.Body, @event.Body.GetType())))
             {
                 try
                 {
                     using (var queue = new msmq.MessageQueue(".\\private$\\bankaccount-tx"))
                     {
                         var message        = new msmq.Message();
                         var jsonBody       = JsonConvert.SerializeObject(ev);
                         message.BodyStream = new MemoryStream(Encoding.Default.GetBytes(jsonBody));
                         var tx             = new msmq.MessageQueueTransaction();
                         tx.Begin();
                         queue.Send(message, tx);
                         tx.Commit();
                     }
                 }
                 catch (Exception ex)
                 {
                     Debugger.Break();
                 }
             }
         });
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
        public void MangledMessageIsNotReceived()
        {
            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                var transaction = new MessageQueueTransaction();
                transaction.Begin();
                messageQueue.Send(new Message
                {
                    Extension = Encoding.UTF32.GetBytes("this is definitely not valid UTF8-encoded JSON")
                }, transaction);
                transaction.Commit();
            }

            Thread.Sleep(5000);

            CleanUpDisposables();

            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                messageQueue.MessageReadPropertyFilter = new MessagePropertyFilter
                {
                    Extension = true
                };

                var transaction = new MessageQueueTransaction();
                transaction.Begin();

                var message = messageQueue.Receive(transaction);

                Assert.That(message, Is.Not.Null);
                Assert.That(Encoding.UTF32.GetString(message.Extension), Is.EqualTo("this is definitely not valid UTF8-encoded JSON"));

                transaction.Commit();
            }
        }
Beispiel #12
0
        static void MoveMessage(Message message, string destinationQueueName, bool leaveCopyInSourceQueue)
        {
            var sourceQueuePath = message.QueuePath;
            var destinationQueuePath = MsmqUtil.GetFullPath(destinationQueueName);

            using (var transaction = new MessageQueueTransaction())
            {
                transaction.Begin();
                try
                {
                    var sourceQueue = new MessageQueue(sourceQueuePath) {MessageReadPropertyFilter = DefaultFilter()};
                    var destinationQueue = new MessageQueue(destinationQueuePath);

                    var msmqMessage = sourceQueue.ReceiveById(message.Id, transaction);
                    destinationQueue.Send(msmqMessage, transaction);

                    if (leaveCopyInSourceQueue)
                    {
                        sourceQueue.Send(msmqMessage, transaction);
                    }

                    transaction.Commit();
                }
                catch
                {
                    transaction.Abort();
                    throw;
                }
            }

            Messenger.Default.Send(new MessageMoved(message, sourceQueuePath, destinationQueuePath, leaveCopyInSourceQueue));
        }
		public void Send2WithLabelWithTransaction ()
		{
			String label1 = "label1";
			String label2 = "label2";
			Message sent1 = new Message ("Message 1", new BinaryMessageFormatter ());
			Message sent2 = new Message ("Message 2", new BinaryMessageFormatter ());
			MessageQueue mq = MQUtil.GetQueue (MQUtil.CreateQueueName (), true);
			mq.MessageReadPropertyFilter.SetAll ();
			Assert.IsTrue(mq.Transactional, "Message Queue should be transactional");
			using (MessageQueueTransaction tx = new MessageQueueTransaction ()) {
				tx.Begin ();
				
				mq.Send (sent1, label1, tx);
				mq.Send (sent2, label2, tx);
				
				tx.Commit ();
				
				Message received1 = mq.Receive ();
				Assert.IsNotNull (received1.TransactionId, "TransactionId not set");
				Message received2 = mq.Receive ();
				Assert.IsNotNull (received2.TransactionId, "TransactionId not set");
				
				Assert.AreEqual (received1.TransactionId, received2.TransactionId, "Messages have differing TransactionIds");
				Assert.IsTrue (received1.TransactionId.Length > 1);
				Assert.AreEqual (sent1.Body, received1.Body, "Message 1 not delivered correctly");
				Assert.AreEqual (sent2.Body, received2.Body, "Message 2 not delivered correctly");
				Assert.AreEqual (label1, received1.Label, "Label 1 not passed correctly");
				Assert.AreEqual (label2, received2.Label, "Label 2 not passed correctly");
			}
		}
        private static void Main(string[] args)
        {
            const string message = "Testing MSMQ";

            List<MessageQueue> queues = CreateQueues(".\\private$\\FirstQueue",
                ".\\private$\\SecondQueue",
                ".\\private$\\ThirdQueue");

            var sender = new Sender();
            var receiver = new Receiver();

            /*
             * Send to all the queues within a transaction
             */
            using (var transaction = new MessageQueueTransaction())
            {
                transaction.Begin();

                foreach (MessageQueue queue in queues)
                {
                    sender.Send(queue, message, transaction);
                }

                transaction.Commit();
            }

            /*
             * Read from all the queues
             */
            receiver.StartReading(queues);

            Console.ReadKey();
        }
        public Boolean sendDeclMessage(string messageId, string outId, int sendType, string messageDetail, int place)
        {
            if (messageId == null && messageId == ""
                && outId == null && outId == ""
                && messageDetail == null && messageDetail == ""
                && sendType == 0
                && place == 0)
            {
                return false;
            }
            MessageQueueTransaction msgTransaction = new MessageQueueTransaction();

            try
            {
                mq = mqFactory.CreateMsgQueueFactory(sendType, place);

                using (TransactionScope scope = new TransactionScope())
                {

                    msgTransaction.Begin();
                    XmlDocument xmldoc = new XmlDocument();

                    if (place == (int)SendPlace.GOVERNMENT)
                    {

                        String key = configUtil.getGovPwd();
                        messageDetail = AESUtil.AesEncoding(messageDetail, key, Encoding.UTF8);

                        mq.SendEncryptMessage(messageDetail, msgTransaction, messageId);
                    }
                    else
                    {
                        xmldoc.LoadXml(messageDetail);
                        mq.SendMessage(xmldoc, msgTransaction, messageId);
                    }
                    Logger.Debug(messageDetail);

                    messageDeclService.createDeclMessage(messageId, outId, sendType, messageDetail,place);
                    messageRespService.createResponseMessage(messageId, outId, sendType,place);

                    scope.Complete();
                    msgTransaction.Commit();
                    return true;

                }
            } catch (Exception e)
            {
                msgTransaction.Abort();
                if ((int)CustomsDeclarationProxy.Constant.CustomsMessageType.MANIFEST== sendType)
                {
                    Logger.Error("shipmentPackId:" + outId + "send and insert manifest message failed!", e);
                }
                else if ((int)CustomsDeclarationProxy.Constant.CustomsMessageType.ORDER == sendType)
                {
                    Logger.Error("shipmentPackId:" + outId + "send and insert order message failed!", e);
                }
                return false;
            }
        }
        protected void MovePoisonMessageToErrorQueue(Message message, MessageQueueTransaction transaction)
        {
            var error = $"Message '{message.Id}' is classfied as a poison message and will be moved to '{errorQueue.QueueName}'";

            Logger.Error(error);

            errorQueue.Send(message, transaction);
        }
Beispiel #17
0
		public void SendInTransactionWithPathNotSet ()
		{
			MessageQueue q = new MessageQueue ();
			Message m = new Message ("foobar", new BinaryMessageFormatter ());
			MessageQueueTransaction tx = new MessageQueueTransaction ();
			
			q.Send (m, tx);
		}
Beispiel #18
0
 private void btnR_Click(object sender, EventArgs e)
 {
     try
     {
         if (this.chbChoose1.Checked)
         {
             MessageQueue queue = new MessageQueue(this.txtMSMQ1.Text) {
                 Formatter = new BinaryMessageFormatter()
             };
             System.Messaging.Message message = new System.Messaging.Message();
             MessageQueueTransaction transaction = new MessageQueueTransaction();
             transaction.Begin();
             try
             {
                 message = queue.Receive(TimeSpan.FromMilliseconds(500.0), transaction);
             }
             catch
             {
                 transaction.Commit();
             }
             StreamReader reader = new StreamReader(message.BodyStream, Encoding.ASCII);
             if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 this.txtPath1.Text = this.saveFileDialog1.FileName;
                 FileStream output = new FileStream(this.txtPath1.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                 BinaryWriter writer = new BinaryWriter(output);
                 writer.Write(Encoding.Default.GetBytes(reader.ReadToEnd()));
                 writer.Flush();
                 writer.Close();
                 transaction.Commit();
                 MessageBox.Show("发送成功!");
             }
         }
         else
         {
             MessageQueue queue2 = new MessageQueue(this.txtMSMQ1.Text) {
                 Formatter = new BinaryMessageFormatter()
             };
             System.Messaging.Message message2 = new System.Messaging.Message();
             StreamReader reader2 = new StreamReader(queue2.Receive(TimeSpan.FromMilliseconds(500.0)).BodyStream, Encoding.ASCII);
             if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 this.txtPath1.Text = this.saveFileDialog1.FileName;
                 FileStream stream2 = new FileStream(this.txtPath1.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                 BinaryWriter writer2 = new BinaryWriter(stream2);
                 writer2.Write(Encoding.Default.GetBytes(reader2.ReadToEnd()));
                 writer2.Flush();
                 writer2.Close();
                 MessageBox.Show("发送成功!");
             }
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show("发送失败!原因:" + exception.Message);
     }
 }
        public MsmqFetchedJob(MessageQueueTransaction transaction, string jobId)
        {
            if (transaction == null) throw new ArgumentNullException("transaction");
            if (jobId == null) throw new ArgumentNullException("jobId");

            _transaction = transaction;

            JobId = jobId;
        }
Beispiel #20
0
 public Session(Connection connection, AcknowledgementMode acknowledgementMode)
 {
     this.connection = connection;
     this.acknowledgementMode = acknowledgementMode;
     MessageConverter = connection.MessageConverter;
     if (this.acknowledgementMode == AcknowledgementMode.Transactional)
     {
         MessageQueueTransaction = new MessageQueueTransaction();
     }
 }
Beispiel #21
0
 public void Enqueue(IDbConnection connection, string queue, string jobId)
 {
     using (var messageQueue = GetMessageQueue(queue))
     using (var message = new Message { Label = jobId })
     using (var transaction = new MessageQueueTransaction())
     {
         transaction.Begin();
         messageQueue.Send(message, transaction);
         transaction.Commit();
     }
 }
Beispiel #22
0
 /// <summary>
 /// Message must be provided, Sends a given msg
 /// </summary>
 /// <param name="qMsg"></param>
 /// <param name="w">   </param>
 public static void SendQMsg(ref System.Messaging.MessageQueue qMsg, ref System.Messaging.Message w)
 {
     System.Messaging.MessageQueueTransaction mqt = new System.Messaging.MessageQueueTransaction();
     mqt.Begin();
     qMsg.Send(w, mqt);
     mqt.Commit();
     mqt.Dispose();
     mqt = null;
     w.Dispose();
     w = null;
 }
Beispiel #23
0
 public static void EnqueueJobId(string queue, string jobId)
 {
     using (var messageQueue = CleanMsmqQueueAttribute.GetMessageQueue(queue))
     using (var message = new Message { Body = jobId, Label = jobId, Formatter = new BinaryMessageFormatter() })
     using (var transaction = new MessageQueueTransaction())
     {
         transaction.Begin();
         messageQueue.Send(message, transaction);
         transaction.Commit();
     }
 }
        private Message ReceiveMessageByCorrelationId(System.Messaging.MessageQueue queue, string correlationId)
        {
            var messageQueueTransaction = new System.Messaging.MessageQueueTransaction();

            messageQueueTransaction.Begin();

            var message = _messageQueueManager.ReceiveByCorrelationId(queue, correlationId, TimeSpan.FromMilliseconds(0), messageQueueTransaction);

            messageQueueTransaction.Commit();

            return(message);
        }
        private Message ReceiveMessage(System.Messaging.MessageQueue queue)
        {
            var messageQueueTransaction = new System.Messaging.MessageQueueTransaction();

            messageQueueTransaction.Begin();

            var message = _messageQueueManager.Receive(queue, TimeSpan.FromMilliseconds(10), messageQueueTransaction);

            messageQueueTransaction.Commit();

            return(message);
        }
		public override void Send(params object[] messages)
		{
			using (var transaction = new MessageQueueTransaction())
			{
				transaction.Begin();
				foreach (var message in messages)
				{
					Queue.Send(message, transaction);
				}
				transaction.Commit();
			}
		}
Beispiel #27
0
        public void testbutton_Click(object sender, EventArgs e)
        {
            MessageQueue mq;
            string queueName = Properties.Settings.Default.MessageQueueName;
            if (MessageQueue.Exists(queueName))
            {
                mq = new MessageQueue(queueName);
            }
            else
            {
                mq = MessageQueue.Create(queueName, true);
            }

            gateway = new MsmqInGatewayWSService();

            MessageQueueTransaction transaction = new MessageQueueTransaction();
            //while (running)
               // {
                try
                {
                    transaction.Begin();
                    System.Messaging.Message message = mq.Receive(new TimeSpan(0, 0, 1), transaction);

                    Console.WriteLine("Message received");

                    msmqInMessage msmqMsg = new msmqInMessage();
                    msmqMsg.label = message.Label;
                    Console.WriteLine("Message received333");
                    msmqMsg.id = message.Id;
                    Console.WriteLine("Message received222");
                    msmqMsg.body = readFully(message.BodyStream);

                    Console.WriteLine("Commit");
                    transaction.Commit();

                    messageList.Items.Add(msmqMsg.label);
                    messageQueues.Add(msmqMsg.id, msmqMsg);
                }
                catch (MessageQueueException mqe)
                {
                    if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                        Console.WriteLine("MessageQueue failure: " + mqe.Message);
                }
                finally
                {
                    if (transaction.Status == MessageQueueTransactionStatus.Pending)
                    {
                        transaction.Abort();
                    }
                }
               // }
        }
 public void SendAMessageWithInvalidHeadersToTheAuditQueue()
 {
     // Generate a bad msg to test MSMQ Audit Queue Importer
     // This message should fail to parse to a transport message because of the bad header and so should end up in the Particular.ServiceControl.Errors queue
     var q = new MessageQueue(MsmqUtilities.GetFullPath(Address.Parse("audit")), false, true, QueueAccessMode.Send);
     using (var tx = new MessageQueueTransaction())
     {
         tx.Begin();
         var message = new Message("Message with invalid headers"){Extension = new byte[]{1}};
         q.Send(message, tx);
         tx.Commit();
     }
 }
        public override async Task ReceiveMessage()
        {
            Message message = null;

            try
            {
                using (var msmqTransaction = new MessageQueueTransaction())
                {
                    msmqTransaction.Begin();

                    if (!TryReceive(msmqTransaction, out message))
                    {
                        return;
                    }

                    Dictionary<string, string> headers;

                    if (!TryExtractHeaders(message, out headers))
                    {
                        MovePoisonMessageToErrorQueue(message, msmqTransaction);

                        msmqTransaction.Commit();
                        return;
                    }

                    var shouldCommit = await ProcessMessage(msmqTransaction, message, headers).ConfigureAwait(false);

                    if (shouldCommit)
                    {
                        msmqTransaction.Commit();
                    }
                    else
                    {
                        msmqTransaction.Abort();
                    }
                }
            }
            // We'll only get here if Commit/Abort/Dispose throws which should be rare.
            // Note: If that happens the attempts counter will be inconsistent since the message might be picked up again before we can register the failure in the LRU cache.
            catch (Exception exception)
            {
                if (message == null)
                {
                    throw;
                }

                failureInfoStorage.RecordFailureInfoForMessage(message.Id, exception);
            }
        }
Beispiel #30
0
 public static void PutMessageOnQueue(string body, string queueName)
 {
     using (var queue = CreateQueue(queueName))
     {
         if (queue.Transactional)
         {
             var transaction = new MessageQueueTransaction();
             transaction.Begin();
             queue.Send(body, transaction);
             transaction.Commit();
         }
         else
             queue.Send(body);
     }
 }
Beispiel #31
0
        static void Main(string[] args)
        {
            string queueName = ConfigurationManager.AppSettings["MSMQLocation"];

            if (args.Count() != 4)
            {
                Console.WriteLine("needs 4 params: sourcedir sourcefiletypes dstdir dstfileformat");
                return;
            }

            try
            {
                MessageQueue rmTxnQ = new MessageQueue(queueName);

                rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) });

                string[] files = Directory.GetFiles(args[0], args[1], SearchOption.AllDirectories);
                int count = 0;
                foreach (string s in files)
                {
                    MessageQueueTransaction msgTx = new MessageQueueTransaction();
                    msgTx.Begin();
                    try
                    {
                        string argument = "-i \"{0}\" -o \"{1}\" --preset \"" + ConfigurationManager.AppSettings["HandbrakePreset"] + "\"";

                        string destination = args[2] + "\\" + Path.GetFileNameWithoutExtension(s) + args[3];

                        ProcessMessage p = new ProcessMessage() { CommandLine = argument, DestinationUrl = destination, OrignalFileUrl = s };

                        rmTxnQ.Send(p, msgTx);
                        Console.WriteLine("Adding message for {0} to queue", s);
                        count++;
                        msgTx.Commit();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        msgTx.Abort();
                    }
                }
                Console.WriteLine("added {0} items to queue. Queue count now {1}", count, rmTxnQ.GetAllMessages().Count());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #32
0
        static void Main(string[] args)
        {
            try
            {
                MessageQueue rmTxnQ = new MessageQueue(ConfigurationManager.AppSettings["MSMQLocation"]);

                Console.WriteLine("I CAN READZ MSMQ?: {0}", rmTxnQ.CanRead);
                while (rmTxnQ.CanRead)
                {
                    rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) });

                    MessageQueueTransaction msgTx = new MessageQueueTransaction();
                    msgTx.Begin();
                    try
                    {
                        rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) });

                        System.Messaging.Message msgTxn = rmTxnQ.Receive(MessageQueueTransactionType.Single);

                        ProcessMessage msg = (ProcessMessage)msgTxn.Body;

                        Process p = new Process();

                        string cmdLine = string.Format(msg.CommandLine, msg.OrignalFileURL, msg.DestinationURL);
                        Console.WriteLine("Recieved message. Commandline: {0}", cmdLine);
                        Console.WriteLine("Starting at {0}", DateTime.Now);
                        Stopwatch st = new Stopwatch();
                        st.Start();
                        p.StartInfo = new ProcessStartInfo() { Arguments = cmdLine, UseShellExecute = true, FileName = ConfigurationManager.AppSettings["HandbrakeEXE"] };//, RedirectStandardOutput = true, RedirectStandardError = true,  };
                        p.Start();
                        p.WaitForExit();
                        Console.WriteLine("Finsihed at {0} - Total time: {1}", DateTime.Now, st.Elapsed);
                        msgTx.Commit();

                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Something went wrong... {0}", ex.Message);
                        msgTx.Abort();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
        public bool SendMessage(string queuePath, object message)
        {
            try
            {
                if (!MessageQueue.Exists(queuePath))
                {
                    this.logger.Log(string.Format("Queue {0} does not exist", queuePath));

                    return false;
                }

                using (var queue = new MessageQueue(queuePath, QueueAccessMode.Send))
                {
                    queue.Formatter = new XmlMessageFormatter(new[] { typeof(MentoringMessage) });

                    MessageQueueTransaction transaction = null;
                    if (queue.Transactional)
                    {
                        transaction = new MessageQueueTransaction();
                        transaction.Begin();
                    }

                    using (Message m = new Message(message) { Recoverable = true })
                    {
                        if (transaction != null)
                        {
                            queue.Send(m, transaction);
                        }
                        else
                        {
                            queue.Send(m);
                        }
                    }

                    if (transaction != null)
                    {
                        transaction.Commit();
                    }
                }

                return true;
            }
            catch (MessageQueueException ex)
            {
                this.logger.LogException(ex, string.Format("An error occured while deleting queue. Path: {0}", queuePath));
                return false;
            }
        }
Beispiel #34
0
        public static string DequeueJobId(string queue, TimeSpan timeout)
        {
            using (var messageQueue = CleanMsmqQueueAttribute.GetMessageQueue(queue))
            using (var transaction = new MessageQueueTransaction())
            {
                transaction.Begin();

                using (var message = messageQueue.Receive(timeout, transaction))
                {
                    message.Formatter = new BinaryMessageFormatter();
                    transaction.Commit();

                    return (string)message.Body;
                }
            }
        }
        private void SendMessage(BusMessage message, MessageQueueTransaction transaction = null)
        {
            try
            {
                Message msmqMessage = new Message();
                msmqMessage.Label = message.Label;
                msmqMessage.Body = message;
                msmqMessage.Formatter = formatter;
                messageQueue.Send(msmqMessage);
            }
            catch (Exception ex)
            {
                Logger.LogError("SendMessage:", ex);
            }

        }
Beispiel #36
0
 MSMQ.Message Receive(MSMQ.MessageQueueTransaction txn)
 {
     try
     {
         _queue.MessageReadPropertyFilter = Filters.Read; // read full details
         return(RecieveCore(txn));
     }
     catch (MSMQ.MessageQueueException ex) when(ex.MessageQueueErrorCode == MSMQ.MessageQueueErrorCode.IOTimeout)
     {
         // we have already peeked to see if a message is available, but another thread or process may have already read the message from the queue, hence the timeout
         return(null);
     }
     catch (MSMQ.MessageQueueException ex) when(ex.MessageQueueErrorCode == MSMQ.MessageQueueErrorCode.TransactionUsage)
     {
         // we attempted a transactions receive on a non-transactional queue
         _isTransactional = false;
         txn.Dispose();
         return(Receive(null)); // recurse without transaction
     }
 }
        private Message RemoveCurrent(TimeSpan timeout, MessageQueueTransaction transaction, MessageQueueTransactionType transactionType)
        {
            long timeoutInMilliseconds = (long)timeout.TotalMilliseconds;

            if (timeoutInMilliseconds < 0 || timeoutInMilliseconds > UInt32.MaxValue)
            {
                throw new ArgumentException(Res.GetString(Res.InvalidParameter, "timeout", timeout.ToString()));
            }

            if (this.index == 0)
            {
                return(null);
            }

            Message message = this.owner.ReceiveCurrent(timeout, NativeMethods.QUEUE_ACTION_RECEIVE,
                                                        CursorHandle, this.owner.MessageReadPropertyFilter, transaction, transactionType);

            --this.index;
            return(message);
        }
        private Message RemoveCurrent(TimeSpan timeout, MessageQueueTransaction transaction, MessageQueueTransactionType transactionType)
        {
            long totalMilliseconds = (long)timeout.TotalMilliseconds;

            if ((totalMilliseconds < 0L) || (totalMilliseconds > 0xffffffffL))
            {
                throw new ArgumentException(Res.GetString("InvalidParameter", new object[] { "timeout", timeout.ToString() }));
            }
            if (this.index == 0)
            {
                return(null);
            }
            Message message = this.owner.ReceiveCurrent(timeout, 0, this.Handle, this.owner.MessageReadPropertyFilter, transaction, transactionType);

            if (!this.useCorrectRemoveCurrent)
            {
                this.index--;
            }
            return(message);
        }
        private string SendMessage(System.Messaging.MessageQueue queue, object body, string correlationId = null)
        {
            var messageQueueTransaction = new System.Messaging.MessageQueueTransaction();

            messageQueueTransaction.Begin();

            var message = new Message {
                Body = body
            };

            if (correlationId != null)
            {
                message.CorrelationId = correlationId;
            }

            _messageQueueManager.Send(queue, message, messageQueueTransaction);

            messageQueueTransaction.Commit();

            return(message.Id);
        }
        public ActionResult Submit(string emailAddress)
        {
            //var workflow = new UnsubscribeWorkflow(emailAddress);
            //workflow.Run();
            var unsubscribeCommand = new UnsubscribeCommand
            {
                EmailAddress = emailAddress
            };

            using (var queue = new msmq.MessageQueue(".\\private$\\sixeyed.messagequeue.unsubscribe-tx"))
            {
                //var message = new msmq.Message(unsubscribeCommand);
                var message  = new msmq.Message();
                var jsonBody = JsonConvert.SerializeObject(unsubscribeCommand);
                message.BodyStream = new MemoryStream(Encoding.Default.GetBytes(jsonBody));
                var tx = new msmq.MessageQueueTransaction();
                tx.Begin();
                queue.Send(message, tx);
                tx.Commit();
            }
            return(View("Confirmation"));
        }
Beispiel #41
0
 static void Main(string[] args)
 {
     using (var queue = new msmq.MessageQueue(".\\private$\\sixeyed.messagequeue.unsubscribe-tx"))
     {
         while (true)
         {
             Console.WriteLine("Listening");
             using (var tx = new msmq.MessageQueueTransaction())
             {
                 tx.Begin();
                 var message            = queue.Receive(tx);
                 var bodyReader         = new StreamReader(message.BodyStream);
                 var jsonBody           = bodyReader.ReadToEnd();
                 var unsubscribeMessage = JsonConvert.DeserializeObject <UnsubscribeCommand>(jsonBody);
                 var workflow           = new UnsubscribeWorkflow(unsubscribeMessage.EmailAddress);
                 Console.WriteLine("Starting unsubscribe for: {0}, at: {1}", unsubscribeMessage.EmailAddress, DateTime.Now.TimeOfDay);
                 workflow.Run();
                 Console.WriteLine("Unsubscribe complete for: {0}, at: {1}", unsubscribeMessage.EmailAddress, DateTime.Now.TimeOfDay);
                 tx.Commit();
             }
         }
     }
 }
Beispiel #42
0
 public Message RemoveCurrent(MessageQueueTransaction transaction)
 {
     try
     {
         IMessage iMsg = delegateEnumerator.RemoveCurrent(transaction.DelegateTx);
         if (iMsg == null)
         {
             return(null);
         }
         return(new Message(iMsg, null, formatter));
     }
     catch (ConnectionException e)
     {
         throw new MessageQueueException(MessageQueueErrorCode.QueueNotAvailable, e.Message);
     }
     catch (MessageUnavailableException e)
     {
         throw new InvalidOperationException(e.Message, e);
     }
     catch (MonoMessagingException e)
     {
         throw new MessageQueueException(MessageQueueErrorCode.Generic, e.Message);
     }
 }
        /// <inheritdoc />
        public void Send(System.Messaging.MessageQueue messageQueue, Message message, System.Messaging.MessageQueueTransaction messageQueueTransaction)
        {
            try
            {
                if (messageQueueTransaction == null)
                {
                    messageQueue.Send(message);
                }
                else
                {
                    messageQueue.Send(message, messageQueueTransaction);
                }
            }
            catch (Exception exception)
            {
                _logger.Debug(exception, "Error Sending Message to Message Queues");

                throw new MessageQueueSendException(messageQueue, message, exception);
            }
        }
        public Message ReceiveByCorrelationId(string correlationId, TimeSpan timeout, MessageQueueTransaction transaction)
        {
            try
            {
                IMessage iMsg = delegateQueue.ReceiveByCorrelationId(correlationId, timeout, transaction.DelegateTx);
                if (iMsg == null)
                {
                    return(null);
                }

                return(new Message(iMsg, null, Formatter));
            }
            catch (ConnectionException e)
            {
                throw new MessageQueueException(MessageQueueErrorCode.QueueNotAvailable, e.Message);
            }
            catch (MessageUnavailableException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
            catch (MonoMessagingException e)
            {
                throw new MessageQueueException(MessageQueueErrorCode.Generic, e.Message);
            }
        }
 public Message Receive(MessageQueueTransaction transaction)
 {
     return(Receive());
 }
        public Message Receive(TimeSpan timeout, MessageQueueTransaction transaction)
        {
            IMessageConsumer consumer = getSession().CreateConsumer(getDestination());

            return(new NMSMessage(consumer.Receive(timeout)));
        }
 public Message ReceiveByCorrelationId(string correlationId, MessageQueueTransaction transaction)
 {
     throw new NotImplementedException();
 }
 public Message ReceiveById(string id, TimeSpan timeout, MessageQueueTransaction transaction)
 {
     throw new NotImplementedException();
 }
 public void Send(object obj, string label, MessageQueueTransaction transaction)
 {
     throw new NotImplementedException();
 }
 public Message RemoveCurrent(MessageQueueTransaction transaction)
 {
     throw new NotImplementedException();
 }
 /// <inheritdoc />
 public MessageQueueTransaction()
 {
     Transaction = new System.Messaging.MessageQueueTransaction();
 }
Beispiel #52
0
 public ReadOnlyMsmqMessage(MSMQ.Message mqm, MSMQ.MessageQueueTransaction txn = null)
 {
     Contract.Requires(mqm != null);
     _msg = mqm;
     _txn = txn;
 }
        /// <inheritdoc />
        public Message ReceiveByCorrelationId(System.Messaging.MessageQueue messageQueue, string correlationId, TimeSpan timeout, System.Messaging.MessageQueueTransaction messageQueueTransaction)
        {
            try
            {
                return(messageQueueTransaction == null?messageQueue?.ReceiveByCorrelationId(correlationId, timeout) : messageQueue.ReceiveByCorrelationId(correlationId, timeout, messageQueueTransaction));
            }
            catch (Exception exception)
            {
                if (exception is MessageQueueException messageQueueException && messageQueueException.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    return(null);
                }

                _logger.Debug(exception, "Error Receiving by Correlation Id Message from Message Queues");

                throw new MessageQueueReceiveException(messageQueue, correlationId, timeout, exception);
            }
        }
Beispiel #54
0
 protected virtual MSMQ.Message RecieveCore(MSMQ.MessageQueueTransaction txn)
 {
     return(txn == null?_queue.Receive(TimeSpan.Zero) : _queue.Receive(TimeSpan.Zero, txn));
 }