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();
                }
            }
        }
Example #2
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();
            }
        }
        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();
        }
Example #4
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();
                    }
                }
            }
        }
        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();
                }
            }
        }
		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");
			}
		}
Example #7
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 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();
			}
		}
Example #9
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 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();
            }
        }
Example #11
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();
            }
        }
Example #12
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..");
        }
        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;
            }
        }
Example #14
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);
     }
 }
Example #15
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();
     }
 }
Example #16
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;
 }
 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();
     }
 }
        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);
        }
Example #19
0
		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();
			}
		}
        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);
        }
Example #21
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);
            }
        }
Example #24
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);
     }
 }
Example #25
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;
            }
        }
Example #27
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);
            }
        }
Example #28
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;
                }
            }
        }
Example #29
0
 public static void SendMessage(this MessageQueue mq, Message message)
 {
     if (mq.Transactional)
     {
         using (var transaction = new MessageQueueTransaction())
         {
             transaction.Begin();
             mq.Send(message, transaction);
             transaction.Commit();
         }
     }
     else
     {
         mq.Send(message);
     }
 }
Example #30
0
        public IFetchedJob Dequeue(string[] queues, CancellationToken cancellationToken)
        {
            string jobId = null;
            MessageQueueTransaction transaction;
            var queueIndex = 0;

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                queueIndex = (queueIndex + 1) % queues.Length;
                var queueName = queues[queueIndex];

                transaction = new MessageQueueTransaction();

                using (var messageQueue = GetMessageQueue(queueName))
                {
                    try
                    {
                        transaction.Begin();

                        var message = queueIndex == 0
                            ? messageQueue.Receive(SyncReceiveTimeout, transaction)
                            : messageQueue.Receive(new TimeSpan(1), transaction);

                        message.Formatter = _formatter.Value;

                        jobId = (string)message.Body;

                    }
                    catch (MessageQueueException ex)
                    {
                        transaction.Abort();
                        transaction.Dispose();

                        if (ex.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                        {
                            throw;
                        }
                    }
                }
            } while (jobId == null);

            return new MsmqFetchedJob(transaction, jobId);
        }
        public ActionResult Submit(string emailAddress)
        {
            //var workflow = new UnsubscribeWorkflow(emailAddress);
            //workflow.Run();

            //fire and forget pattern
            var unsubscribeCommmand = new UnsubscribeCommand
            {
                EmailAddress = emailAddress
            };
            /*
            using (var queue = new msmq.MessageQueue(".\\private$\\sixeyed.messagequeue.unsubscribe"))
            {
                //default message type = XML
                //var message = new msmq.Message(unsubscribeCommmand);

                //Json format = smaller message size
                var jsonBody = JsonConvert.SerializeObject(unsubscribeCommmand);
                var message = new msmq.Message();
                message.BodyStream = new MemoryStream(Encoding.Default.GetBytes(jsonBody));

                queue.Send(message);
            }
            */

            using (var queue = new msmq.MessageQueue(".\\private$\\sixeyed.messagequeue.unsubscribe-tx"))
            {
                //default message type = XML
                //var message = new msmq.Message(unsubscribeCommmand);

                //Json format = smaller message size
                var jsonBody = JsonConvert.SerializeObject(unsubscribeCommmand);
                var message = new msmq.Message();
                message.BodyStream = new MemoryStream(Encoding.Default.GetBytes(jsonBody));

                var tx = new msmq.MessageQueueTransaction();

                    tx.Begin();
                    queue.Send(message,tx);
                    tx.Commit();

            }

            return View("Confirmation");
        }
Example #32
0
        static void Main(string[] args)
        {
            string path = @"kim-msi\private$\kimqueue2";
            MessageQueue queue = null;
            if (!MessageQueue.Exists(path))
            {
                queue = MessageQueue.Create(path, true);
            }
            else
                queue = new MessageQueue(path);
            //queue.Purge();
            //return;
            //   queue.ReceiveCompleted += Queue_ReceiveCompleted;//非同步寫法BeginReceive接收Send事件
            // queue.BeginReceive();
            var messages = queue.GetAllMessages();
            for (int i = 0; i < 10; i++)
            {
                if (messages.Count() == 0)
                {
                    Message message = new Message(i.ToString());
                    queue.Send(message, MessageQueueTransactionType.Single);
                }
                else
                {
                    MessageQueueTransaction tran = new MessageQueueTransaction();
                    tran.Begin();

                    var msg = queue.Receive(tran);
                    if (msg == null)
                        break;
                    System.Messaging.XmlMessageFormatter stringFormatter;
                    stringFormatter = new System.Messaging.XmlMessageFormatter(
                       new string[] { "System.String" });
                    msg.Formatter = stringFormatter;
                    Console.WriteLine(" e.Message:" + msg.Body);
                    if (i % 2 == 0)
                        tran.Dispose();
                    else
                        tran.Commit();
                }

            }
            Console.ReadLine();
        }
Example #33
0
 public void Send(object message)
 {
     var transaction = new MessageQueueTransaction();
     try
     {
         transaction.Begin();
         _messageQueue.Send(message, transaction);
         transaction.Commit();
     }
     catch
     {
         transaction.Abort();
         throw;
     }
     finally
     {
         transaction.Dispose();
     }
 }
Example #34
0
 private void OnMessagePeeked(object sender, PeekCompletedEventArgs e)
 {
     var transaction = new MessageQueueTransaction();
     try
     {
         transaction.Begin();
         var message = _messageQueue.Receive(transaction);
         MessageReceived(this, new MessageReceivedEventArgs(message));
     }
     catch
     {
         transaction.Abort();
         throw;
     }
     finally
     {
         transaction.Dispose();
     }
 }
        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"));
        }
Example #37
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();
             }
         }
     }
 }