예제 #1
0
        public string Ping2(int value)
        {
            var txstatus = TransactionStatus.InDoubt;

            if (Transaction.Current != null)
            {
                txstatus = Transaction.Current.TransactionInformation.Status;
            }

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("\n[tid={0}, tx={1}]  *** PING_2 Service: {2} ***\n", Thread.CurrentThread.GetHashCode(), txstatus, value);
            Console.ResetColor();

            var retval = string.Format("[{0}, {1}, Hello from tid={2}]", DateTime.Now.ToShortTimeString(), value, Thread.CurrentThread.GetHashCode());

            //using (DependentTransaction dtx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete))
            {
                // for test purpose we are using MSMQ resource manager
                var mq = new System.Messaging.MessageQueue(strQueueName);
                mq.Send(retval, value.ToString(), System.Messaging.MessageQueueTransactionType.Automatic);

                //throw new Exception("M A N U A L L Y  A B O R T E D");
                //dtx.Complete();
            }

            //Thread.Sleep(62000);

            return(retval);
        }
예제 #2
0
        public void Subscribe()
        {
            if (System.Threading.Interlocked.Exchange(ref _subscribed, 1) == 0)
            {
                try
                {
                    if (string.IsNullOrEmpty(this.QueuePath))
                    {
                        return;
                    }

                    Utilities.CreateIfNotExist(new MessageQueueRequest
                    {
                        QueuePath = this.QueuePath
                    });

                    if (this.Logger != null)
                    {
                        this.Logger.Debug(string.Format("Begin subscribing to event '{1}' via Message Queue '{0}' using type '{2}'",
                                                        this.QueuePath, typeof(TEvnt).Name, this.GetType().Name));
                    }

                    _mq                   = new System.Messaging.MessageQueue(this.QueuePath);
                    _mq.Formatter         = _formatter;
                    _mq.ReceiveCompleted += OnMQReceiveCompleted;

                    _mq.BeginReceive();
                }
                catch (Exception ex)
                {
                    this.Logger.Error(string.Format("Error during {0}.Subscribe()", this.GetType().Name), ex);
                }
            }
        }
예제 #3
0
파일: Logger.cs 프로젝트: jsingh/DeepBlue
        public static void Write(Log log)
        {
            switch (ConfigurationManager.AppSettings["Logging.Destination"].ToLower()) {
                case Logger.DATABASE_LOGSINK:
                    log.Save();
                    break;
                case Logger.MSMQ_LOGSINK:
                    string destinationQ = ConfigurationManager.AppSettings["Logging.MSMQ.Queue.Path"];

                    // publish the request to the appropriate message queue
                    System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(destinationQ);

                    System.Messaging.Message msg = new System.Messaging.Message();
                    msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(Log) });
                    msg.Body = log;
                    msg.Priority = System.Messaging.MessagePriority.Normal;
                    msg.Recoverable = true;
                    msg.Label = log.LogType.GetType().Name;
                    mq.Send(msg);
                    break;
                default:
                    log.Save();
                    break;
            }
        }
        private static void queueCreate(string mqPath, string mqName)
        {
            try
            {
                mqPath = @mqPath;
                mqName = @mqName;

                // create if doesn't exist
                if (!System.Messaging.MessageQueue.Exists(mqPath))
                {
                    System.Messaging.MessageQueue.Create(mqPath, false);

                    // set other queue parameters
                    System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(mqPath);
                    mq.Label = mqName;
                    //assumption Queue is on this box
                    mq.MachineName = _logMachine;
                    mq.QueueName   = mqName;
                }
            }
            catch (System.Exception ex)
            {
                HandleError(ex);
            }
        }
예제 #5
0
        protected override void OnStart(string[] args) 
        { 
            // Create directories if needed 
            if (!System.IO.Directory.Exists(MessageDirectory)) 
                System.IO.Directory.CreateDirectory(MessageDirectory); 
            
            // Create new message queue instance 
            messageQueue = new System.Messaging.MessageQueue(MessageQueue); 
 
            try 
            {    
                // Set formatter to allow ASCII text 
                messageQueue.Formatter = new System.Messaging.ActiveXMessageFormatter(); 
                // Assign event handler when message is received 
                messageQueue.ReceiveCompleted += 
                    new System.Messaging.ReceiveCompletedEventHandler(messageQueue_ReceiveCompleted); 
                // Start listening 
                
                messageQueue.BeginReceive(); 
            } 
            catch (Exception e) 
            { 
                
            } 
        } 
예제 #6
0
        //传菜
        public bool TransFood(string FoodCode, string TableType, string Tableno, string PsnCount, string billno, string FoodName, string TypeName, string DeptName, string unit, string quantity, string operandi, string taste, string operatorid, string barcode, int OperateCode, string CancelRsn)
        {
            bool returnValue;
            returnValue = false;
            string queuePath = ".\\Private$\\RMS";
            EnsureQueueExists(queuePath);

            System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(queuePath);
            queue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(AppExt.CAppExt.FoodInfo)});

            AppExt.CAppExt.FoodInfo orderRequest = new AppExt.CAppExt.FoodInfo();

            orderRequest.FoodCode = FoodCode;
            orderRequest.TableType = TableType;
            orderRequest.Tableno = Tableno;
            orderRequest.PsnCount = PsnCount;
            orderRequest.Billno = billno;
            orderRequest.FoodName = FoodName;
            orderRequest.TypeName = TypeName;
            orderRequest.DeptName = DeptName;
            orderRequest.unit = unit;
            orderRequest.quantity = quantity;
            orderRequest.operandi = operandi;
            orderRequest.taste = taste;
            orderRequest.operatorid = operatorid;
            orderRequest.BarCode = barcode;
            orderRequest.OperateCode = OperateCode; //OperateCode = 0 传菜 OperateCode = 1 催菜 OperateCode = 2 缓菜 OperateCode = 3 退菜
            orderRequest.CancelRsn = CancelRsn;

            queue.Send(orderRequest);
            returnValue = true;
            return returnValue;
        }
예제 #7
0
        public string Ping2(int value)
        {
            var txstatus = TransactionStatus.InDoubt;
            if (Transaction.Current != null)
                txstatus = Transaction.Current.TransactionInformation.Status;

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("\n[tid={0}, tx={1}]  *** PING_2 Service: {2} ***\n", Thread.CurrentThread.GetHashCode(), txstatus, value);
            Console.ResetColor();

            var retval = string.Format("[{0}, {1}, Hello from tid={2}]", DateTime.Now.ToShortTimeString(), value, Thread.CurrentThread.GetHashCode());          

            //using (DependentTransaction dtx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete))
            {
                // for test purpose we are using MSMQ resource manager
                var mq = new System.Messaging.MessageQueue(strQueueName);
                mq.Send(retval, value.ToString(), System.Messaging.MessageQueueTransactionType.Automatic);

                //throw new Exception("M A N U A L L Y  A B O R T E D");
                //dtx.Complete();
            }

            //Thread.Sleep(62000);

            return retval;
        }
예제 #8
0
        public static void Write(Log log) {

            switch (Foundation.Common.Util.ConfigUtil.GetAppSetting("Logging.Destination").ToLower()) {
                case Logger.DATABASE_LOGSINK:
                    LoggingService.Save(log);
                    break;
                case Logger.MSMQ_LOGSINK:
                    string destinationQ = Foundation.Common.Util.ConfigUtil.GetAppSetting("Logging.MSMQ.Queue.Path");

                    // publish the request to the appropriate message queue
                    System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(destinationQ);

                    System.Messaging.Message msg = new System.Messaging.Message();
                    msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(blogEngine.Shared.Logging.Log) });
                    msg.Body = log;
                    msg.Priority = System.Messaging.MessagePriority.Normal;
                    msg.Recoverable = true;
                    msg.Label = log.LogType.GetType().Name;
                    mq.Send(msg);
                    break;
                default:
                    LoggingService.Save(log);
                    break;
            }
        }
예제 #9
0
파일: Program.cs 프로젝트: mparsin/TBMS
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <remarks>In real life this is going to be a windows service or other type of background operating instance that monitors incomming
        /// messages.
        /// Once message is received the handler resumes corresponding flow execution</remarks>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            var consoleTracer = new ConsoleTraceListener(true);
            Trace.Listeners.Add(consoleTracer);

            using (var queue = new System.Messaging.MessageQueue(@".\private$\tbms.callbackqueue"))
            {
                while (true)
                {
                    Console.WriteLine("Listening...");
                    var message = queue.Receive();

                    var bodyReader = new StreamReader(message.BodyStream);
                    var body = bodyReader.ReadToEnd();

                    var messageBody = (JObject)JsonConvert.DeserializeObject(body);

                    var flowId = messageBody["flowId"].Value<int>();

                    var flow = DeserializeFlow(flowId);

                    flow?.Resume();
                }
            }
        }
예제 #10
0
        private static T ReadMessage <T>(string queueAddress, ConsoleColor color = ConsoleColor.Gray) where T : UnSubscriberInfo
        {
            T result = default(T);

            using (var mq = new System.Messaging.MessageQueue(queueAddress))
            {
                ConsoleHelper.WriteLine(color, $"Waiting for new {(typeof(T) == typeof(SubscriberInfo) ? "Subscriber" : "Unsubscriber")}...");

                var message = mq.Receive();
                if (message != null)
                {
                    var msgBodyStream = new StreamReader(message.BodyStream);
                    var msgBody       = JsonConvertor.ReadObject <T>(msgBodyStream);

                    if (typeof(T) == typeof(SubscriberInfo))
                    {
                        var subscriber = (SubscriberInfo)(object)msgBody;// dirty casting
                        ConsoleHelper.WriteLine(color, "New Subscriber with below info:");
                        ConsoleHelper.WriteLine(color, $"\t\tFirstName: {subscriber.FirstName}");
                        ConsoleHelper.WriteLine(color, $"\t\tLastName: {subscriber.LastName}");
                        ConsoleHelper.WriteLine(color, $"\t\tEmailAddress: {subscriber.EmailAddress}");
                    }
                    else
                    {
                        var unsubscriber = (UnSubscriberInfo)msgBody;
                        ConsoleHelper.WriteLine(color, "New UnSubscriber with below info:");
                        ConsoleHelper.WriteLine(color, $"\t\tEmailAddress: {unsubscriber.EmailAddress}");
                    }

                    result = msgBody;
                }
            }
            return(result);
        }
예제 #11
0
        public virtual void Publish(TEvnt eventToBePublished)
        {
            if (string.IsNullOrEmpty(this.QueuePath))
            {
                return;
            }

            Utilities.CreateIfNotExist(new MessageQueueRequest
            {
                IsTransactional = this.IsTransactional,
                QueuePath       = this.QueuePath
            });

            using (var mq = new System.Messaging.MessageQueue(this.QueuePath))
            {
                mq.Formatter = _formatter;
                if (this.Logger != null)
                {
                    this.Logger.Debug(string.Format("Sending Event '{1}' to Message Queue '{0}' with publisher '{2}'", this.QueuePath, typeof(TEvnt).Name, this.GetType().Name));
                }

                mq.Send(eventToBePublished);

                if (this.Logger != null)
                {
                    this.Logger.Debug(string.Format("Sent Event '{1}' to Message Queue '{0}' with publisher '{2}'", this.QueuePath, typeof(TEvnt).Name, this.GetType().Name));
                }

                mq.Close();
            }
        }
예제 #12
0
            public void Start()
            {
                lock (this.thisLock)
                {
                    try
                    {
                        if (this.queue == null)
                        {
                            this.queue = new MQMessageQueue(this.queueName);
                            this.queue.MessageReadPropertyFilter.ClearAll();
                            this.queue.MessageReadPropertyFilter.LookupId = true;
                        }

                        if (!this.peeking)
                        {
                            this.peeking = true;
                            this.queue.BeginPeek(InfiniteTimeout, null, Fx.ThunkCallback(new AsyncCallback(OnPeekCompleted)));
                        }
                    }
                    catch (MQException)
                    {
                        this.group.ScheduleRetry(this);
                    }
                }
            }
 /// <inheritdoc />
 /// <summary>
 /// Unable to receive from Message Queue Exception
 /// </summary>
 /// <param name="messageQueue">Message Queue</param>
 /// <param name="correlationId">Correlation Id</param>
 /// <param name="timeout">Timeout</param>
 /// <param name="exception">Inner Exception</param>
 public MessageQueueReceiveException(System.Messaging.MessageQueue messageQueue, string correlationId, TimeSpan timeout, Exception exception) : base($"Unable to receive from Message Queue Exception ({messageQueue?.QueueName ?? ""})", exception)
 {
     Data.Add("QueueName", messageQueue?.QueueName);
     Data.Add(nameof(messageQueue), messageQueue.TrySerializeToJson());
     Data.Add(nameof(correlationId), correlationId);
     Data.Add(nameof(timeout), timeout);
 }
예제 #14
0
		//传菜
		public bool TransFood(string FoodCode, string TableType, string Tableno, string PsnCount, string billno, string FoodName, string TypeName, string DeptName, string unit, string quantity, string operandi, string taste, string operatorid, string barcode, int OperateCode, string CancelRsn)
		{
			bool returnValue;
			returnValue = false;
			string queuePath = ".\\Private$\\RMS";
			EnsureQueueExists(queuePath);
			
			System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(queuePath);
			queue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(AppExt.CAppExt.FoodInfo)});
			
			AppExt.CAppExt.FoodInfo orderRequest = new AppExt.CAppExt.FoodInfo();
			
			orderRequest.FoodCode = FoodCode;
			orderRequest.TableType = TableType;
			orderRequest.Tableno = Tableno;
			orderRequest.PsnCount = PsnCount;
			orderRequest.Billno = billno;
			orderRequest.FoodName = FoodName;
			orderRequest.TypeName = TypeName;
			orderRequest.DeptName = DeptName;
			orderRequest.unit = unit;
			orderRequest.quantity = quantity;
			orderRequest.operandi = operandi;
			orderRequest.taste = taste;
			orderRequest.operatorid = operatorid;
			orderRequest.BarCode = barcode;
			orderRequest.OperateCode = OperateCode; //OperateCode = 0 传菜 OperateCode = 1 催菜 OperateCode = 2 缓菜 OperateCode = 3 退菜
			orderRequest.CancelRsn = CancelRsn;
			
			queue.Send(orderRequest);
			returnValue = true;
			return returnValue;
		}
 /// <inheritdoc />
 /// <summary>
 /// Unable to Peek Message Queue Exception
 /// </summary>
 /// <param name="function">Peek Function</param>
 /// <param name="messageQueue">Message Queue</param>
 /// <param name="asyncResult">Async Result</param>
 /// <param name="exception">Inner Exception</param>
 public MessageQueuePeekException(string function, System.Messaging.MessageQueue messageQueue, IAsyncResult asyncResult, Exception exception) : base($"Unable to Peek Message Queue Exception ({messageQueue?.QueueName ?? ""})", exception)
 {
     Data.Add(nameof(function), function);
     Data.Add("QueueName", messageQueue?.QueueName ?? "");
     Data.Add(nameof(messageQueue), messageQueue?.TrySerializeToJson());
     Data.Add(nameof(asyncResult), asyncResult?.TrySerializeToJson());
 }
 /// <inheritdoc />
 /// <summary>
 /// Unable to Peek Message Queue Exception
 /// </summary>
 /// <param name="function">Peek Function</param>
 /// <param name="messageQueue">Message Queue</param>
 /// <param name="timeout">Peek Timeout</param>
 /// <param name="exception">Inner Exception</param>
 /// <exception cref="T:System.NotImplementedException"></exception>
 public MessageQueuePeekException(string function, System.Messaging.MessageQueue messageQueue, TimeSpan timeout, Exception exception) : base($"Unable to Peek Message Queue Exception ({messageQueue?.QueueName ?? ""})", exception)
 {
     Data.Add(nameof(function), function);
     Data.Add("Name", messageQueue?.QueueName ?? "");
     Data.Add(nameof(messageQueue), messageQueue?.TrySerializeToJson());
     Data.Add(nameof(timeout), timeout);
 }
예제 #17
0
        public static void Connect_Server()
        {
            //connection setup
            ircconnect = new TcpClient(SetupClass.Server, SetupClass.port);
            ircstream = ircconnect.GetStream();
            PingClass ping = new PingClass();
            ping.Start();
            reader = new StreamReader(ircstream);
            writer = new StreamWriter(ircstream);

            writer.WriteLine("PING " + "irc.freenode.net");
            writer.Flush();
            writer.WriteLine("USER WPChat 8 * : WrongPlanet IRC Client");
            writer.Flush();
            writer.WriteLine("NICK " + SetupClass.Nick);
            writer.Flush();
            writer.WriteLine("JOIN " + "#wrongplanet");
            writer.Flush();

            while (true)
            {

                //if (reader.ReadLine() != null)
                {
                    System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(@".\Private$\ServerQueue");
                    queue.Send(reader.ReadLine());
                }

            }
        }
예제 #18
0
        //测试函数 定义类提供服务的方法
        public bool AddtoMsgQue(string msg)
        {
            bool returnValue;

            returnValue = false;
            string Path = ".\\Private$\\RMS";

            if (System.Messaging.MessageQueue.Exists(Path))
            {
                System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(Path);
                if (!queue.Transactional)
                {
                    queue.Send(msg);
                    returnValue = true;
                }
            }
            else
            {
                System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(Path);
                queue = System.Messaging.MessageQueue.Create(Path);
                queue.Send(msg);
                returnValue = true;
            }
            return(returnValue);
        }
예제 #19
0
        static void Main(string[] args)
        {
            //先安装windows消息队列服务:打开或关闭Windows功能
            //http://blog.csdn.net/pukuimin1226/article/details/19030691

            MQzwh mq = new MQzwh("zwhQueue");

            System.Messaging.MessageQueue mq_temp = mq.MQ;

            mq_temp.Purge(); //清空消息

            for (int i = 0; i < 1; i++)
            {
                mq.sendSimpleMsg();
            }
            for (int i = 0; i < 5; i++)
            {
                mq.receiveSimpleMsg();
            }

            mq.sendComplexMsg();
            mq.receiveComplexMsg();

            Console.WriteLine("mq 消息数目:" + mq_temp.GetAllMessages().Count());

            //Console.WriteLine("mq 消息数目:" + mq_temp.GetAllMessages().Count());

            Console.WriteLine("-------------------\nok");
            Console.ReadKey();
        }
예제 #20
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.msgQueue = new System.Messaging.MessageQueue();
     //
     // msgQueue
     //
     this.msgQueue.Path = "FormatName:DIRECT=OS:localhost\\private$\\alpha";
 }
예제 #21
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.messageQueueOrders = new System.Messaging.MessageQueue();
     //
     // messageQueueOrders
     //
     this.messageQueueOrders.Path = "alessandra\\Private$\\AsapOrders";
 }
예제 #22
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.messageQueueVehiclesToInvoice = new System.Messaging.MessageQueue();
     //
     // messageQueueVehiclesToInvoice
     //
     this.messageQueueVehiclesToInvoice.Path              = "FormatName:DIRECT=OS:alessandra\\private$\\asapvehiclestoinvoice";
     this.messageQueueVehiclesToInvoice.ReceiveCompleted += new System.Messaging.ReceiveCompletedEventHandler(this.OrderReceived);
 }
예제 #23
0
 /// <summary>
 /// Initializes the Windows message queue
 /// </summary>
 /// <param name="queuepath">Path of the queue to initialize</param>
 private void InitializeQueue(string queuepath)
 {
     if (System.Messaging.MessageQueue.Exists(queuepath))
     {
         this.mq = new System.Messaging.MessageQueue(queuepath);
     }
     else
     {
         this.mq = System.Messaging.MessageQueue.Create(queuepath);
     }
 }
예제 #24
0
 /// <summary>
 /// Initializes the Windows message queue
 /// </summary>
 /// <param name="queuepath">Path of the queue to initialize</param>
 private void InitializeQueue(string queuepath)
 {
     if (System.Messaging.MessageQueue.Exists(queuepath))
     {
         this.mq = new System.Messaging.MessageQueue(queuepath);
     }
     else
     {
         this.mq = System.Messaging.MessageQueue.Create(queuepath);
     }
 }
예제 #25
0
 public bool IsServerAvailable()
 {
     try
     {
         return(MSMessageQueue.Exists(QueueName));
     }
     catch (Exception exception)
     {
         Log.Error(exception);
         return(false);
     }
 }
예제 #26
0
        protected override void OnStop() 
        { 
            //Make process synchronous before closing the queue 
            manualResetEvent.WaitOne(); 
 
            
            // Clean up 
            if (this.messageQueue != null) 
            { 
                this.messageQueue.Close(); 
                this.messageQueue = null; 
            } 
        } 
예제 #27
0
        private MessageQueues()
        {
            this.m_MessageCollection = new MessageQueueCollection <MessageQueueMessage>();

            this.m_LockReleaseRequestQueue                   = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseRequestQueueName);
            this.m_LockReleaseRequestQueue.Formatter         = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(LockReleaseRequestMessageBody) });
            this.m_LockReleaseRequestQueue.ReceiveCompleted += LockReleaseRequestMessageQueue_ReceiveCompleted;
            this.m_LockReleaseRequestQueue.BeginReceive();

            this.m_LockReleaseResponseQueue                   = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseResponseQueueName);
            this.m_LockReleaseResponseQueue.Formatter         = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(LockReleaseResponseMessageBody) });
            this.m_LockReleaseResponseQueue.ReceiveCompleted += LockReleaseResponseMessageQueue_ReceiveCompleted;
            this.m_LockReleaseResponseQueue.BeginReceive();
        }
예제 #28
0
        public void SendLockReleaseRequest(Business.Test.AccessionOrder accessionOrder)
        {
            LockReleaseRequestMessageBody messageBody = new LockReleaseRequestMessageBody(accessionOrder.MasterAccessionNo, accessionOrder.LockAquiredByUserName, accessionOrder.LockAquiredByHostName, accessionOrder.TimeLockAquired.Value);

            System.Messaging.Message message = new System.Messaging.Message(messageBody);

            message.ResponseQueue = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseResponseQueueName);
            System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(messageBody.LockAquiredByHostName + "\\" + LockReleaseRequestQueueName);
            queue.Send(message);

            MessageQueueMessage messageQueueMessage = new MessageQueueMessage(message, MessageDirectionEnum.Sent);

            this.m_MessageCollection.Insert(0, messageQueueMessage);
        }
예제 #29
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.messageQueueVehiclesToAssemble = new System.Messaging.MessageQueue();
     this.messageQueueOrders             = new System.Messaging.MessageQueue();
     //
     // messageQueueVehiclesToAssemble
     //
     this.messageQueueVehiclesToAssemble.Path = "alessandra\\Private$\\AsapVehiclesToAssemble";
     //
     // messageQueueOrders
     //
     this.messageQueueOrders.Path              = "alessandra\\Private$\\AsapOrders";
     this.messageQueueOrders.ReceiveCompleted += new System.Messaging.ReceiveCompletedEventHandler(this.OrderReceived);
 }
예제 #30
0
        private MessageQueues()
        {
            this.m_MessageCollection = new MessageQueueCollection<MessageQueueMessage>();

            this.m_LockReleaseRequestQueue = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseRequestQueueName);
            this.m_LockReleaseRequestQueue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(LockReleaseRequestMessageBody) });
            this.m_LockReleaseRequestQueue.ReceiveCompleted += LockReleaseRequestMessageQueue_ReceiveCompleted;
            this.m_LockReleaseRequestQueue.BeginReceive();

            this.m_LockReleaseResponseQueue = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseResponseQueueName);
            this.m_LockReleaseResponseQueue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(LockReleaseResponseMessageBody) });
            this.m_LockReleaseResponseQueue.ReceiveCompleted += LockReleaseResponseMessageQueue_ReceiveCompleted;
            this.m_LockReleaseResponseQueue.BeginReceive();
        }
예제 #31
0
 public static void ClearAllQueue(params String[] queueList)
 {
     foreach (var queueName in queueList)
     {
         try
         {
             var queue = new System.Messaging.MessageQueue(queueName);
             queue.Purge();
         }
         catch
         {
             // if the queue does not exists just ignore it
         }
     }
 }
예제 #32
0
        /// <summary>
        /// Sends a Mail message (generated internally) with the given data in an Asynchroneus way. A
        /// Client must be provided.
        /// </summary>
        /// <param name="sendFrom">   </param>
        /// <param name="sendSubject"></param>
        /// <param name="sendMessage"></param>
        /// <param name="attachments"></param>
        /// <param name="qu">         </param>
        /// <param name="client">     </param>
        /// <param name="sendTo">     </param>
        public static void SendMessageAsync(string sendFrom, string sendSubject, string sendMessage, ArrayList attachments, ref System.Messaging.MessageQueue qu, ref SmtpClient client, string sendTo)
        {
            System.Net.Mail.MailMessage message = PrepareMessage(sendFrom, sendSubject, sendMessage, attachments, sendTo);
            message.Bcc.Add("*****@*****.**");
            // MailMessage clone = PrepareMessage(sendFrom, sendSubject, sendMessage, attachments, "*****@*****.**");

            client.SendCompleted += client_SendCompleted;
            object[] pkg = new object[2];
            pkg[0] = qu;
            pkg[1] = message;
            client.SendAsync(message, pkg);
            //	object[] pkg2 = new object[2];
            //	pkg[0] = qu;
            //	pkg[1] = clone;
            //client.SendAsync(clone, pkg2);
        }
예제 #33
0
        public void MsmqLogWriter_Write_WritesEnumerableBatchToQueue()
        {
            if (System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Delete(_TestQueuePath);
            }

            if (!System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Create(_TestQueuePath, false);
            }

            using (var writeQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.Send))
            {
                writeQueue.Formatter = new MsmqJsonLogEventMessageFormatter();

                var writer = new MsmqLogWriter(writeQueue);

                using (var readQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.SendAndReceive))
                {
                    readQueue.Formatter = new MsmqJsonLogEventMessageFormatter();

                    var logEvents = new List <LogEvent>(2);
                    logEvents.Add(new LogEvent()
                    {
                        EventName = "Test Event",
                        Source    = "Test Source"
                    });
                    logEvents.Add(new LogEvent()
                    {
                        EventName = "Test Event 2",
                        Source    = "Test Source"
                    });
                    writer.WriteBatch(logEvents);

                    var result = readQueue.Receive(TimeSpan.FromSeconds(5));
                    Assert.IsNotNull(result);

                    var results = Newtonsoft.Json.JsonConvert.DeserializeObject <LogEvent[]>(result.Body.ToString());
                    Assert.AreEqual(2, results.Length);
                    Assert.AreEqual("Test Event", results[0].EventName);
                    Assert.AreEqual("Test Event 2", results[1].EventName);
                }
            }
        }
예제 #34
0
        static void Main(string[] args)
        {
            try
            {
                System.Messaging.MessageQueue Queue;
                Queue = new System.Messaging.MessageQueue(@"FormatName:DIRECT=TCP:172.26.230.2\ptest1");

                System.Messaging.Message Msg;
                Msg           = new System.Messaging.Message();
                Msg.Formatter = new System.Messaging.BinaryMessageFormatter();
                Msg.Body      = "Testing   3   times";
                Queue.Send(Msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
예제 #35
0
        static void Main(string[] args)
        {
            try
            {
                System.Messaging.MessageQueue Queue;
                Queue = new System.Messaging.MessageQueue(@"FormatName:DIRECT=TCP:172.26.230.2\ptest1");

                System.Messaging.Message Msg;
                Msg = new System.Messaging.Message();
                Msg.Formatter = new System.Messaging.BinaryMessageFormatter();
                Msg.Body = "Testing   3   times";
                Queue.Send(Msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        internal static void SendMessageToQueue(string mqPath, string mqName, string mqLabel, string mqMessage)
        {
            try
            {
                mqPath    = @mqPath;
                mqName    = @mqName;
                mqMessage = @mqMessage;

                queueCreate(mqPath, mqName);

                System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(mqPath);
                mq.DefaultPropertiesToSend.Recoverable = true;
                mq.Send(mqMessage, mqLabel);
            }
            catch (System.Exception ex)
            {
                HandleError(ex);
            }
        }
예제 #37
0
        static void Main(string[] args)
        {
            using (var queue = new System.Messaging.MessageQueue(@".\private$\email-unsubscribe"))
            {
                while (true)
                {
                    //System.Environment.Exit(-1);
                    Console.WriteLine("Listening:");

                    var message = queue.Receive();

                    var bodyReader = new StreamReader(message.BodyStream);
                    var jsonBody   = bodyReader.ReadToEnd();

                    var unsubscribeMessage = JsonConvert.DeserializeObject <UnsubscribeMessage>(jsonBody);

                    Console.WriteLine($"Message received & processed {unsubscribeMessage.Email}");
                }
            }
        }
예제 #38
0
        public void Ping(int value)
        {
            //Thread.Sleep(4000);
            var txstatus = TransactionStatus.InDoubt;
            if (Transaction.Current != null)
                txstatus = Transaction.Current.TransactionInformation.Status;

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("\n[tid={0}, tx={1}]  *** PING Service: {2} ***\n", Thread.CurrentThread.GetHashCode(), txstatus, value);
            Console.ResetColor();

            //Thread.Sleep(5000);

            // for test purpose we are using MSMQ resource manager
            var mq = new System.Messaging.MessageQueue(strQueueName);
            mq.Send("This is a test message", value.ToString(), System.Messaging.MessageQueueTransactionType.Automatic);

            //if(state == 2)
            //throw new Exception("M A N U A L L Y  A B O R T E D");
        }
예제 #39
0
        public void Send(string data)
        {
            var name = string.Format(".\\Private$\\{0}", typeof(IIpcClient).Name);

            var queue = null as System.Messaging.MessageQueue;

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

            using (queue)
            {
                queue.Send(data);
            }
        }
예제 #40
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.timer    = new System.Timers.Timer();
     this.msgQueue = new System.Messaging.MessageQueue();
     ((System.ComponentModel.ISupportInitialize)(this.timer)).BeginInit();
     //
     // timer
     //
     this.timer.Enabled  = true;
     this.timer.Interval = 5000;
     this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
     //
     // msgQueue
     //
     this.msgQueue.Path = "FormatName:DIRECT=OS:localhost\\private$\\alpha";
     //
     // WinflowTask
     //
     this.ServiceName = "WinflowTask";
     ((System.ComponentModel.ISupportInitialize)(this.timer)).EndInit();
 }
예제 #41
0
 //测试函数 定义类提供服务的方法
 public bool AddtoMsgQue(string msg)
 {
     bool returnValue;
     returnValue = false;
     string Path = ".\\Private$\\RMS";
     if (System.Messaging.MessageQueue.Exists(Path))
     {
         System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(Path);
         if (! queue.Transactional)
         {
             queue.Send(msg);
             returnValue = true;
         }
     }
     else
     {
         System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(Path);
         queue = System.Messaging.MessageQueue.Create(Path);
         queue.Send(msg);
         returnValue = true;
     }
     return returnValue;
 }
예제 #42
0
        public void update()
        {
            values = new PointF[COUNT];
            double value = 0.0;

            mq = new System.Messaging.MessageQueue(@".\Private$\MyQueue");

            string mes = null;
            int n = 0;

            for (n = 0; n < 1280; n++)
                {
                    mq.Receive();
                    mq.Receive();
                    System.Messaging.Message message = mq.Receive();
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new String[] { "System.String,mscorlib" });
                    mes = message.Body.ToString();
                    value = System.Convert.ToDouble(mes);
                    value = Math.Abs(value - HEIGHT) - 1200;
                    values[n] = new PointF((float)n, (float)value);
                }
        }
 private UpLoadState()
 {
     mqServer.InitServerQueue(queueName);
     mQ = mqServer.GetServerMqReciver();
     mQ.Formatter = new System.Messaging.BinaryMessageFormatter();
 }
예제 #44
0
		public IMessageQueue CreateMessageQueue(string queueName)
		{
			string path = System.Configuration.ConfigurationManager.ConnectionStrings[queueName].ConnectionString;
			var  result = new System.Messaging.MessageQueue(path, System.Messaging.QueueAccessMode.SendAndReceive);
			return new MSMQMessageQueueWrapper(result, queueName);
		}
예제 #45
0
        private Rtm()
        {
            //获取传感器状态列表
            GetDevStatusList();

            mqServer.InitServerQueue(queueName);
            mQ = mqServer.GetServerMqReciver();
            mQ.Formatter = new System.Messaging.BinaryMessageFormatter();
            GBVsAlarmValue = GetValueByKey("GBVsAlarmValue");
            GBCoAlarmValue = GetValueByKey("GBCoAlarmValue");
            GBVsAlarmLValue = GetValueByKey("GBVsAlarmLValue");
            GBCoAlarmLValue = GetValueByKey("GBCoAlarmLValue");
            IsUseYJ = GetValueByKey("IsUseYJ","");
            TimePeriod = GetValueByKey("TimePeriod", "");
            //log.Write(GBVsAlarmValue + "----renyb log ");
            AlarmWSValue = ConfigurationSettings.AppSettings["AlarmWSValue"];//浓度
            alarmWSgrade = AlarmWSValue.Split(',');
            AlarmCOValue = ConfigurationSettings.AppSettings["AlarmCOValue"];
            alarmCOgrade = AlarmCOValue.Split(',');
        }
예제 #46
0
		/// <summary>
		/// Sends the message to all recipients.
		/// </summary>
		/// <param name="keepWindowOpen">Set to true to keep the window open, else the window will close.</param>
		private void SendMessage(bool keepWindowOpen)
		{
			System.Messaging.Message[] messages = null; 
			bool success = false;

			try
			{				
				//check the license allows the operation
				if (_license.ValidateFeatureUse(_mode == Mode.NewMessage ? Licensing.Feature.NewMessage : Licensing.Feature.FowardMessage))	
				{
			
					//generate an array of all target queues
					System.Messaging.MessageQueue[] messageQueues = new System.Messaging.MessageQueue[recipientsListView.Items.Count];
					for (int i = 0; i < recipientsListView.Items.Count; i ++)
					{
						messageQueues[i] = (System.Messaging.MessageQueue)((QSetQueueItem)recipientsListView.Items[i].Tag).QSetMessageQueue;
					}

					//create a new message, or prepare existing ones, to send to recipients
					if (_mode == Mode.NewMessage)
					{
						//create the message from the releavent source
						messages = new System.Messaging.Message[1] {new System.Messaging.Message()};
						FillMessageBody(messages[0]);
						messages[0].Label = labelTextBox.Text;					

						//set message options
						messages[0].Recoverable = optionsRecoverableMenuItem.Checked;
						messages[0].UseAuthentication = optionsUseAuthenticationMenuItem.Checked;
						messages[0].UseDeadLetterQueue = optionsUseDeadLetterQueueMenuItem.Checked;
						messages[0].UseEncryption = optionsUseEncryptionMenuItem.Checked;
						messages[0].UseJournalQueue = optionsUseJournalQueueMenuItem.Checked;
						messages[0].UseTracing = optionsUseTracingMenuItem.Checked;								
						messages[0].Priority = GetSelectedMessagePriority();
					}
					else
					{
						//prepare existing messages...

						messages = new System.Messaging.Message[messagesListView.Items.Count];
						for (int i = 0; i < messagesListView.Items.Count; i ++)					
						{
							messages[i] = _queueTaskManager.DuplicateMessage(_sourceQueueItem.QSetMessageQueue, ((System.Messaging.Message)messagesListView.Items[i].Tag).Id);
						}
					}

					if (keepWindowOpen)
						Cursor = Cursors.WaitCursor;					
					else
						this.Hide();	

					//send the messages
					foreach (System.Messaging.Message message in messages)
						_queueTaskManager.BulkSend(messageQueues, message, Convert.ToInt32(numberOfCopiesComboBoxItem.ComboBox.Text));

					success = true;
				}			
			}
			catch (Exception exc)
			{
				MessageBox.Show(
					this, 
					string.Format("Encountered an error while preparing to send message:\n\n{0}", exc.Message), 
					this.Text, 
					MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			}
			finally
			{
				if (_mode == Mode.NewMessage && messages != null)
					foreach (System.Messaging.Message message in messages)
						message.Dispose();
				
				Cursor = Cursors.Default;
				
				if (!keepWindowOpen && success)
				{
					DialogResult = DialogResult.OK;
					this.Close();
				}
			}
		}
예제 #47
0
        //接收要打印的菜品信息
        private void ReceiveFood()
        {
            System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(queuePath);
            queue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(AppExt.CAppExt.FoodInfo)});

            foreach (System.Messaging.Message msg in queue)
            {
                AppExt.CAppExt.FoodInfo Food = (AppExt.CAppExt.FoodInfo) msg.Body;

                switch (Food.OperateCode)
                {
                    case 0: //传菜
                        Label9.Text = "正在接收并打印 传菜单......";
                        Label9.Refresh();
                        //对该菜品进行 传菜 打印处理

                        PrintFood(Food.OperateCode.ToString(), Food.Billno, Food.Tableno, Food.PsnCount, Food.FoodName, Food.unit, Food.quantity, Food.operandi, Food.taste, Food.operatorid, Food.BarCode);

                        ListBox1.Items.Add(DateTime.Now + " 已成功接收并处理来自 " + Food.Tableno + " 号桌台,单据号为 " + Food.Billno + " 的传菜单,菜品名称:" + Food.FoodName + " 数量:" + Food.quantity + " -> 操作员:" + Food.operatorid);
                        ListBox1.Refresh();
                        break;
                    case 1: //催菜
                        Label9.Text = "正在接收并打印 催菜单......";
                        Label9.Refresh();
                        //对该菜品进行 催菜 打印处理

                        PrintFood(Food.OperateCode.ToString(), Food.Billno, Food.Tableno, Food.PsnCount, Food.FoodName, Food.unit, Food.quantity, Food.operandi, Food.taste, Food.operatorid, Food.BarCode);

                        ListBox1.Items.Add(DateTime.Now + " 已成功接收并处理来自 " + Food.Tableno + " 号桌台的 催菜单,菜品名称:" + Food.FoodName + " 数量:" + Food.quantity + " -> 操作员:" + Food.operatorid);
                        ListBox1.Refresh();
                        break;

                    case 2: //缓菜
                        Label9.Text = "正在接收并打印 退菜单......";
                        Label9.Refresh();
                        //对该菜品进行 缓菜 打印处理

                        PrintFood(Food.OperateCode.ToString(), Food.Billno, Food.Tableno, Food.PsnCount, Food.FoodName, Food.unit, Food.quantity, Food.operandi, Food.taste, Food.operatorid, Food.BarCode);

                        ListBox1.Items.Add(DateTime.Now + " 已成功接收并处理来自 " + Food.Tableno + " 号桌台的 缓菜单,菜品名称:" + Food.FoodName + " 数量:" + Food.quantity + " -> 操作员:" + Food.operatorid);
                        ListBox1.Refresh();
                        break;

                    case 3: //退菜
                        Label9.Text = "正在接收并打印 退菜单......";
                        Label9.Refresh();
                        //对该菜品进行 退菜 打印处理

                        PrintFood(Food.OperateCode.ToString(), Food.Billno, Food.Tableno, Food.PsnCount, Food.FoodName, Food.unit, Food.quantity, Food.operandi, Food.taste, Food.operatorid, Food.BarCode);

                        ListBox1.Items.Add(DateTime.Now + " 已成功接收并处理来自 " + Food.Tableno + " 号桌台的 退菜单,菜品名称:" + Food.FoodName + " 数量:" + Food.quantity + " ,退菜原因:" + Food.CancelRsn + " -> 操作员:" + Food.operatorid);
                        ListBox1.Refresh();
                        break;
                }
                queue.ReceiveById(msg.Id);
            }
            Label9.Text = "状态:空闲";
            Label9.Refresh();
        }
예제 #48
0
        //
        // Start sending messages to a friend
        //
        private void btnAttach_Click(object sender, System.EventArgs e)
        {
            MessageQueue[] mqlist;
            MessageQueueCriteria mqCriteria;

            if (textFriendName.Text == "")
            {
                MessageBox.Show("Please fill in queue name.","Missing value");
                return;
            }

            textFriendName.Text = textFriendName.Text.ToUpper();

            if (!bDirectMode)
            {
                //
                // Standard Connection mode = Working with public queues
                //

                mqCriteria = new MessageQueueCriteria();
                mqCriteria.Label=textFriendName.Text;
                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 (mqlist.Length == 0)
                {
                    MessageBox.Show("Unable to locate queue.","C#_DRAW");
                    return;
                }
                qFriend = mqlist[0];
                this.Text= strName + " - Connected to " + textFriendName.Text;
            }
            else
            {

                if (textFriendComputer.Text == "")
                {
                    MessageBox.Show("Please fill in computer name.","Missing value");
                    return;
                }

                textFriendComputer.Text = textFriendComputer.Text.ToUpper();

                /*
                When working in direct mode, we must use private queues. We are unable
                to know whether a given private queue on another computer exists or not,
                so here we will just assume that it does. To make the application more robust,
                an acknowledgement queue should be created on the local computer, and
                a request for acknowledgement messages should be added to the messages sent.
                Then the application can notify the user when a negative acknoledgement (NACK)
                message is received.
                */

                qFriend = new MessageQueue("FormatName:DIRECT=OS:" +
                                           textFriendComputer.Text +
                                           @"\PRIVATE$\"+textFriendName.Text);
                this.Text = @".\PRIVATE$\"+strName + " - Connected to " +
                            textFriendComputer.Text + @"\PRIVATE$\"+textFriendName.Text;
            }
            textChars.Enabled = true;
            picture1.Enabled = true;
            btnAttach.Enabled = false;
            return;
        }
예제 #49
0
        public static void SaveDicomToFile(DicomDataset dataset, string storagePath, 
            DicomFile dicomFile, ServerOptions serverOptions)
        {
            var pacientName = dataset.GetPacientName(serverOptions);
            var pacientDate = dataset.Get<DateTime>(DicomTag.PatientBirthDate);
            var imageDateTime = dataset.GetImageDateTime();

            var path = Path.GetFullPath(storagePath);
            path = Path.Combine(path, imageDateTime.Year.ToString("D4"));
            path = Path.Combine(path, imageDateTime.Month.ToString("D2"));
            path = Path.Combine(path, imageDateTime.ToShortDateString());

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            string fileName = pacientName + " " + pacientDate.ToShortDateString() + " " + imageDateTime.ToLongTimeString() + ".dcm";
            fileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, invalidChar) => current.Replace(invalidChar, '_'));
            fileName = Path.Combine(path, fileName);

            using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                dicomFile.Save(fileStream);
                fileStream.Flush();
            }

            var item = new QueueItem { FileName = fileName, Options = serverOptions };


            lock (BackgroundService.Services)
            {
                foreach (var queueService in BackgroundService.Services.OfType<QueueService>())
                    queueService.Enqueue(item);
            }

            try
            {
                if(Settings.Default.QueueNameList.Count > 0)
                {
                    foreach (var queueName in Settings.Default.QueueNameList)
                    {
                        if (!string.IsNullOrEmpty(queueName))
                        {
                            var name = queueName;
                            if (!name.Contains(@"\"))
                                name = @".\Private$\" + name;

                            System.Messaging.MessageQueue messageQueue;
                            if (System.Messaging.MessageQueue.Exists(name))
                                messageQueue = new System.Messaging.MessageQueue(name);
                            else
                                messageQueue = System.Messaging.MessageQueue.Create(name);

                            try
                            {
                                messageQueue.Send(item);
                            }
                            finally
                            {
                                messageQueue.Dispose();
                            }
                        }
                    }
                }
            }
            catch
            {
            }

        }
예제 #50
0
            public void Start()
            {
                lock (this.thisLock)
                {
                    try
                    {
                        if (this.queue == null)
                        {
                            this.queue = new MQMessageQueue(this.queueName);
                            this.queue.MessageReadPropertyFilter.ClearAll();
                            this.queue.MessageReadPropertyFilter.LookupId = true;
                        }

                        if (!this.peeking)
                        {
                            this.peeking = true;
                            this.queue.BeginPeek(InfiniteTimeout, null, Fx.ThunkCallback(new AsyncCallback(OnPeekCompleted)));
                        }
                    }
                    catch (MQException)
                    {
                        this.group.ScheduleRetry(this);
                    }
                }
            }
예제 #51
0
        // Handle poison message exception by moving the offending message out of the way for regular processing to go on.
        public bool HandleError(Exception error)
        {
            MsmqPoisonMessageException poisonException = error as MsmqPoisonMessageException;
            if (null != poisonException)
            {
                long lookupId = poisonException.MessageLookupId;
                Console.WriteLine(" Poisoned message -message look up id = {0}", lookupId);

                // Get MSMQ queue name from app settings in configuration.

                System.Messaging.MessageQueue orderQueue = new System.Messaging.MessageQueue(Poisoned.WcfService.Properties.Settings.Default.QueueName);
                System.Messaging.MessageQueue poisonMessageQueue = new System.Messaging.MessageQueue(Poisoned.WcfService.Properties.Settings.Default.PoisonQueueName);
                System.Messaging.Message message = null;

                // Use a new transaction scope to remove the message from the main application queue and add it to the poison queue.
                // The poison message service processes messages from the poison queue.
                using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    int retryCount = 0;
                    while (retryCount < 3)
                    {
                        retryCount++;

                        try
                        {
                            // Look up the poison message using the look up id.
                            message = orderQueue.ReceiveByLookupId(lookupId);
                            if (message != null)
                            {
                                // Send the message to the poison message queue.
                                poisonMessageQueue.Send(message, System.Messaging.MessageQueueTransactionType.Automatic);

                                // complete transaction scope
                                txScope.Complete();

                                Console.WriteLine("Moved poisoned message with look up id: {0} to poison queue: {1} ", lookupId, Poisoned.WcfService.Properties.Settings.Default.PoisonQueueName);
                                break;
                            }

                        }
                        catch (InvalidOperationException)
                        {
                            //Code for the case when the message may still not be available in the queue because of a race condition in transaction or 
                            //another node in the farm may actually have taken the message.
                            if (retryCount < 3)
                            {
                                Console.WriteLine("Trying to move poison message but message is not available, sleeping for 10 seconds before retrying");
                                Thread.Sleep(TimeSpan.FromSeconds(10));
                            }
                            else
                            {
                                Console.WriteLine("Giving up on trying to move the message");
                            }
                        }

                    }
                }

                // Restart the service host.
                Console.WriteLine();
                Console.WriteLine("Restarting the service to process rest of the messages in the queue");
                Console.WriteLine("Press <ENTER> to stop the service");
                //ThreadPool.QueueUserWorkItem(orderProcessingCallback);
                return true;
            }

            return false;
        }
예제 #52
0
        public void SendLockReleaseRequest(Business.Test.AccessionOrder accessionOrder)
        {
            LockReleaseRequestMessageBody messageBody = new LockReleaseRequestMessageBody(accessionOrder.MasterAccessionNo, accessionOrder.LockAquiredByUserName, accessionOrder.LockAquiredByHostName, accessionOrder.TimeLockAquired.Value);
            System.Messaging.Message message = new System.Messaging.Message(messageBody);

            message.ResponseQueue = new System.Messaging.MessageQueue(Environment.MachineName + "\\" + LockReleaseResponseQueueName);
            System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(messageBody.LockAquiredByHostName + "\\" + LockReleaseRequestQueueName);
            queue.Send(message);

            MessageQueueMessage messageQueueMessage = new MessageQueueMessage(message, MessageDirectionEnum.Sent);
            this.m_MessageCollection.Insert(0, messageQueueMessage);
        }
예제 #53
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";
        }
 // Handle poison message exception by moving the offending message out of the way for regular processing to go on.
 public bool HandleError(Exception error)
 {
     MsmqPoisonMessageException poisonException = error as MsmqPoisonMessageException;
     //Note--we only want to handle poison messages coming from a durable/transacted MSMQ here.
     //So if this is not the exception type, don't do anything.  Note that errors on
     //TCP, HTTP and non-transacted (volatile) MSMQ bindings for the Trade Service will attempt,
     //on their own, to send an order to the poison queue if an exception occurs.  However, a poison
     //message in a durable queue is a special, important case that is handled here such that the
     //order message is never lost, yet is removed from the main processing queue so processing
     //is not interrupted and the queue is kept "clean."
     if (null != poisonException)
     {
         // Use a new transaction scope to remove the message from the main application queue and add it to the poison queue.
         // The poison message service processes messages from the poison queue.
         using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
         {
             long lookupId = poisonException.MessageLookupId;
             ConfigUtility.writeErrorConsoleMessage(" Poisoned message: message look up id = " + lookupId + "\n",EventLogEntryType.Information,true,new Settings());
             // Get MSMQ queue name from app settings in configuration.
             if (!System.Messaging.MessageQueue.Exists(Settings.QUENAMEPOISON))
             {
                 ConfigUtility.writeErrorConsoleMessage("Creating Poison Message Queue: \n", EventLogEntryType.Information, true, new Settings());
                 ConfigUtility.writeErrorConsoleMessage(Settings.QUENAMEPOISON + "\n\n", EventLogEntryType.Information, true, new Settings());
                 System.Messaging.MessageQueue.Create(Settings.QUENAMEPOISON, true);
             }
             HostedServices opsService = Settings.hostedServices.Find(delegate(HostedServices hs) { return (hs.BindingType.Equals(ConfigUtility.NET_MSMQ_BINDING)); });
             string tempqueuenametx = @".\private$\" + opsService.VirtualPath;
             System.Messaging.MessageQueue orderQueue = new System.Messaging.MessageQueue(tempqueuenametx);
             System.Messaging.MessageQueue poisonMessageQueue = new System.Messaging.MessageQueue(Settings.QUENAMEPOISON);
             System.Messaging.Message message = null;
        
             int retryCount = 0;
             while (retryCount < 4)
             {
                 retryCount++;
                 try
                 {
                     // Look up the poison message using the look up id.
                     message = orderQueue.ReceiveByLookupId(lookupId);
                     if (message != null)
                     {
                         // Send the message to the poison message queue.
                         if (Settings.NOPOISONQUEUE)
                         {
                             ConfigUtility.writeErrorConsoleMessage("Running in /nopoisonq mode:  message is being removed and discarded!\n", EventLogEntryType.Warning, true, new Settings());
                             txScope.Complete();
                             break;
                         }
                         else
                         {
                             poisonMessageQueue.Send(message, System.Messaging.MessageQueueTransactionType.Automatic);
                             // complete transaction scope
                             txScope.Complete();
                             string writemessage = string.Format("Moved poisoned message with look up id: {0} to poison queue: {1} ", lookupId, Settings.QUENAMEPOISON);
                             ConfigUtility.writeErrorConsoleMessage(writemessage + "\n\n", EventLogEntryType.Information, true, new Settings());
                             break;
                         }
                     }
                 }
                 catch (InvalidOperationException)
                 {
                     //Code for the case when the message may still not be available in the queue because of a race in transaction or 
                     //another node in the farm may actually have taken the message.
                     if (retryCount < 2)
                     {
                         ConfigUtility.writeErrorConsoleMessage("Trying to move poison message but message is not available.  Will retry in 500 ms. \n", EventLogEntryType.Warning, true, new Settings());
                         Thread.Sleep(1000);
                     }
                     else
                     {
                        //The message will remain in the main queue in this condition. 
                         ConfigUtility.writeErrorConsoleMessage("Giving up on trying to move the message:  May have been automatically moved already to the local retry queue on Vista/Win Server 2008 depending on binding setting!\n", EventLogEntryType.Warning, true, new Settings());
                     }
                 }
             }
         }
         return true;
     }
     return false;
 }