Пример #1
2
        public static void PrepareQueue()
        {
            string msqName = ConfigurationManager.AppSettings["MSQName"].ToString();
            MessageQueue myQueue = new MessageQueue(".\\private$\\" + msqName);
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });

            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);

            WaitHandle[] waitHandleArray = new WaitHandle[10];
            for (int i = 0; i < 10; i++)
            {
                waitHandleArray[i] = myQueue.BeginReceive().AsyncWaitHandle;
            }

            WaitHandle.WaitAll(waitHandleArray);

            return;
        }
Пример #2
1
        private static void Main()
        {
            //var factory = new ConnectionFactory() { HostName = "localhost" };
            //using (var connection = factory.CreateConnection())
            //using (var channel = connection.CreateModel())
            //{
            //    channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

            //    var consumer = new EventingBasicConsumer(channel);
            //    consumer.Received += (model, ea) =>
            //    {
            //        var body = ea.Body;
            //        var message = Encoding.UTF8.GetString(body);
            //        Console.WriteLine(" [x] Received {0}", message);
            //    };
            //    channel.BasicConsume(queue: "hello", noAck: true, consumer: consumer);

            //    Console.WriteLine(" Press [enter] to exit.");
            //    Console.ReadLine();
            //}

            //while (true)
            //{
            try
            {
                var queue = new MessageQueue(@".\Private$\HelloWorld")
                {
                    Formatter = new XmlMessageFormatter(new[] { "".GetType() })
                };

                queue.ReceiveCompleted += (sender, e) =>
                {
                    var msg = queue.EndReceive(e.AsyncResult);
                    Console.WriteLine(msg.Body.ToString());
                    queue.BeginReceive();

                };

                queue.BeginReceive();

                //var message = queue.Receive(new TimeSpan(0, 0, 1));
                //message.Formatter = new XmlMessageFormatter(
                //                    new String[] { "System.String, mscorlib" });
                //Console.WriteLine(message.Body.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("No Message");
            }
            //Thread.Sleep(100);
            //}

            Console.WriteLine("Listening... Press any key to quit");
            Console.ReadLine();


        }
Пример #3
0
 public void ReceiveAsync()
 {
     if (!MessageQueue.Exists(path)) { throw new Exception("queue does't exist!"); }
     System.Messaging.MessageQueue queue2 = new System.Messaging.MessageQueue(path);
     queue2.ReceiveCompleted += new ReceiveCompletedEventHandler(queue2_ReceiveCompleted);
     queue2.BeginReceive();
 }
Пример #4
0
        public static void StartProcessing()
        {
            initializeSmtpClient();

            String queuePath = @".\private$\SendEmailQueue";

            new SendEmailQueueService().InsureQueueExsists(queuePath);
            msgQ = new MessageQueue(queuePath);
            msgQ.Formatter = new XmlMessageFormatter();

            /*
            The MessagePropertyFilter used by the queue to filter the set 
            of properties it receives or peeks for each message. 

            This filter is a set of Boolean values restricting the message
            properties that the MessageQueue receives or peeks. When the MessageQueue
            receives or peeks a message from the server queue, it retrieves only those
            properties for which the MessageReadPropertyFilter value is true.

            https://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.messagereadpropertyfilter(v=vs.110).aspx
            */
            msgQ.MessageReadPropertyFilter.SetAll();
            msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_RecieveCompleted);
            msgQ.BeginReceive();
        }
Пример #5
0
        public static void StartMSMQService()
        {
            msMqRequestDelete = new MessageQueue("FormatName:Direct=OS:" + Environment.MachineName.ToLower() + "\\private$\\requestdeletequeue");
            if (System.Messaging.MessageQueue.Exists(".\\private$\\requestdeletequeue"))
            {
                msMqRequestDelete.Purge();
                if (msMqRequestDelete != null)
                {
                    msMqRequestDelete.BeginReceive();
                }
                msMqRequestDelete.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompletedRequestTaskKill);
            }
            else
            {
                msMqRequestDelete = System.Messaging.MessageQueue.Create(".\\private$\\requestdeletequeue", true);
            }


            msMqReply = new MessageQueue("FormatName:Direct=OS:" + Environment.MachineName.ToLower() + "\\private$\\requestqueue");
            if (System.Messaging.MessageQueue.Exists(".\\private$\\requestqueue"))
            {
                {
                    msMqReply.Purge();
                    if (msMqReply != null)
                    {
                        msMqReply.BeginReceive();
                    }
                    msMqReply.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompletedReply);
                }
            }
            else
            {
                msMqReply = System.Messaging.MessageQueue.Create(".\\private$\\requestqueue", true);
            }
        }
Пример #6
0
        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);
            }
        }
Пример #7
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();
        }
Пример #8
0
      public void Start() 
      {
          //读取远程队列名称
          FileSyncMQ = ConfigurationManager.AppSettings["FileSyncMQ"];
          logger.Debug("远程队列名 " + FileSyncMQ);
          MAX_WORKER_THREADS = Convert.ToInt32(ConfigurationManager.AppSettings["MAX_WORKER_THREADS"].ToString());
          logger.Debug("异步读取工作线程数 " + MAX_WORKER_THREADS);
          try
          {
         
              
           q = new MessageQueue(FileSyncMQ);


          q.ReceiveCompleted += q_ReceiveCompleted;
            
            //异步方式,并发
            
            for(int i=0; i<MAX_WORKER_THREADS; i++)
            {
               
                waitHandleArray.Add( q.BeginReceive(MessageQueue.InfiniteTimeout).AsyncWaitHandle);
            }
               }
              catch (Exception ex)
              {
                  
                  logger.Error(ex);
              }
      }
        public void ReadGameServerInputQueue()
        {
            MessageQueue mq = new MessageQueue(".\\Private$\\Finvaders.ServerInputs");

            mq.BeginReceive(new TimeSpan(0, 4, 0), mq, MessageHandler);

            ServerInputQueue = mq;
        }
Пример #10
0
 public Replier(string requestQueueName,string invalidQueueName)
 {
     MessageQueue requestQueue = new MessageQueue(requestQueueName);
     invalidQueue = new MessageQueue(invalidQueueName);
     requestQueue.MessageReadPropertyFilter.SetAll();
     ((XmlMessageFormatter)requestQueue.Formatter).TargetTypeNames = new string[] { "System.String,mscorlib"};
     requestQueue.ReceiveCompleted += requestQueue_ReceiveCompleted;
     requestQueue.BeginReceive();
 }
Пример #11
0
 public static void StartProcessing()
 {
     string path = @".\private$\testqueue";
     ReadyQueue(path);
     _q = new MessageQueue(path);
     _q.Formatter = new XmlMessageFormatter(new Type[] { typeof(Email) });
     _q.MessageReadPropertyFilter.Body = true;
     _q.ReceiveCompleted += new ReceiveCompletedEventHandler(q_ReceiveCompleted);
     _q.BeginReceive();
 }
Пример #12
0
        public SimpleRouter(MessageQueue inQueue,
            MessageQueue outQueue1, MessageQueue outQueue2)
        {
            this.inQueue = inQueue;
            this.outQueue1 = outQueue1;
            this.outQueue2 = outQueue2;

            inQueue.ReceiveCompleted += OnMessage;
            inQueue.BeginReceive();
        }
Пример #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MsmqEventConsumer"/> class.
        /// </summary>
        /// <param name="mqPath">The mq path.</param>
        public MsmqEventConsumer(string mqPath)
        {
            if (!MessageQueue.Exists(mqPath)) {
                throw new ArgumentException("invalid msmq path", "mqPath");
            }

            _messageQueue = new MessageQueue(mqPath);
            _messageQueue.Formatter = new BinaryMessageFormatter();
            _messageQueue.ReceiveCompleted += FinishReceive;
            _messageQueue.BeginReceive();
        }
Пример #14
0
        public Replier(string requestQueueName, string invalidQueueName)
        {
            _requestQueue = QueueFactory.Get(requestQueueName);
            _invalidQueue = QueueFactory.Get(invalidQueueName);

            _requestQueue.MessageReadPropertyFilter.SetAll();
            ((XmlMessageFormatter)_requestQueue.Formatter).TargetTypeNames = new string[] { "System.String,mscorlib" };

            _requestQueue.ReceiveCompleted += OnReceiveCompleted;
            _requestQueue.BeginReceive();
        }
        public GestionReservation()
        {
            System.Diagnostics.Debug.WriteLine("(Info) Lancement du service de Gestion des reservations.");
            // Créé la queue de messages et son formateur.
            MessageQueue myQueue = new MessageQueue(QueuePath);
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProjetNet.Modele.ModeleReservation.ReservationHotelVol) });

            // Ajoute l'evenement de reception d'un message.
            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyPeekCompleted);

            // Lance l'attente asynchrone d'un message.
            myQueue.BeginReceive();
        }
Пример #16
0
        public void Start()
        {
            if (!MessageQueue.Exists(QueueName))
            {
                MessageQueue.Create(QueueName);
            }

            try
            {
                if (MessageQueue.Exists(QueueName))
                {
                    _listeningQueue = new MessageQueue(QueueName);
                    _listeningQueue.ReceiveCompleted += (sender, args) =>
                    {
                        args.Message.Formatter = new XmlMessageFormatter(
                            new[] { typeof(string) });
                        var msg = args.Message.Body.ToString();

                        Console.WriteLine("Message received:{0}", msg);

                        var parts = msg.Split('|');
                        var json = parts[0];
                        var typeName = parts[1];
                        var type = Type.GetType(typeName);
                        var evt = (Event)JsonConvert.DeserializeObject(json, type);

                        new Denormaliser().StoreEvent(evt);

                        _listeningQueue.BeginReceive();
                    };

                    _listeningQueue.BeginReceive();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Unable to initialise message queue on your local machine.\r\n\r\n{0}", e));
            }
        }
Пример #17
0
        void replyQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            replyQueue = (MessageQueue)sender;
            Message replyMessage = replyQueue.EndReceive(e.AsyncResult);

             Console.WriteLine("Received reply");
            Console.WriteLine("\tTime:          {0}", DateTime.Now.ToString("HH:mm:ss.ffffff"));
            Console.WriteLine("\tMessage ID:    {0}", replyMessage.Id);
            Console.WriteLine("\tCorrel:        {0}", replyMessage.CorrelationId);
            Console.WriteLine("\tReply To   :   {0}", "<n/a>");
            Console.WriteLine("\tContents:       {0}", replyMessage.Body.ToString());
            replyQueue.BeginReceive();
        }
        private static Message Receive(MessageQueue queue, CancellationToken cancelToken)
        {
            var receiveAsyncResult = queue.BeginReceive();
            WaitHandle.WaitAny(new[] { receiveAsyncResult.AsyncWaitHandle, cancelToken.WaitHandle });

            Message message = null;

            if (!cancelToken.IsCancellationRequested)
            {
                message = queue.EndReceive(receiveAsyncResult);
            }

            return message;
        }
Пример #19
0
        public override bool Execute()
        {
            Log.LogMessage("Starting MSMQ Server");

            outputQueue = new MessageQueue(OutputQueueName);

            inputQueue = new MessageQueue(InputQueueName);
            inputQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);
            inputQueue.BeginReceive();

            System.Threading.Tasks.Task.Factory.StartNew(ProcessInputQueue);

            processingDone.WaitOne();
            return true;
        }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueReader"/> class.
        /// </summary>
        /// <param name="queueName">Name of the message queue.</param>
        /// <param name="receiver">The implementation of this interface will be invoked for each received log entry.</param>
        public QueueReader(string queueName, ILogReceiver receiver)
        {
            if (queueName == null) throw new ArgumentNullException("queueName");
            if (receiver == null) throw new ArgumentNullException("receiver");
            _queueName = queueName;
            _receiver = receiver;

            if (!MessageQueue.Exists(queueName))
                throw new ArgumentOutOfRangeException("queueName", queueName, "Queue do not exist.");

            _queue = new MessageQueue(_queueName);
            _queue.ReceiveCompleted += OnReceived;
            _queue.Formatter = new XmlMessageFormatter(new[] {typeof (LogEntryDTO)});
            _queue.BeginReceive();
        }
        public void Start()
        {
            var queue = new MessageQueue(QueueConstants.PRIVATE_QUEQUE + this.queueName);
            queue.Formatter = new XmlMessageFormatter(new[] { QueueConstants.TIPO_SERIALIZACION });

            while (true)
            {
                // Set the event to nonsignaled state.
                allDone.Reset();

                queue.BeginReceive(new TimeSpan(1, 0, 0), queue, this.ReceiveCallback);

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }
        }
Пример #22
0
        public override void Init(string path)
        {
            base.Init(path);

            m_messageQueue = getIncomingQueue(LocalPath);
            var receiveAsync = Observable.FromAsyncPattern<Message>(
                (cb,obj) => m_messageQueue.BeginReceive(MessageQueue.InfiniteTimeout, obj, cb),
                m_messageQueue.EndReceive);

            m_msgs = Observable.Defer(receiveAsync)
                .Repeat()
                .Publish()
                .RefCount()
                .Select(msg => msg.Body)
                .OfType<TransportMessage>();
        }
Пример #23
0
		static void Main(string[] args)
		{
	
			// Create a transaction queue using System.Messaging API
			// You could also choose to not do this and instead create the
			// queue using MSMQ MMC -make sure you create a transactional queue

            if (!MessageQueue.Exists(ConfigurationManager.AppSettings["queueName"]))
				MessageQueue.Create(ConfigurationManager.AppSettings["queueName"], true);

			//Connect to the queue
			MessageQueue Queue = new MessageQueue(ConfigurationManager.AppSettings["queueName"]);

			Queue.ReceiveCompleted += new ReceiveCompletedEventHandler(ProcessOrder);
			Queue.BeginReceive();
			Console.WriteLine("Order Service is running");
            Console.WriteLine("Press <ENTER> to terminate service.");
			Console.ReadLine();
		}
Пример #24
0
        static void Main()
        {
            string queueName = @".\Private$\myqueue1";
            var queue = new MessageQueue(queueName);
            queue.Formatter = new XmlMessageFormatter(
                  new string[] { "System.String" });

            queue.ReceiveCompleted += MessageArrived;

            queue.BeginReceive();
            // thread does not wait
            // can do something else
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("...");
                Thread.Sleep(100);
                
            }
            Console.ReadKey();
        }
Пример #25
0
        SerializableDisposable(SerializationInfo info, StreamingContext context) {
            this._queuePath = info.GetString("queuePath");
            this._serverDisposable = (IServerDisposable)info.GetValue("server", typeof(IServerDisposable));
            this._subscription = (SecsEventSubscription)info.GetValue("subscription", typeof(SecsEventSubscription));
            this._subscription._disposable = this;

            var serverLease = (ILease)RemotingServices.GetLifetimeService((MarshalByRefObject)_serverDisposable);
            if (serverLease != null)
                serverLease.Register(Sponsor);

            if (_subscription.Recoverable && MessageQueue.Exists(_queuePath)) {
                var queue = new MessageQueue(_queuePath, true, false) {
                    Formatter = new BinaryMessageFormatter()
                };
                queue.ReceiveCompleted += Recover;
                queue.BeginReceive(TimeSpan.FromSeconds(QUEUE_RECEIVE_TIMEOUT));
            } else {
                if (MessageQueue.Exists(_queuePath))
                    MessageQueue.Delete(_queuePath);
                _serverDisposable.RecoverComplete();
            }
        }
Пример #26
0
 public override bool Listen(int numberOfSimultaneousRequests=1)
 {
     MessageQueue mqReceive = new MessageQueue(url);
     MessageQueue.EnableConnectionCache = false;
     // Control Queue permissions here:
     mqReceive.SetPermissions("Everyone",
         MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
     Console.WriteLine(mqReceive.MulticastAddress);
     mqReceive.Formatter = new XmlMessageFormatter(paramTypes);
     //mqReceive.Formatter = new BinaryMessageFormatter();
     //int numberOfSimultaneousRequests = 1;
     try
     {
         for (int i = 0; i < numberOfSimultaneousRequests; i++) mqReceive.BeginReceive(TimeSpan.FromSeconds(5),
              mqReceive, new AsyncCallback(OnMessageArrival));
         running = true;
         return true;
     }
     catch (Exception e)
     {
         return false;
     }
 }
Пример #27
0
        /// <summary>
        /// 
        /// </summary>
        private void Start()
        {
            _queue = new MessageQueue(this.QueueName);

            _queue.ReceiveCompleted += delegate(Object source, ReceiveCompletedEventArgs asyncResult)
            {
                try
                {
                    // End the asynchronous receive operation.
                    Message m = ((MessageQueue)source).EndReceive(asyncResult.AsyncResult);

                    if (Notifiable != null)
                    {
                        string loggingEvent = System.Text.Encoding.ASCII.GetString(((MemoryStream)m.BodyStream).ToArray());
                        LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "MSMQLogger");
                        logMsg.LoggerName = string.Format("{0}_{1}", QueueName.TrimStart('.'), logMsg.LoggerName);
                        Notifiable.Notify(logMsg);
                    }

                    if (this.BulkProcessBackedUpMessages)
                    {
                        Message[] all = ((MessageQueue) source).GetAllMessages();
                        if (all.Length > 0)
                        {
                            int numberofmessages = all.Length > 1000 ? 1000 : all.Length;

                            LogMessage[] logs = new LogMessage[numberofmessages];

                            for (int i = 0; i < numberofmessages; i++)
                            {
                                Message thisone = ((MessageQueue) source).Receive();

                                string loggingEvent =
                                    System.Text.Encoding.ASCII.GetString(((MemoryStream) thisone.BodyStream).ToArray());
                                LogMessage logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "MSMQLogger");
                                logMsg.LoggerName = string.Format("{0}_{1}", QueueName.TrimStart('.'), logMsg.LoggerName);
                                logs[i] = logMsg;
                            }

                            Notifiable.Notify(logs);
                        }
                    }

                    ((MessageQueue)source).BeginReceive();
                }
                catch (MessageQueueException)
                {
                    // Handle sources of MessageQueueException.
                }
            };

            _queue.BeginReceive();
        }
Пример #28
0
 private void checkForDrawing()
 {
     drawingMQ.BeginReceive(new TimeSpan(0, 0, 3));
 }
Пример #29
0
 public IAsyncResult BeginReceive()
 {
     return(m_Queue.BeginReceive());
 }
Пример #30
0
        public void StartMSMQService()
        {
            // removes all messages on start up

            msMqHelp = new MessageQueue("FormatName:Direct=OS:" + Environment.MachineName.ToLower() + "\\private$\\requesthelpqueue");
            if (System.Messaging.MessageQueue.Exists(".\\private$\\requesthelpqueue"))
            {
                msMqHelp.Purge();
                if (msMqHelp != null)
                {
                    msMqHelp.BeginReceive();
                }
                msMqHelp.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompletedRequestHelpQ);
            }
            else
            {
                msMqHelp = System.Messaging.MessageQueue.Create(".\\private$\\requesthelpqueue", true);
            }

            msMqNotify = new MessageQueue("FormatName:Direct=OS:" + Environment.MachineName.ToLower() + "\\private$\\notifyqueue");
            if (System.Messaging.MessageQueue.Exists(".\\private$\\notifyqueue"))
            {
                msMqNotify.Purge();
                if (msMqNotify != null)
                {
                    msMqNotify.BeginReceive();
                }
            }
            else
            {
                msMqNotify = System.Messaging.MessageQueue.Create(".\\private$\\notifyqueue", true);
            }
            msMqNotify.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompletedNotifyQ);


            msMqReply = new MessageQueue("FormatName:Direct=OS:" + Environment.MachineName.ToLower() + "\\private$\\replyqueue");
            if (System.Messaging.MessageQueue.Exists(".\\private$\\replyqueue"))
            {
                msMqReply.Purge();
                if (msMqReply != null)
                {
                    msMqReply.BeginReceive();
                }
                else
                {
                    System.Messaging.MessageQueue.Create(".\\private$\\replyqueue", true);
                }
            }
            msMqReply.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompletedReplyQ);
        }
Пример #31
0
        public override bool Execute()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            Log.LogMessage("Starting MSMQ transfer with " + TotalBatches.ToString() + " batchs with " + BatchSize.ToString() + " items each");

            messageCount = TotalBatches;

            inputQueue = new MessageQueue(InputQueueName);
            inputQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(inQueue_ReceiveCompleted);
            inputQueue.BeginReceive();

            System.Threading.Tasks.Task.Factory.StartNew(ProcessInputQueue);

            MessageQueue queue = new MessageQueue(OutputQueueName);

            int count = 1;

            for (int i = 0; i < TotalBatches; i++)
            {
                Message msg = new Message();
                msg.BodyStream = new MemoryStream();

                StreamUtil.GenerateBigRequest(msg.BodyStream, false, count, count + (BatchSize - 1));
                msg.BodyStream.Seek(0, SeekOrigin.Begin);
                queue.Send(msg, IsTransactional ? MessageQueueTransactionType.Single : MessageQueueTransactionType.None);

                count += BatchSize;
            }
            Log.LogMessage("Messages sent");

            processingDone.WaitOne();

            watch.Stop();
            Log.LogMessage("Total processing time: " + watch.Elapsed.TotalSeconds.ToString("0.00") + " seconds");

            return true;
        }
Пример #32
0
        public MessageListener StartListener(string nombreCola, ReceiveCompletedEventHandler MQueueReceiveEventHandler)
        {
            MessageListener MsgListener;

            MessageQueue.EnableConnectionCache = false;
            MessageQueue cola = new MessageQueue(PRIVATE_QUEQUE + nombreCola);

            EstablecerFormateador(cola);

            cola.ReceiveCompleted += MQueueReceiveEventHandler;

            IAsyncResult MQResult = cola.BeginReceive(TimeSpan, cola);

            MsgListener.MQueue = cola;
            MsgListener.AsyncResult = MQResult;
            return MsgListener;
        }
Пример #33
0
        static void Main(string[] args)
        {
            
            // open the queue
            if (!MessageQueue.Exists(QueuePath)) MessageQueue.Create(QueuePath);
            MessageQueue mqReceive = new MessageQueue(QueuePath);
            MessageQueue.EnableConnectionCache = false;
            // Control Queue permissions here:
            mqReceive.SetPermissions("Everyone",
                MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
            Console.WriteLine(mqReceive.MulticastAddress);
            Type[] paramTypes = new Type[1];
            paramTypes[0] = typeof(Package.MessagePackage);
            mqReceive.Formatter = new XmlMessageFormatter(paramTypes);
            //mqReceive.Formatter = new BinaryMessageFormatter();
			int numberOfSimultaneousRequests=10;	 
            try
            {
                for (int i = 0; i < numberOfSimultaneousRequests; i++)mqReceive.BeginReceive(TimeSpan.FromSeconds(5),
                    mqReceive, new AsyncCallback(OnMessageArrival));

            }
            catch (Exception e)
            {
                Out(e);
            }

            sendcount = 1000;
            Out2(" Send {0} message to MQ and recieve with {1} ", sendcount, numberOfSimultaneousRequests);
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            Parallel.For(0, sendcount, (i) => QueueJob(QueuePath, Package.MessagePackage.CreateFrom(new BOLibrary.FakeBo1())));   
            watch.Stop();         
            Out2("Parallel send,               recieved {0} in {1} ms", Interlocked.Read(ref recievecount), watch.ElapsedMilliseconds);

            //Interlocked.Exchange(ref recievecount, 0);
            //watch.Start();
            //ThreadPool.QueueUserWorkItem(
            //    o=>QueueJob(QueuePath, Package.MessagePackage.CreateFrom(new BOLibrary.FakeBo1()))                 
            //    );
            //watch.Stop();
            //Out("ThreadPool, recieve{0} in {1} ms", Interlocked.Read(ref recievecount), watch.ElapsedMilliseconds);
           

            Interlocked.Exchange(ref recievecount, 0);
            watch.Start();
            for (int idx = 0; idx < sendcount; idx++)
            {
                QueueJob(mqReceive, Package.MessagePackage.CreateFrom(new BOLibrary.FakeBo1()));
            }
            watch.Stop();
            Out2("Serial send not creating mq, recieved {0} in {1} ms", Interlocked.Read(ref recievecount), watch.ElapsedMilliseconds);

            Interlocked.Exchange(ref recievecount, 0);
            watch.Start();
            for (int idx = 0; idx < sendcount; idx++)
            {
                QueueJob(QueuePath, Package.MessagePackage.CreateFrom(new BOLibrary.FakeBo1()));
            }
            watch.Stop();
            Out2("Serial send,                 recieved {0} in {1} ms", Interlocked.Read(ref recievecount), watch.ElapsedMilliseconds);
            Console.ReadLine();
            mqReceive.Close();
        }
Пример #34
0
        private void btnConnect_Click(object sender, System.EventArgs e)
        {
            MessageQueue[]       mqlist;
            MessageQueueCriteria mqCriteria;

            System.Windows.Forms.Cursor TempCursor;

            bDirectMode = radioDSDisabled.Checked;
            TempCursor  = this.Cursor;
            this.Cursor = Cursors.WaitCursor;

            if (radioDSDisabled.Checked)
            {             // User wants to use a private queue (direct connection).
                try
                {
                    qMe          = MessageQueue.Create(@".\private$\" + strName);
                    qMe.Label    = strName;
                    qMe.Category = new System.Guid(guidDraw);
                }
                catch (MessageQueueException MQE)
                {
                    qMe      = new MessageQueue();
                    qMe.Path = @".\private$\" + strName;
                }
            }
            else
            {             // The user wants to use a public queue (standard mode)
                          // so query the direcotry service for a public queue with the
                          // user-specified name.
                mqCriteria          = new MessageQueueCriteria();
                mqCriteria.Label    = strName;
                mqCriteria.Category = new System.Guid(guidDraw);
                try
                {
                    mqlist = MessageQueue.GetPublicQueues(mqCriteria);
                }
                catch (MessageQueueException MQE)
                {
                    MessageBox.Show("An error occurred in locating the queue. (" + MQE.Message + ")", "C#_Draw");
                    this.Close();
                    return;
                }
                // If no such queue then create one
                if (mqlist.Length == 0)
                {
                    try
                    {
                        MessageQueue.Create(@".\" + strName);
                    }
                    catch (MessageQueueException MQE)
                    {
                        MessageBox.Show("An error occurred in creating the queue. (" + MQE.Message + ")", "C#_Draw");
                        this.Close();
                        return;
                    }
                    qMe          = new MessageQueue();
                    qMe.Path     = @".\" + strName;
                    qMe.Label    = strName;
                    qMe.Category = new System.Guid(guidDraw);
                }
                else
                {
                    qMe = mqlist[0];
                }
            }

            // Start receiving

            qMe.Formatter         = new ActiveXMessageFormatter();
            qMe.ReceiveCompleted += new ReceiveCompletedEventHandler(this.qMe_ReceiveCompleted);
            qMe.BeginReceive();

            groupConnectionMode.Visible = false;
            btnConnect.Visible          = false;
            btnCancel.Visible           = false;

            btnAttach.Visible      = true;
            groupSendType.Visible  = true;
            lblRemoteQueue.Visible = true;
            textFriendName.Visible = true;

            if (radioDSDisabled.Checked)
            {
                lblRemoteComputer.Visible  = true;
                textFriendComputer.Visible = true;
            }

            this.Cursor = TempCursor;
            // Anyway, on the local computer, the connection to the Directory
            // service remains available
            lblDSConnection.Text = "MODE: Domain";
        }