public void FormatString ()
 {
     Type[] t = { typeof (string) };
     string s = "this is a test string";
     
     Stream ms = new MemoryStream ();
     mock1.ExpectAndReturn ("get_BodyStream", ms);
     mock1.ExpectAndReturn ("get_BodyStream", ms);
     
     mock2.ExpectAndReturn ("get_BodyStream", ms);
     mock2.ExpectAndReturn ("get_BodyStream", ms);
     
     Message m = TestUtils.CreateMessage (msg1);
     
     XmlMessageFormatter xmlF = new XmlMessageFormatter ();
     m.Formatter = xmlF;
     m.Formatter.Write (m, s);
     Stream stream = m.BodyStream;
     
     Assert.AreEqual (typeof (string), xmlF.TargetTypes[0]);
     
     Assert.IsTrue (stream.Length > 0);
     
     Message m2 = TestUtils.CreateMessage (msg2);
     m2.Formatter = new XmlMessageFormatter (t);
     
     Assert.AreEqual (s, (string) m2.Formatter.Read (m2), "The string did not serialise/deserialise properly");
     
     mock1.Verify ();
     mock2.Verify ();
 }
Exemple #2
0
        static void Main(string[] args)
        {
            ConsumerRegistry.Configure();

            var consumer = ObjectFactory.GetInstance<IConsumer>();
            var messagesToWriteToDb = consumer.ConsumeLogMessages();
            var formatter = new XmlMessageFormatter(new[] {typeof (LogMessage)});

            using (var connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))
            {
                connection.Open();

                foreach (var messageToWrite in messagesToWriteToDb)
                {
                    messageToWrite.Formatter = formatter;
                    var message = (LogMessage) messageToWrite.Body;

                    using (var command = new SqlCommand("CreateLogMessage", connection) { CommandType = CommandType.StoredProcedure})
                    {
                        command.Parameters.AddWithValue("@Category", message.Category);
                        command.Parameters.AddWithValue("@Severity", message.Severity);
                        command.Parameters.AddWithValue("@Description", message.Description);
                        command.Parameters.AddWithValue("@CreatedDate", message.CreatedDate);
                        command.Parameters.AddWithValue("@CreatedBy", message.CreatedBy);

                        command.ExecuteNonQuery();
                    }
                }
            }
        }
Exemple #3
0
 private static void Queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
 {
     MessageQueue mq = (MessageQueue)sender;
     var message = mq.EndReceive(e.AsyncResult);
     System.Messaging.XmlMessageFormatter stringFormatter;
     stringFormatter = new System.Messaging.XmlMessageFormatter(
        new string[] { "System.String" });
     message.Formatter = stringFormatter;
     Console.WriteLine(" e.Message:" + message.Body);
     mq.BeginReceive();
 }
        private MessageQueue InitializeMQ(string MQName, XmlMessageFormatter formatter)
        {
            MessageQueue MQ;

            if (MessageQueue.Exists(MQName))
                MQ = new MessageQueue(MQName);
            else
                MQ = MessageQueue.Create(MQName);

            MQ.Formatter = formatter;

            return MQ;
        }
 public object Clone()
 {
     XmlMessageFormatter formatter = new XmlMessageFormatter {
         targetTypes = this.targetTypes,
         targetTypeNames = this.targetTypeNames,
         typesAdded = this.typesAdded,
         typeNamesAdded = this.typeNamesAdded
     };
     foreach (Type type in this.targetSerializerTable.Keys)
     {
         formatter.targetSerializerTable[type] = new XmlSerializer(type);
     }
     return formatter;
 }
        public static IMessageFormatter GetMessageFormatter(this MessageFormatType formatType)
        {
            IMessageFormatter formatter = null;
            switch (formatType) {
                case MessageFormatType.XML:
                    formatter = new XmlMessageFormatter();
                    break;
                case MessageFormatType.Binary:
                    formatter = new BinaryMessageFormatter();
                    break;
                default:
                    throw new NotSupportedException(String.Format("Message format type {0} is not supported.", formatType));
            }

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

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

            }
            Console.ReadLine();
        }
Exemple #8
0
 static void Main()
 {
     string queueName = @".\Private$\myqueue1";
     try
     {
         if (!MessageQueue.Exists(queueName))
         {
             MessageQueue.Create(queueName);
         }
         //var formatter = new BinaryMessageFormatter();
         var formatter = new XmlMessageFormatter();
         var queue = new MessageQueue(queueName);
         queue.Formatter = formatter;
         queue.Send("Sample Message1", "Label1");
         queue.Send("Sample Message2", "Label2");
         queue.Send("Sample Message3", "Label3");
         Console.WriteLine("Send Message successfully.");
     }
     catch (MessageQueueException ex)
     {
         Console.WriteLine(ex.Message);
     }
     Console.ReadKey();
 }
Exemple #9
0
 public MsmqListener(string queuePath, XmlMessageFormatter xmlMessageFormatter)
 {
     _queue = new MessageQueue(queuePath) {Formatter = xmlMessageFormatter};
 }
Exemple #10
0
        public void TestMethod_Recive()
        {
            var path = @".\Private$\test";
            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }
            var formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            MessageQueue mq = new MessageQueue();
            mq.Formatter = formatter;
            mq.Path = path;


            do
            {

                try
                {
                    var msg = mq.Receive(TimeSpan.FromSeconds(0.1));

                    if (msg == null)
                        break;


                    Console.WriteLine(msg.Body.ToString());
                }
                catch (System.Messaging.MessageQueueException)
                {

                    Console.WriteLine("time out");

                    break;
                }


            } while (true);

        }
Exemple #11
0
        public void TestMethod1()
        {
            /*    注意事项:
       *    1. 发送和接受消息的电脑都要安装MSMQ。
       *    2. 在工作组模式下不能访问public队列。
       *    3. 访问本地队列和远程队列,path字符串格式不太一样。
       *    4. public队列存在于消息网络中所有主机的消息队列中。
       *    5. private队列则只存在于创建队列的那台主机上。
       */

            #region 以下是private队列访问示例:

            //访问本地电脑上的消息队列时Path的格式可以有如下几种:


            var path = @".\Private$\test";
            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }
            var formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            MessageQueue mq = new MessageQueue();
            mq.Formatter = formatter;
            mq.Path = path;
            //mq.Path = @"sf00902395d34\Private$\test";  //sf00902395d34是主机名
            //mq.Path = @"FormatName:DIRECT=OS:sf00902395d34\Private$\test";
            //mq.Path = @"FormatName:DIRECT=OS:localhost\Private$\test";

            //访问远程电脑上的消息队列时Path的格式
            //mq.Path = @"FormatName:DIRECT=OS:server\Private$\test";


            //构造消息
            Message msg = new Message();



            for (int i = 0; i < 1000000; i++)
            {
                msg.Body = i + "Hello,world. This is a test message. " + DateTime.Now.ToString();
                //向队列发送消息
                mq.Send(msg);

            }
            //mq.BeginReceive(TimeSpan.FromSeconds(10), null, ar =>
            //                                           {
            //                                               Message m = mq.EndReceive(ar);

            //                                               Console.WriteLine(m.Body.ToString());
            //                                               var a = 1;
            //                                           });
            //读取队列中的所有消息
            //Message[] msgs = mq.GetAllMessages();
            //foreach (Message m in msgs)
            //{
            //    Console.WriteLine(m.Body.ToString());
            //
            //}




            //清除队列中的所有消息
            //mq.Purge();

            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));

            #endregion
        }
        /// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Clone"]/*' />
        /// <devdoc>
        ///    This method is needed to improve scalability on Receive and ReceiveAsync scenarios.  Not requiring 
        ///     thread safety on read and write.
        /// </devdoc>
        public object Clone()
        {
            XmlMessageFormatter formatter = new XmlMessageFormatter();
            formatter.targetTypes = targetTypes;
            formatter.targetTypeNames = targetTypeNames;
            formatter.typesAdded = typesAdded;
            formatter.typeNamesAdded = typeNamesAdded;
            foreach (Type targetType in targetSerializerTable.Keys)
                formatter.targetSerializerTable[targetType] = new XmlSerializer(targetType);

            return formatter;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlMessageConverter"/> class.
 /// </summary>
 /// <param name="messageFormatter">The message formatter.</param>
 public XmlMessageConverter(XmlMessageFormatter messageFormatter)
 {
     this.messageFormatter = messageFormatter;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlMessageConverter"/> class.
 /// </summary>
 public XmlMessageConverter()
 {
     messageFormatter = new XmlMessageFormatter();
 }
Exemple #15
0
		/// <summary>
		/// Attempts to extract the content of a message in string format.
		/// </summary>
		/// <param name="message">Message to extract.</param>
		/// <param name="usedMessageFormatterType">Informs which formatter was used to extract the message.</param>
		/// <returns>A string if successful else null.</returns>
		private string ExtractMessageContent(System.Messaging.Message message)
		{
			string result = null;

			//create an array of formatters, ordered as we are going to attempt to use them
			IMessageFormatter[] formatterArray = new IMessageFormatter[3];
			formatterArray[0] = new ActiveXMessageFormatter();
			formatterArray[1] = new XmlMessageFormatter();
			formatterArray[2] = new BinaryMessageFormatter();

			//attempt to read the message body using the different formatters			
			foreach (IMessageFormatter formatter in formatterArray)
			{				
				try
				{
					//attempt to extract the message
					message.Formatter = formatter;					
					if (message.Formatter is ActiveXMessageFormatter)
						result = Convert.ToString(message.Body);
					else
					{
						message.BodyStream.Position=0;									
						StreamReader sr = new StreamReader(message.BodyStream);	//do not dispose this stream else the underlying stream will close				
						result = sr.ReadToEnd(); 				
					}
					
					//message has been successfully extracted (else we would have thrown an exception)					

					//check the xml formatter has given us valid xml
					if (!(formatter is XmlMessageFormatter && !IsXml(result)))						
						break;
				}
				catch 
				{
					result = null;
				}
			}
			if (result == null)
				result = Locale.UserMessages.UnableToDisplayBinaryMessage;
			
			return result;
		}
 public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
 {
     object[] values = new object[4];
     values[0] = new ActiveXMessageFormatter();
     values[1] = new BinaryMessageFormatter();
     values[2] = new XmlMessageFormatter();
     return new TypeConverter.StandardValuesCollection(values);
 }
        public IEnumerable<ReqMessageStatus> GetStatus()
        {
            IList<Message> list1 = qmanager.GetMessagesAndJournal(QueueType.RequestQueue);
            IList<Message> list2 = qmanager.GetMessages(QueueType.FileProcessQueue);

            System.Messaging.XmlMessageFormatter stringFormatter = new System.Messaging.XmlMessageFormatter(new string[] { "System.String" });

            //for (int index = 0; index < messages.Length; index++)
            //{
            //    string test = System.Convert.ToString(messages[index].Priority);
            //    messages[index].Formatter = stringFormatter;
            //    messageTable.Rows.Add(new string[] { messages[index].Label, messages[index].Body.ToString(), "New", messages[index].ArrivedTime.ToShortTimeString() });

            //}

            IEnumerable<ReqMessageStatus> qfileStatus = (from item1 in list1
                                   join item2 in list2
                                   on item1.Label equals item2.Label into g
                                   from o in g.DefaultIfEmpty()
                                   select new ReqMessageStatus { ID = item1.Id, Label = item1.Label,
                                       Body = string.Empty, Status = (o == null ? "New" : "In FileProcess Queue"), DateTime = (o == null ? item1.ArrivedTime.ToShortTimeString() : o.SentTime.ToShortTimeString()) });

            IEnumerable<Message> list3 = qmanager.GetMessages(QueueType.PrintBatchQueue);

            IEnumerable<ReqMessageStatus> qPrintBatchStatus = (from item1 in qfileStatus
                                                         join item2 in list3
                                                          on item1.Label equals item2.Label into g
                                                               from o in g.DefaultIfEmpty()
                                                         select new ReqMessageStatus
                                                         {
                                                             ID = item1.ID,
                                                             Label = item1.Label,
                                                             Body = string.Empty,
                                                             Status = (o == null ? item1.Status : "In PrintBatch Queue"),
                                                             DateTime = (o == null ? item1.DateTime : o.SentTime.ToShortTimeString())
                                                         });

            IList<Message> list4 = qmanager.GetMessages(QueueType.ValidationQueue);

            IEnumerable<ReqMessageStatus> qValQ = (from item1 in qPrintBatchStatus
                                                               join item2 in list4
                                                               on item1.Label equals item2.Label into g
                                                               from o in g.DefaultIfEmpty()
                                                               select new ReqMessageStatus
                                                               {
                                                                   ID = item1.ID,
                                                                   Label = item1.Label,
                                                                   Body = string.Empty,
                                                                   Status = (o == null ? item1.Status : "In Validation Queue"),
                                                                   DateTime = (o == null ? item1.DateTime : o.SentTime.ToShortTimeString())
                                                               });

            IList<Message> list5= qmanager.GetMessages(QueueType.QueueOut);

            IEnumerable<ReqMessageStatus> qOutQ = (from item1 in qValQ
                                                   join item2 in list5
                                                   on item1.Label equals item2.Label into g
                                                   from o in g.DefaultIfEmpty()
                                                   select new ReqMessageStatus
                                                   {
                                                       ID = item1.ID,
                                                       Label = item1.Label,
                                                       Body = string.Empty,
                                                       Status = (o == null ? item1.Status : "In Queue delivery"),
                                                       DateTime = (o == null ? item1.DateTime : o.SentTime.ToShortTimeString())
                                                   });

            IList<Message> list6 = qmanager.GetMessagesAndJournal(QueueType.QueueOut);

            IEnumerable<ReqMessageStatus> qCompletedQ = (from item1 in qOutQ
                                                   join item2 in list6
                                                   on item1.Label equals item2.Label into g
                                                   from o in g.DefaultIfEmpty()
                                                   select new ReqMessageStatus
                                                   {
                                                       ID = item1.ID,
                                                       Label = item1.Label,
                                                       Body = string.Empty,
                                                       Status = (o == null ? item1.Status : "Completed Requested Item"),
                                                       DateTime = (o == null ? item1.DateTime : o.SentTime.ToShortTimeString())
                                                   });
            return qCompletedQ;
        }
Exemple #18
0
		private Message[] PeekMessages(MessageQueue activeQueue, bool blnDynamicConnection, MessageFormat eMessageFormat, System.Type CustomType)
		{
			Message objMessage;
			Message[] arrCurrentMessages = new Message[0];
			Message[] arrCopyOfMessages = null;
			IMessageFormatter objFormatter = null ;
			MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter();
			int intArrayIndex;

			// Message Formatter
			switch (eMessageFormat)
			{
				case MessageFormat.XMLSerialize:
					if (CustomType == null)
					{
						objFormatter = new XmlMessageFormatter();
					}
					else
					{
					// objFormatter = new XmlMessageFormatter(new Type() [CustomType]);
					}

					break;
				case MessageFormat.ActiveXSerialize:
					objFormatter = new ActiveXMessageFormatter();
					break;
				case MessageFormat.BinarySerialize:
					objFormatter = new BinaryMessageFormatter();
					break;
			}

			// Messages in Private Queue
			// Ensure these properties are received (CorrelationID defaults to False)
			objMessagePropertyFilter.SetDefaults();
			objMessagePropertyFilter.CorrelationId = true;
			objMessagePropertyFilter.AppSpecific = true;
			objMessagePropertyFilter.ArrivedTime = true;
			activeQueue.MessageReadPropertyFilter = objMessagePropertyFilter;

			// Message Formatter
			activeQueue.Formatter = objFormatter;

			// Dynamic Connection whilst gathering messages
			if (blnDynamicConnection == true)
			{
				IEnumerator objMessageEnumerator = activeQueue.GetEnumerator();
				intArrayIndex = 0;
				while (objMessageEnumerator.MoveNext())
				{
					objMessage = (Message) objMessageEnumerator.Current;
					if (intArrayIndex > 0)
					{
						arrCopyOfMessages = new Message[intArrayIndex];
						arrCurrentMessages.CopyTo(arrCopyOfMessages,0);
						arrCurrentMessages=arrCopyOfMessages;
					}
					arrCurrentMessages[intArrayIndex] = objMessage;
					intArrayIndex += 1;
				}
			}
			else // Snapshot of messages currently in Queue
			{
				arrCurrentMessages = null ;
				try
				{
					arrCurrentMessages = activeQueue.GetAllMessages();
				}
				catch (System.Messaging.MessageQueueException excM)
				{
					throw excM;
				}
			}

			return arrCurrentMessages;

		}
Exemple #19
0
        private IMessageFormatter SetQueueFormatterAndProperties(MessageQueue activeQueue, eMessageFormat messageFormat, Type customType)
        {
            IMessageFormatter objFormatter = null;
            MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter();

            // Message Formatter
            switch (messageFormat)
            {
                case eMessageFormat.XMLSerialize:
                    if (customType == null)
                    {
                        objFormatter = new XmlMessageFormatter();
                    }
                    else
                    {
                        objFormatter = new XmlMessageFormatter(new Type[] { customType });
                    }

                    break;
                case eMessageFormat.ActiveXSerialize:
                    objFormatter = new ActiveXMessageFormatter();
                    break;
                case eMessageFormat.BinarySerialize:
                    objFormatter = new BinaryMessageFormatter();
                    break;
            }

            // Messages in Private Queue
            // Ensure these properties are received (CorrelationID defaults to False)
            objMessagePropertyFilter.SetDefaults();
            objMessagePropertyFilter.CorrelationId = true;
            objMessagePropertyFilter.AppSpecific = true;
            objMessagePropertyFilter.ArrivedTime = true;
            activeQueue.MessageReadPropertyFilter = objMessagePropertyFilter;

            // Message Formatter
            activeQueue.Formatter = objFormatter;

            return objFormatter;
        }