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();
                }
            }
        }
Beispiel #2
1
 public Requestor(string requestQueueName,string replyQueueName)
 {
     requestQueue = new MessageQueue(requestQueueName);
     replyQueue = new MessageQueue(replyQueueName);
     replyQueue.MessageReadPropertyFilter.SetAll();
     ((XmlMessageFormatter)replyQueue.Formatter).TargetTypeNames = new string[] { "System.String,mscorlib" };
 }
Beispiel #3
0
        /// <summary>
        /// Sends a startup notification to the StromoLight queue.
        /// </summary>
        public static void SendNotification(string messageToSend)
        {
            MessageQueue startupQueue     = null;
            string       startupQueueName = @".\Private$\StromoLight_Startup";

            if (MessageQueue.Exists(startupQueueName))
            {
                startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup");
                System.Messaging.Message message = new System.Messaging.Message();
                message.Body  = messageToSend;
                message.Label = "Message from Task Designer";
                startupQueue.Send(message);
            }
            else
            {
                startupQueue = MessageQueue.Create(@".\Private$\StromoLight_Startup");

                startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup");

                System.Messaging.Message message = new System.Messaging.Message();
                message.Body  = messageToSend;
                message.Label = "Message from Task Designer";
                startupQueue.Send(message);
            }
        }
Beispiel #4
0
        public void InsertMessageinQueue()
        {
            try
            {
                MessageQueue msmq = null;
                if (MessageQueue.Exists(connection))
                {
                    msmq = new MessageQueue(connection);
                }
                else
                {
                    msmq = MessageQueue.Create(connection);
                }

                var msg = new Message();
                msg.Body = "SampleMessage ";

                msg.Label = "Msg" + i.ToString();
                ++i;
                msmq.Send(msg);
                msmq.Refresh();
                //msmq.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        public void MessageCreator()
        {
            MessageQueueTemplate mqt = applicationContext["txqueue"] as MessageQueueTemplate;
            Assert.IsNotNull(mqt);        
            string path = @".\Private$\mlptestqueue";
            if (MessageQueue.Exists(path))
            {
                MessageQueue.Delete(path);
            }
            MessageQueue.Create(path, true);
            mqt.MessageQueueFactory.RegisterMessageQueue("newQueueDefinition", delegate
                                                                               {
                                                                                   MessageQueue mq = new MessageQueue();
                                                                                   mq.Path = path;                                                                                                      
                                                                                   // other properties
                                                                                   return mq;
                                                                               });

            Assert.IsTrue(mqt.MessageQueueFactory.ContainsMessageQueue("newQueueDefinition"));

            SendAndReceive("newQueueDefinition",mqt);

            SimpleCreator sc  = new SimpleCreator();
            mqt.MessageQueueFactory.RegisterMessageQueue("fooQueueDefinition", sc.CreateQueue );

        }
 private void recuperarFacturasToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         string rutaCola = @".\private$\facturas";
         if (!MessageQueue.Exists(rutaCola))
             MessageQueue.Create(rutaCola);
         MessageQueue cola = new MessageQueue(rutaCola);
         cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Factura) });
         int total = cola.GetAllMessages().Count();
         while (cola.GetAllMessages().Count() != 0)
         {
             System.Messaging.Message mensaje = cola.Receive();
             Factura facturaItem = (Factura)mensaje.Body;
             string postdata = "{\"Numero\":\"" + facturaItem.Numero + "\",\"Fecha\":\"" + facturaItem.Fecha + "\",\"Cliente\":\"" + facturaItem.Cliente + "\",\"ImporteBruto\":\"" + facturaItem.ImporteBruto + "\",\"ImporteVenta\":\"" + facturaItem.ImporteVenta + "\",\"ImporteIGV\":\"" + facturaItem.ImporteIGV + "\",\"ImporteTotalVenta\":\"" + facturaItem.ImporteTotalVenta + "\"}";
             byte[] data = Encoding.UTF8.GetBytes(postdata);
             HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23440/Facturas.svc/Facturas");
             req.Method = "POST";
             req.ContentLength = data.Length;
             req.ContentType = "application/json";
             var reqStream = req.GetRequestStream();
             reqStream.Write(data, 0, data.Length);
             HttpWebResponse res = (HttpWebResponse)req.GetResponse();
             StreamReader reader = new StreamReader(res.GetResponseStream());
             string compraJson = reader.ReadToEnd();
             JavaScriptSerializer js = new JavaScriptSerializer();
         }
         MessageBox.Show(total + " facturas recuperadas", "Facturas Recuperadas");
     }
     catch {
         MessageBox.Show("Error de comunicación", "Error");            }
 }
		public void Purge()
		{
			using (var queue = new MessageQueue(_address.LocalName, QueueAccessMode.ReceiveAndAdmin))
			{
				queue.Purge();
			}
		}
Beispiel #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Simple Text");
            Console.WriteLine("Input for MSMQ Message:");
            string input = Console.ReadLine();

            MessageQueue queue = new MessageQueue(@".\private$\test");

            queue.Send(input);

            Console.WriteLine("Press Enter to continue");
            Console.ReadLine();

            Console.WriteLine("Output for MSMQ Queue");
            Console.WriteLine(queue.Receive().Body.ToString());
            Console.ReadLine();

            Console.WriteLine("Complex Text");

            User tester = new User();
            tester.Birthday = DateTime.Now;
            tester.Name = "Test Name";
            queue.Send(tester);

            Console.WriteLine("Output for MSMQ Queue");
            User output = (User)queue.Receive().Body;
            Console.WriteLine(output.Birthday.ToShortDateString());
            Console.ReadLine();
        }
        private void SendMessage(object item)
        {
            MessageQueue queue;

            if (MessageQueue.Exists(mqCreateTxt.Text))
            {
                queue = new System.Messaging.MessageQueue(mqCreateTxt.Text);
            }
            else
            {
                queue = MessageQueue.Create(mqCreateTxt.Text);
            }

            System.Messaging.Message messageItem = item as System.Messaging.Message;
            if (queue != null)
            {
                try
                {
                    queue.Send(messageItem);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Get the queued message from the message queue.
        /// </summary>
        /// <param name="serverAndQueuePath">The server and queue path name.</param>
        /// <returns>The queued message.</returns>
        public Message GetMessage(string serverAndQueuePath)
        {
            // Connect to the queue
            System.Messaging.MessageQueue serverQueue =
                new System.Messaging.MessageQueue(serverAndQueuePath);

            // Get the message.
            Message message = new Message();
            Object  o       = new Object();

            System.Type[] arrTypes = new System.Type[2];
            arrTypes[0]           = message.GetType();
            arrTypes[1]           = o.GetType();
            serverQueue.Formatter = new XmlMessageFormatter(arrTypes);

            // Create a transaction scope.
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
            {
                // Get the message
                message = ((Message)serverQueue.Receive(MessageQueueTransactionType.Automatic).Body);

                // Complete the transaction.
                scope.Complete();
            }

            // Return the message from the queue.
            return(message);
        }
Beispiel #11
0
        public void Start()
        {
            Task.Factory.StartNew(() =>
            {
                var name = string.Format(".\\Private$\\{0}", typeof(IIpcClient).Name);

                if (System.Messaging.MessageQueue.Exists(name) == true)
                {
                    queue = new System.Messaging.MessageQueue(name);
                }
                else
                {
                    queue = System.Messaging.MessageQueue.Create(name);
                }

                queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                while (true)
                {
                    var msg  = queue.Receive();
                    var data = msg.Body.ToString();
                    this.OnReceived(new DataReceivedEventArgs(data));
                }
            });
        }
Beispiel #12
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.pictureBox1 = new System.Windows.Forms.PictureBox();
     this.drawingMQ   = new System.Messaging.MessageQueue();
     this.SuspendLayout();
     //
     // pictureBox1
     //
     this.pictureBox1.Location = new System.Drawing.Point(8, 8);
     this.pictureBox1.Name     = "pictureBox1";
     this.pictureBox1.Size     = new System.Drawing.Size(416, 216);
     this.pictureBox1.TabIndex = 0;
     this.pictureBox1.TabStop  = false;
     this.pictureBox1.Paint   += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
     //
     // drawingMQ
     //
     this.drawingMQ.Path = "synergy\\drawings";
     this.drawingMQ.SynchronizingObject = this;
     this.drawingMQ.ReceiveCompleted   += new System.Messaging.ReceiveCompletedEventHandler(this.drawingMQ_ReceiveCompleted);
     //
     // Form2
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize        = new System.Drawing.Size(440, 229);
     this.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.pictureBox1
     });
     this.Name  = "Form2";
     this.Text  = "Drawing Receiver";
     this.Load += new System.EventHandler(this.Form2_Load);
     this.ResumeLayout(false);
 }
 public override void InitializeOutbound(string addressName,
                                         MessagePattern pattern,
                                         bool isTemporary = false)
 {
     InitializeProperties(Direction.Outbound, addressName, pattern, isTemporary);
     _queue = new msmq.MessageQueue(MessageAddress.Address);
 }
        /// <summary>
        /// Connect to or Create the Academic Queue
        /// </summary>
        private void queueCreate(string mqPath, string mqName)
        {
            try
            {
                mqPath = @mqPath;
                mqName = @mqName;

                if (!System.Messaging.MessageQueue.Exists(mqPath))
                {
                    System.Messaging.MessageQueue.Create(mqPath, false);
                    SecurityPermissions.ACLQueue(mqPath);

                    // set other queue parameters
                    System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(mqPath);
                    mq.Label = mqName;
                    //assumption Queue is on this box
                    mq.MachineName      = ".";
                    mq.QueueName        = mqName;
                    mq.MaximumQueueSize = 10240;                      // Set max queue size to 10M
                }
            }
            catch (System.Exception)
            {
            }
        }
Beispiel #15
0
        public static bool VisualiserLoaded()
        {
            MessageQueue startupQueue     = null;
            string       startupQueueName = @".\Private$\StromoLight_Startup";

            if (MessageQueue.Exists(startupQueueName))
            {
                startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup");
                System.Messaging.Message peekedMessage = startupQueue.Peek(System.TimeSpan.FromSeconds(20));

                object lockObject = new object();
                string peekedMessageBody;

                lock (lockObject)
                {
                    peekedMessage.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
                    peekedMessageBody       = peekedMessage.Body.ToString();
                }

                //return true if visualiser started ok
                if (peekedMessageBody == "VSOK")
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #16
0
        public Queue2()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            //Q Creation
            string colaStr = @"FormatName:Direct=TCP:127.0.0.1\\private$\\MyQueue";

            //  MessageQueue rmQ = new MessageQueue(colaStr);
            //  rmQ.Send("sent to regular queue - Atul");

            if (MessageQueue.Exists(colaStr))
            {
                mq = new MessageQueue(colaStr);
            }
            else
            {
                mq = MessageQueue.Create(colaStr);
            }

            //if(MessageQueue.Exists(@".\Private$\MyQueue"))
            //    mq = new MessageQueue(@".\Private$\MyQueue");
            //else
            //    mq = MessageQueue.Create(@".\Private$\MyQueue");
        }
        public override void Configure(System.Xml.XmlElement element)
        {
            // Reflect some of the necessary protected methods on the SimpleCache class that are needed
            Type type = typeof(SimpleCache);
            getCachedItemMethod = type.GetMethod("GetCachedItem", BindingFlags.Instance | BindingFlags.NonPublic);
            purgeMethod = type.GetMethod("Purge", BindingFlags.Instance | BindingFlags.NonPublic);

            // Instantiate and configure the SimpleCache instance to be used for the local cache
            cache = new SimpleCache();
            cache.Configure(element);

            // Allow the base CacheBase class to configure itself
            base.Configure(element);

            // Check for and configure the queue
            if (element.HasAttribute("path"))
            {
                string path = element.GetAttribute("path");
                if (MessageQueue.Exists(path))
                {
                    queue = new MessageQueue(path);
                    queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(CachedItem) });

                    // Start the listener thread
                    listen = true;
                    listenThread = new Thread(new ThreadStart(Listen));
                    listenThread.IsBackground = true;
                    listenThread.Start();
                }
                else
                {
                    throw new ConfigurationErrorsException("The specified queue path (" + path + ") does not exist.");
                }
            }
        }
Beispiel #18
0
        public static MSMQ.MessageQueue GetOrAddQueue(Uri uri, out QueueDetails details)
        {
            details = default(QueueDetails);
            if (uri == null)
            {
                return(null);
            }

            details = UriToQueueName(uri);
            if (!details.Valid)
            {
                return(null);
            }

            var q = (MSMQ.MessageQueue)Queues.Get(details.QueueName);

            if (q == null)
            {
                q = new MSMQ.MessageQueue(details.QueueName);
                Queues.AddOrGetExisting(details.QueueName, q, new CacheItemPolicy {
                    SlidingExpiration = TimeSpan.FromMinutes(20)
                });
            }
            return((MSMQ.MessageQueue)q);
        }
Beispiel #19
0
 public Message getFirstReservation()
 {
     MessageQueue queue = new MessageQueue(FlyHotelConstant.ADRESSE_QUEUE);
     queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(DemandeReservation) });
     Message messageResa = queue.Peek();
     return messageResa;
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            var queueAddress = args != null && args.Length == 1 ? args[0] :
                               ".\\private$\\sixeyed.messagequeue.unsubscribe";

            using (var queue = new msmq.MessageQueue(queueAddress))
            {
                while (true)
                {
                    Console.WriteLine("Listening on: {0}", queueAddress);
                    var message     = queue.Receive();
                    var messageBody = message.BodyStream.ReadFromJson(message.Label);
                    //TODO - would use a factory/IoC/MEF for this:
                    var messageType = messageBody.GetType();
                    if (messageType == typeof(UnsubscribeCommand))
                    {
                        Unsubscribe((UnsubscribeCommand)messageBody);
                    }
                    else if (messageType == typeof(DoesUserExistRequest))
                    {
                        CheckUserExists((DoesUserExistRequest)messageBody, message);
                    }
                }
            }
        }
Beispiel #21
0
 private static void PurgeQueue(string queuePath)
 {
     using (var queue = new MessageQueue(queuePath))
     {
         queue.Purge();
     }
 }
        public MessageQueue GetMessageQueue(string strQueuePath, bool CreateIfNotExists)
        {
            MessageQueue _mQueue = null;

            try
            {
                if (MessageQueue.Exists(strQueuePath))
                {
                    //creates an instance MessageQueue
                    _mQueue = new System.Messaging.MessageQueue(strQueuePath);
                }
                else
                {
                    if (CreateIfNotExists)
                    {
                        //creates a new private queue
                        _mQueue = MessageQueue.Create(strQueuePath);
                        _mQueue.SetPermissions("EveryOne", MessageQueueAccessRights.FullControl);
                        _mQueue.Formatter = new ActiveXMessageFormatter();
                    }
                }
                _mQueue.Formatter = new ActiveXMessageFormatter();
                return(_mQueue);
            }
            catch (Exception Ex)
            {
                Logger.Error("QueueManager", "GetMessageQueue(\"" + strQueuePath + "\")", Ex);
                throw Ex;
            }
        }
        /// <summary>
        /// Constructs the <see cref="MsmqMessageQueue"/>, using the specified input queue. If the queue does not exist,
        /// it will attempt to create it. If it already exists, it will assert that the queue is transactional.
        /// </summary>
        public MsmqMessageQueue(string inputQueueName, bool allowRemoteQueue = false)
        {
            if (inputQueueName == null) return;

            try
            {
                machineAddress = GetMachineAddress();

                inputQueuePath = MsmqUtil.GetPath(inputQueueName);
                MsmqUtil.EnsureMessageQueueExists(inputQueuePath);
                MsmqUtil.EnsureMessageQueueIsTransactional(inputQueuePath);

                if (!allowRemoteQueue)
                {
                    EnsureMessageQueueIsLocal(inputQueueName);
                }

                inputQueue = GetMessageQueue(inputQueuePath);

                this.inputQueueName = inputQueueName;
            }
            catch (MessageQueueException e)
            {
                throw new ArgumentException(
                    string.Format(
                        @"An error occurred while initializing MsmqMessageQueue - attempted to use '{0}' as input queue",
                        inputQueueName), e);
            }
        }
Beispiel #24
0
    private void HookQueue()
    {
        try
        {
            // This is necessary since we unhook
            // when we are stopped.

            if (this.qOrders == null)
            {
                this.qOrders = new System.Messaging.MessageQueue(this.m_Path);
            }

            // Start waiting for messages to arrive.

            this.qOrders.BeginReceive();
        }
        catch (MessageQueueException exp)
        {
            this.EventLog.WriteEntry(exp.Message);
        }
        catch (Exception exp)
        {
            this.EventLog.WriteEntry(exp.Message);
        }
    }
Beispiel #25
0
        /// <include file='doc\QueuePathEditor.uex' path='docs/doc[@for="QueuePathEditor.EditValue"]/*' />
        /// <devdoc>
        ///      Edits the given object value using the editor style provided by
        ///      GetEditorStyle.  A service provider is provided so that any
        ///      required editing services can be obtained.
        /// </devdoc>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (provider != null)
            {
                IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (edSvc != null)
                {
                    QueuePathDialog dialog = new QueuePathDialog(provider);
                    MessageQueue queue = null;
                    if (value is MessageQueue)
                        queue = (MessageQueue)value;
                    else if (value is string)
                        queue = new MessageQueue((string)value);
                    else if (value != null)
                        return value;

                    if (queue != null)
                        dialog.SelectQueue(queue);

                    IDesignerHost host = (IDesignerHost)provider.GetService(typeof(IDesignerHost));
                    DesignerTransaction trans = null;
                    if (host != null)
                        trans = host.CreateTransaction();

                    try
                    {
                        if ((context == null || context.OnComponentChanging()) && edSvc.ShowDialog(dialog) == DialogResult.OK)
                        {
                            if (dialog.Path != String.Empty)
                            {
                                if (context.Instance is MessageQueue || context.Instance is MessageQueueInstaller)
                                    value = dialog.Path;
                                else
                                {
                                    value = MessageQueueConverter.GetFromCache(dialog.Path);
                                    if (value == null)
                                    {
                                        value = new MessageQueue(dialog.Path);
                                        MessageQueueConverter.AddToCache((MessageQueue)value);
                                        if (context != null)
                                            context.Container.Add((IComponent)value);
                                    }
                                }

                                context.OnComponentChanged();
                            }
                        }
                    }
                    finally
                    {
                        if (trans != null)
                        {
                            trans.Commit();
                        }
                    }
                }
            }

            return value;
        }
Beispiel #26
0
    private void InitializeComponent()
    {
        System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();

        this.qOrders = new System.Messaging.MessageQueue();

        //

        //qOrders

        //

        this.qOrders.Formatter = new System.Messaging.XmlMessageFormatter(new string[] { "Server.MSMQOrders,Server" });

        this.qOrders.Path = (string)configurationAppSettings.GetValue("msmqOrders.Path", typeof(System.String));

        //

        //WatchMSMQ

        //

        this.CanHandlePowerEvent = true;

        this.CanPauseAndContinue = true;

        this.CanShutdown = true;

        this.ServiceName = "WatchMSMQ";
    }
Beispiel #27
0
		public string GetElementFromSource(string pQueuePach)
		{
			System.Messaging.Message sourceMessage;
			string str="";
			
			try
			{
				sourceQueue = new System.Messaging.MessageQueue(pQueuePach);
				((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[]{"System.String"};
				if(sourceQueue.GetAllMessages ().Length >0)
				{
					sourceMessage = sourceQueue.Receive(System.Messaging.MessageQueueTransactionType.Automatic);
					// Set the formatter.
					//	sourceQueue.Formatter = new XmlMessageFormatter(new Type[]	{typeof(String)});
					((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[]{"Empleado"};

					str = (string)sourceMessage.Body;
				}
			
				return str;
			}
			catch(MessageQueueException e)
			{
				throw e;
			}
			catch(Exception e)
			{
				throw e;
			}
		}
Beispiel #28
0
        /// <summary>
        /// Purge Queue With Path Name.
        /// </summary>
        /// <param name="path">the queue name.</param>
        /// <returns>ResultModel:show the status of the request.</returns>
        internal ResultModel PurgeQueue(string path)
        {
            ResultModel resultModel = new ResultModel();

            try
            {
                System.Messaging.MessageQueue messageQueue = new System.Messaging.MessageQueue(path);
                messageQueue.Purge();
                resultModel.Result = (int)ResultsEnum.QueuePurged;
                _logger.LogDebug(string.Format("Queue : {0} Purged", path));
            }
            catch (System.Messaging.MessageQueueException ex)
            {
                KubeMQ.MSMQSDK.Results.MessageQueueException messageEx = new KubeMQ.MSMQSDK.Results.MessageQueueException(ex);
                _logger.LogCritical(string.Format("MSMQ Path:{0} Purge failed on ex :{1}", path, ex.Message));
                resultModel.Result    = (int)ResultsEnum.Error;
                resultModel.exception = messageEx;
            }
            catch (Exception ex)
            {
                resultModel.Result = (int)ResultsEnum.Error;
                _logger.LogCritical(string.Format("MSMQ Path:{0} Purge failed on ex :{1}", path, ex.Message));
                resultModel.exception = ex;
            }
            return(resultModel);
        }
        public object receiveByID(string MessageID, string InputQueue)
        {
            // Open existing queue
            using (MessageQueue queue = new MessageQueue(InputQueue))
            {
                //Peek to find message with the MessageID in the label
                while (true)
                {
                    Message[] peekedmessage = queue.GetAllMessages();
                    foreach (Message m in peekedmessage)
                    {
                        if (m.Label.StartsWith(MessageID))
                        {
                            using (Message message = queue.ReceiveById(m.Id))
                            {
                                RequestGuid = MessageID;
                                // Gets object type from the message label
                                Type objType = Type.GetType(message.Label.Split('|')[1], true, true);

                                // Derializes object from the stream
                                DataContractSerializer serializer = new DataContractSerializer(objType);
                                return serializer.ReadObject(message.BodyStream);
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Send message to existing queue from json format.
        /// </summary>
        /// <param name="meta">contain the queue general data for exemple:queue path , queue name.</param>
        /// <param name="body">the body as string to insert to the queue</param>
        /// <returns>ResultModel:show the status of the request.</returns>
        internal ResultModel SendJsonRequestToQueue(MSMQMeta meta, string body)
        {
            ResultModel resultModel = new ResultModel();

            try
            {
                System.Messaging.MessageQueue myQueue = new System.Messaging.MessageQueue(meta.Path);
                myQueue.Formatter = new ActiveXMessageFormatter();
                System.Messaging.Message MyMessage = MessageConvert.ConvertStringToSystemMessage(body, meta.FormmaterName, meta.Label);
                myQueue.Send(MyMessage);
                _logger.LogDebug(string.Format("Added json message to Queue:{0}", meta.Path));
                resultModel.Result = (int)ResultsEnum.AddedToQueue;
            }
            catch (System.Messaging.MessageQueueException ex)
            {
                KubeMQ.MSMQSDK.Results.MessageQueueException messageEx = new KubeMQ.MSMQSDK.Results.MessageQueueException(ex);
                _logger.LogCritical("Failed Sending json Message to queue {0} on exception {1}", meta.Path, ex.Message);
                resultModel.Result    = (int)ResultsEnum.Error;
                resultModel.exception = messageEx;
            }
            catch (Exception ex)
            {
                resultModel.Result = (int)ResultsEnum.Error;
                _logger.LogCritical("Failed Sending json Message to queue {0} on exception {1}", meta.Path, ex.Message);
                resultModel.exception = ex;
            }
            return(resultModel);
        }
Beispiel #31
0
        /// <summary>
        /// Peek Event Handler
        /// </summary>
        private async Task MyPeekCompleted(object source,
                                           PeekCompletedEventArgs asyncResult, string ChannelToReturnTo, string channelPeeked)
        {
            ResultModel resultModel = new ResultModel();

            try
            {
                // Connect to the queue.
                System.Messaging.MessageQueue mq = (System.Messaging.MessageQueue)source;

                // End the asynchronous peek operation.
                System.Messaging.Message myMessage = mq.EndPeek(asyncResult.AsyncResult);
                resultModel.message = MessageConvert.ConvertFromSystemMessage(myMessage);
                resultModel.Result  = (int)ResultsEnum.Done;
                // Restart the asynchronous peek operation.
                Response response = await initiator.SendRequestAsync(new KubeMQ.SDK.csharp.CommandQuery.LowLevel.Request()
                {
                    Metadata    = "PeekOK",
                    Body        = Converter.ToByteArray(resultModel),
                    CacheKey    = "",
                    CacheTTL    = 0,
                    Channel     = ChannelToReturnTo,
                    ClientID    = clientID,
                    RequestType = RequestType.Query
                });
            }
            catch (Exception ex)
            {
                _logger.LogCritical(string.Format("Failed to peek path {0} on ex {1}", channelPeeked, ex.Message));
            }
        }
Beispiel #32
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);
     }
 }
 private static async Task <string> GetMessage(string queue)
 {
     return(await Task.Run(() =>
     {
         try
         {
             string path = @".\private$\" + queue;
             System.Messaging.MessageQueue messageQueue = null;
             if (System.Messaging.MessageQueue.Exists(path))
             {
                 messageQueue = new System.Messaging.MessageQueue(path);
             }
             else
             {
                 messageQueue = System.Messaging.MessageQueue.Create(path);
             }
             Message message = messageQueue.Receive(new TimeSpan(0, 0, 2));
             message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
             return $"队列名称:{queue} 消息内容 {message.Body.ToString()}";
         }
         catch (Exception ex)
         {
             return ex.Message;
         }
     }));
 }
Beispiel #34
0
        private static System.Messaging.MessageQueue GetOrCreateQueue(string queuePath, bool createQueueIfNotFound)
        {
            if (queuePath == null)
            {
                throw new ArgumentNullException(nameof(queuePath));
            }
            if (String.IsNullOrWhiteSpace(queuePath))
            {
                throw new ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.PropertyCannotBeEmptyOrWhitespace, nameof(queuePath)), nameof(queuePath));
            }

            lock (_QueueCreationSynchroniser)
            {
                if (createQueueIfNotFound && !System.Messaging.MessageQueue.Exists(queuePath))
                {
                    System.Messaging.MessageQueue.Create(queuePath, false);
                }
            }

            var retVal = new System.Messaging.MessageQueue(queuePath, false, true, QueueAccessMode.Send);

            retVal.Formatter = new MsmqJsonLogEventMessageFormatter();
            retVal.DefaultPropertiesToSend.Recoverable = true;
            return(retVal);
        }
Beispiel #35
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2013.11.14 PM
        /// 描述:处理登录日志(消息队列)
        /// </summary>
        public static void DoLoginLog()
        {
            InitQueue(MsmqType.LoginLog);

            using (var mq = new MessageQueue(MsmpPath + MsmqType.LoginLog))
            {
                var msgs = mq.GetAllMessages();
                foreach (var msg in msgs)
                {
                    try
                    {
                        msg.Formatter = new XmlMessageFormatter(new[] { typeof(LoginLogs) });
                        var item = msg.Body as LoginLogs;
                        if (null == item)
                        {
                            continue;
                        }
                        LoginLogsBLL.CreateLoginLogs(item);
                    }
                    //记录下(异常)日志信息
                    catch (Exception e)
                    {
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = Utility.CommonHelper.To<int>(ExceptionType.Msmq),
                            Message = string.Format("MSMQ-DoLoginLog:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = 0,
                            CreateTime = DateTime.Now
                        });
                    }
                }
                mq.Purge();
            }
        }
Beispiel #36
0
        public void Listen(CancellationToken cancellationToken, int listenerId)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Message newMessage = MSMessageQueue.Receive();
            var     body       = newMessage.Body as byte[];
            var     message    = Encoding.UTF8.GetString(body);

            Log.Debug(x => x("Message queue listener received {0}", message));
            if (IntegrationJobTypes != null && !IntegrationJobTypes.Any())
            {
                return;
            }
            var type           = IntegrationJobTypes.FirstOrDefault(t => t.FullName.Equals(message));
            var integrationJob = Activator.CreateInstance(type) as IIntegrationJob;

            try
            {
                if (integrationJob != null)
                {
                    integrationJob.Run();
                }
            }
            catch (Exception exception)
            {
                Log.Error(x => x("Integration job did not run successfully ({0})}", message), exception);
            }
        }
Beispiel #37
0
 public bool addReservation(DemandeReservation reservation)
 {
     MessageQueue queue = new MessageQueue(FlyHotelConstant.ADRESSE_QUEUE);
     queue.Send(reservation);
     queue.Close();
     return true;
 }
Beispiel #38
0
        public ProcessingServiceData GetProcessingServiceData()
        {
            if (!System.Messaging.MessageQueue.Exists(_remoteControlQueueName))
            {
                System.Messaging.MessageQueue.Create(_remoteControlQueueName);
            }

            using (var remoteControlQueue = new System.Messaging.MessageQueue(_remoteControlQueueName, QueueAccessMode.SendAndReceive))
            {
                remoteControlQueue.Formatter = new XmlMessageFormatter(new[] { typeof(ProcessingServiceData), typeof(RemoteControlCommand) });
                var processingServiceDataRequest = new RemoteControlCommand
                {
                    Code = RemoteControlCommandCode.GetProcessingServiceData
                };
                remoteControlQueue.Send(new Message(processingServiceDataRequest));
                do
                {
                    var processingServiceMessage = remoteControlQueue.GetAllMessages().FirstOrDefault();
                    var processingServiceData    = processingServiceMessage?.Body as ProcessingServiceData;
                    if (processingServiceData == null)
                    {
                        Thread.Sleep(_callDelay);
                        continue;
                    }

                    remoteControlQueue.Receive();
                    return(processingServiceData);
                } while (true);
            }
        }
 public string MessageReceiver()
 {
     const string queue_name = @".\private$\dynamics";
     var queue = new MessageQueue(queue_name);
     queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
     return queue.Receive().Body.ToString();
 }
Beispiel #40
0
 /// <summary>
 /// Start the listen to the queue for incoming messages and
 /// notifiy the handlers as new messges arrive
 /// </summary>
 private void StartQueueListener()
 {
     //create a separate connection to the message queue
     System.Messaging.MessageQueue listenermq = new System.Messaging.MessageQueue(formatName);
     ((XmlMessageFormatter)listenermq.Formatter).TargetTypeNames = (string[])(supportedTypes.ToArray(typeof(System.String)));
     System.Messaging.Message message = null;
     queueListenerStarted = true;
     try
     {
         //listen to the queue continusly through loop
         while (queueListenerStarted == true)
         {
             System.Threading.Thread.Sleep(sleepTime);
             if (handler.GetInvocationList().Length > 0)
             {
                 //this is a call that will block the thread if no
                 //message is in the queue.
                 message = listenermq.Receive();
                 SAF.MessageQueue.Message safMessage = new SAF.MessageQueue.Message();
                 safMessage.Label   = message.Label;
                 safMessage.Content = message.Body;
                 //fire the event
                 handler(safMessage, queueName);
             }
         }
     }
     finally
     {
         //close the connetion
         listenermq.Close();
     }
 }
		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 #42
0
        private void SendStartupNotification()
        {
            MessageQueue startupQueue     = null;
            string       startupQueueName = @".\Private$\StromoLight_Startup";

            if (MessageQueue.Exists(startupQueueName))
            {
                startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup");
                System.Messaging.Message message = new System.Messaging.Message();
                message.Body  = "DSOK";
                message.Label = "Message from Diagnostics";
                startupQueue.Send(message);
            }
            else
            {
                startupQueue = MessageQueue.Create(@".\Private$\StromoLight_Startup");

                startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup");

                System.Messaging.Message message = new System.Messaging.Message();
                message.Body  = "DSOK Started OK";
                message.Label = "Message from Diagnostics";
                startupQueue.Send(message);
            }
        }
Beispiel #43
0
 private static void PurgeSubqueue(string queuePath, string subqueueName)
 {
     using (var queue = new MessageQueue(queuePath + ";" + subqueueName))
     {
         queue.Purge();
     }
 }
Beispiel #44
0
        /// <summary>
        /// Create message compatible with MSMQ
        /// </summary>
        /// <param name="queueName"></param>
        /// <returns></returns>
        public virtual IMessageQueue CreateMessageQueue(string queueName, string topicName = null)
        {
            var pathConfig = System.Configuration.ConfigurationManager.ConnectionStrings[queueName];

            if (pathConfig == null)
            {
                throw new ArgumentException(string.Format("queueName {0} does not exists in connectionStrings section configuration", queueName));
            }

            var path = pathConfig.ConnectionString;

            if (!path.StartsWith("formatname:direct") &&
                !System.Messaging.MessageQueue.Exists(path))
            {
                try
                {
                    string everyone = new System.Security.Principal.SecurityIdentifier(
                        "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                    var queue = System.Messaging.MessageQueue.Create(path);
                    queue.SetPermissions(everyone, MessageQueueAccessRights.FullControl);
                }
                catch (Exception ex)
                {
                    ex.Data.Add("queueName", queueName);
                    ex.Data.Add("queuePath", path);
                    throw ex;
                }
            }

            var result = new System.Messaging.MessageQueue(path, System.Messaging.QueueAccessMode.SendAndReceive);

            return(new QueueProviders.MSMQMessageQueue(result, queueName));
        }
        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();
                }
            }
        }
Beispiel #46
0
        public void Add_ShouldWriteToQueueWithoutChildren()
        {
            var messageQueue = new MessageQueue <TestPayload>(TestQueueName, null, true);

            var payload = new TestPayload
            {
                Id   = Guid.NewGuid(),
                Text = "Some test text",
                Time = DateTime.Now.TimeOfDay
            };

            messageQueue.Add(payload);

            var msgQueue = new MSFT.MessageQueue(messageQueue.Path)
            {
                Formatter = new MessageFormatter <TestPayload>()
            };

            var msg = msgQueue.Receive(TimeSpan.FromSeconds(30));

            msg.Body.Should().NotBeNull();
            msg.Body.Should().BeOfType <TestPayload>();

            var actualPayload = (TestPayload)msg.Body;

            actualPayload.Id.Should().Be(payload.Id);
            actualPayload.Text.Should().Be(payload.Text);
            actualPayload.Time.Should().Be(payload.Time);
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                string queueName = ConfigurationManager.AppSettings["ProvisionQueueName"];
                //if (!MessageQueue.Exists(queueName))MessageQueue.Create(queueName, true);
                var queue = new MessageQueue(queueName);
                Trace.WriteLine("Queue Created in MSMQService at:" + DateTime.Now);
                //Console.ReadLine();
                queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
                //Below code reads from queue once

                Message[] messages = queue.GetAllMessages();
                Trace.WriteLine("Reading from queue in MSMQService : " + queueName);
                Trace.WriteLine("Number of messages in MSMQService: " + messages.Length);
                /**foreach (Message msg in messages)
                {
                   // var decoded = JsonConvert.DeserializeObject(msg.Body.ToString());
                    Console.WriteLine("message:" + msg.Body);
                    Console.ReadLine();
                }
                Console.WriteLine("End of messages");
                Console.ReadLine();
                **/
                //Below code keeps reading from queue
                queue.ReceiveCompleted += QueueMessageReceived;
                queue.BeginReceive();
                signal.WaitOne();
                //Console.ReadLine();
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error in receiving in MSMQService: " + e.Message);
            }
        }
Beispiel #48
0
        public string GetElementFromSource(string pQueuePach)
        {
            System.Messaging.Message sourceMessage;
            string str = "";

            try
            {
                sourceQueue = new System.Messaging.MessageQueue(pQueuePach);
                ((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[] { "System.String" };
                if (sourceQueue.GetAllMessages().Length > 0)
                {
                    sourceMessage = sourceQueue.Receive(System.Messaging.MessageQueueTransactionType.Automatic);
                    // Set the formatter.
                    //	sourceQueue.Formatter = new XmlMessageFormatter(new Type[]	{typeof(String)});
                    ((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[] { "Empleado" };

                    str = (string)sourceMessage.Body;
                }

                return(str);
            }
            catch (MessageQueueException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #49
0
        protected override void OnStart(string[] args)
        {
            //HTTP listener
            //http://127.0.0.1:8081/sensores?var1=15&var2=514&var3=125&var4=145
            HTTPListener listen = new HTTPListener();

            listen.Listen();

            //Recepcion mensaje
            //Los sensores envían 2 mediciones por segundo (en forma independiente y potencialmente simultánea)
            mq                   = new MessageQueue(@".\private$\Sensores");
            mq.Formatter         = new XmlMessageFormatter(new Type[] { typeof(int[]) });
            mq.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);
            mq.BeginReceive();

            //Procesamiento princpal
            timer = new System.Timers.Timer();
            //El sistema de procesamiento, por limitaciones de hardware, sólo puede procesar información 2 veces por minuto.
            timer.Interval = 30000; // 30 seconds = 30000
            timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
            timer.Enabled  = true;
            timer.Start();

            signal.WaitOne();
        }
        public void SendMessageToQueue(string queueName, CallDisposition data)
        {
            var msMq = new MessageQueue(queueName);
            var myMessage = new System.Messaging.Message();
            myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(CallDisposition) });
            myMessage.Body = data;
            myMessage.Label = "MessageQueue";
            
            myMessage.UseJournalQueue = true;
            myMessage.Recoverable = true;

            //message send acknowledgement. 
            myMessage.AdministrationQueue = new MessageQueue(@".\Private$\MessageAcknowledgeQueue");
            myMessage.AcknowledgeType = AcknowledgeTypes.PositiveReceive | AcknowledgeTypes.PositiveArrival;

            try
            {
                msMq.Send(myMessage);
                Console.WriteLine("Message sent successfully!");

            }
            catch (MessageQueueException e)
            {
                Console.Write(e.ToString());
            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
            }
            finally
            {
                msMq.Close();
            }
        }
        public void Raven_dtc_bug()
        {
            new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin)
            .Purge();

            using (var tx = new TransactionScope())
            {

                using (var session = store.OpenSession())
                {
                    session.Store(new GatewayMessage());
                    session.SaveChanges();
                }

                using (var q = new MessageQueue(QueueAddress, QueueAccessMode.Send))
                {
                    var toSend = new Message { BodyStream = new MemoryStream(new byte[8]) };

                    //sending a message to a msmq queue causes raven to promote the tx
                    q.Send(toSend, MessageQueueTransactionType.Automatic);
                }

                //when we complete raven commits it tx but the DTC tx is never commited and eventually times out
                tx.Complete();
            }
            Thread.Sleep(1000);

            Assert.AreEqual(1,new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin)
            .GetAllMessages().Length);
        }
Beispiel #52
0
		public void An_undecipherable_blob_should_be_discarded()
		{
			var formatName = Endpoint.Address.Uri.GetInboundFormatName();
			using (var queue = new MessageQueue(formatName, QueueAccessMode.Send))
			{
				queue.Send("This is just crap, it will cause pain");
			}

			try
			{
				Endpoint.Receive(context =>
					{
						IConsumeContext<PingMessage> pingContext;
						context.TryGetContext(out pingContext);

						Assert.Fail("Receive should have thrown a serialization exception");

						return null;
					}, TimeSpan.Zero);
			}
			catch (Exception ex)
			{
				Assert.Fail("Did not expect " + ex.GetType() + " = " + ex.Message);
			}

			Assert.AreEqual(0, EndpointAddress.GetMsmqMessageCount(), "Endpoint was not empty");
			Assert.AreEqual(1, ErrorEndpointAddress.GetMsmqMessageCount(), "Error endpoint did not contain bogus message");
		}
Beispiel #53
0
        static MsmqAddress GetIndependentAddressForQueue(MessageQueue q)
        {
            var arr = q.FormatName.Split('\\');
            var queueName = arr[arr.Length - 1];

            var directPrefixIndex = arr[0].IndexOf(DIRECTPREFIX);
            if (directPrefixIndex >= 0)
            {
                return new MsmqAddress(queueName, arr[0].Substring(directPrefixIndex + DIRECTPREFIX.Length));
            }

            var tcpPrefixIndex = arr[0].IndexOf(DIRECTPREFIX_TCP);
            if (tcpPrefixIndex >= 0)
            {
                return new MsmqAddress(queueName, arr[0].Substring(tcpPrefixIndex + DIRECTPREFIX_TCP.Length));
            }

            try
            {
                // the pessimistic approach failed, try the optimistic approach
                arr = q.QueueName.Split('\\');
                queueName = arr[arr.Length - 1];
                return new MsmqAddress(queueName, q.MachineName);
            }
            catch
            {
                throw new Exception($"Could not translate format name to independent name: {q.FormatName}");
            }
        }
        void ISubscriptionStorage.Init()
        {
            var path = MsmqUtilities.GetFullPath(Queue);

            q = new MessageQueue(path);

            bool transactional;
            try
            {
                transactional = q.Transactional;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(string.Format("There is a problem with the subscription storage queue {0}. See enclosed exception for details.", Queue), ex);
            }

            if (!transactional && TransactionsEnabled)
                throw new ArgumentException("Queue must be transactional (" + Queue + ").");

            var messageReadPropertyFilter = new MessagePropertyFilter { Id = true, Body = true, Label = true };

            q.Formatter = new XmlMessageFormatter(new[] { typeof(string) });

            q.MessageReadPropertyFilter = messageReadPropertyFilter;

            foreach (var m in q.GetAllMessages())
            {
                var subscriber = Address.Parse(m.Label);
                var messageTypeString = m.Body as string;
                var messageType = new MessageType(messageTypeString); //this will parse both 2.6 and 3.0 type strings

                entries.Add(new Entry { MessageType = messageType, Subscriber = subscriber });
                AddToLookup(subscriber, messageType, m.Id);
            }
        }
Beispiel #55
0
		public QueueAgent(string inboundQueue, string outboundQueue)
		{

		mobjInboundQueue = new MessageQueue(QUEUE_PREFIX + inboundQueue);
		mobjOutboundQueue = new MessageQueue(QUEUE_PREFIX + outboundQueue);
		
		}
Beispiel #56
0
        private bool DoesUserExist(string emailAddress)
        {
            var responseAddress = Guid.NewGuid().ToString().Substring(0, 6);

            responseAddress = ".\\private$\\" + responseAddress;
            try
            {
                using (var responseQueue = msmq.MessageQueue.Create(responseAddress))
                {
                    var doesUserExistRequest = new DoesUserExistRequest
                    {
                        EmailAddress = emailAddress
                    };
                    using (var requestQueue = new msmq.MessageQueue(
                               ".\\private$\\sixeyed.messagequeue.doesuserexist"))
                    {
                        var message = new msmq.Message();
                        message.BodyStream    = doesUserExistRequest.ToJsonStream();
                        message.Label         = doesUserExistRequest.GetMessageType();
                        message.ResponseQueue = responseQueue;
                        requestQueue.Send(message);
                    }
                    var response     = responseQueue.Receive();
                    var responseBody = response.BodyStream.ReadFromJson <DoesUserExistResponse>();
                    return(responseBody.Exists);
                }
            }
            finally
            {
                if (msmq.MessageQueue.Exists(responseAddress))
                {
                    msmq.MessageQueue.Delete(responseAddress);
                }
            }
        }
Beispiel #57
0
        public string RetriveMessageFromQueue()
        {
            try
            {
                MessageQueue mqueu = null;
                if (MessageQueue.Exists(connection))
                {
                    mqueu = new MessageQueue(connection);
                }
                else
                {
                    Console.WriteLine("cannot find queue");
                    mqueu = MessageQueue.Create(connection);
                }

                mqueu.Refresh();
                string mqvalue = string.Empty;
                System.Type[] msgtypes = new System.Type[1];
                msgtypes[0] = mqvalue.GetType();
                mqueu.Formatter = new System.Messaging.XmlMessageFormatter(msgtypes);
                mqvalue = mqueu.Receive(new TimeSpan(0, 0, 5), System.Messaging.MessageQueueTransactionType.Single).Body.ToString();
                return mqvalue;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }
Beispiel #58
0
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<ITradeContextFactory, TradeContextFactory>();

            container.RegisterType<IMessageHandler, ValidateTradeHandler>("ValidateTradeHandler");
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty1Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                true, false));
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty2Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                false, true));

            container.RegisterType<MessageHandlerFactory>();

            _HandlerFactory = container.Resolve<MessageHandlerFactory>();

            var arguments = Args.Configuration.Configure<Arguments>().CreateAndBind(args);
            var queue = new MessageQueue(arguments.InputQueue, QueueAccessMode.Receive);
            while (true)
            {
                var msg = queue.Receive();
                Handle(msg);
            }
        }
        public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage)
        {
            var result = new List<int>();

            using (var messageQueue = new MessageQueue(String.Format(_pathPattern, queue)))
            {
                var current = 0;
                var end = @from + perPage;
                var enumerator = messageQueue.GetMessageEnumerator2();

                var formatter = new BinaryMessageFormatter();

                while (enumerator.MoveNext())
                {
                    if (current >= @from && current < end)
                    {
                        var message = enumerator.Current;

                        message.Formatter = formatter;
                        result.Add(int.Parse((string)message.Body));
                    }

                    if (current >= end) break;

                    current++;
                }
            }

            return result;
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="queuePath"></param>
 /// <param name="newEMNoRequest"></param>
 public static void AddAPIRequestToQueue(string queuePath,
                                         Emizon.APIModels.MSMQTypes.QueueOrderMessage newEMNoRequest
                                         )
 {
     System.Messaging.MessageQueue msmq = new System.Messaging.MessageQueue(queuePath);
     msmq.Send(newEMNoRequest, "Emizon Order: " + newEMNoRequest.orderID.ToString());
 }