当前位置: 首页>>代码示例>>C#>>正文


C# Messaging.Message类代码示例

本文整理汇总了C#中System.Messaging.Message的典型用法代码示例。如果您正苦于以下问题:C# Message类的具体用法?C# Message怎么用?C# Message使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Message类属于System.Messaging命名空间,在下文中一共展示了Message类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Send

        public void Send(string Msg)
        {
            string QueuePath = ".\\private$\\SLS_Allcai_Task_Alipay_" + MessageType;

            if (!MessageQueue.Exists(QueuePath))
            {
                return;
            }

            MessageQueue mq = null;

            try
            {
                mq = new MessageQueue(QueuePath);
            }
            catch
            {
                return;
            }

            if (mq == null)
            {
                return;
            }

            System.Messaging.Message m = new System.Messaging.Message();

            m.Body = Msg;
            m.Formatter = new System.Messaging.BinaryMessageFormatter();

            mq.Send(m);
        }
开发者ID:ichari,项目名称:ichari,代码行数:32,代码来源:Message.cs

示例2: Convert

        /// <summary>
        ///     Converts a TransportMessage to an Msmq message.
        ///     Doesn't set the ResponseQueue of the result.
        /// </summary>
        public static Message Convert(TransportMessage message)
        {
            var result = new Message();

            if (message.Body != null)
            {
                result.BodyStream = new MemoryStream(message.Body);
            }

            AssignMsmqNativeCorrelationId(message, result);

            result.Recoverable = message.Recoverable;

            if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            {
                result.TimeToBeReceived = message.TimeToBeReceived;
            }

            using (var stream = new MemoryStream())
            {
                headerSerializer.Serialize(stream, message.Headers.Select(pair => new HeaderInfo
                {
                    Key = pair.Key,
                    Value = pair.Value
                }).ToList());
                result.Extension = stream.ToArray();
            }

            result.AppSpecific = (int) message.MessageIntent;

            return result;
        }
开发者ID:89sos98,项目名称:NServiceBus,代码行数:36,代码来源:MsmqUtilities.cs

示例3: MoveFromSubQueue

 public void MoveFromSubQueue(Type messageType, Message message)
 {
     using (var pendingQueue = GetQueue(messageType))
     {
         pendingQueue.MoveFromSubQueue(message);
     }
 }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:7,代码来源:PendingQueueHelper.cs

示例4: Main

        static void Main()
        {
            Console.WriteLine("Using straight xml serialization and msmq to test interop.");
            Console.WriteLine("To exit, enter 'q'. Press 'Enter' to send a message.");

            string queueName = string.Format("FormatName:DIRECT=OS:{0}\\private$\\OrderServiceInputQueue", Environment.MachineName);
            var label = "<CorrId></CorrId><WinIdName>UDI_MOBILE_2\\Administrator</WinIdName>";

            var q = new MessageQueue(queueName);

            var serializer = new XmlSerializer(typeof(OrderMessage), new[] { typeof(OrderLine) });

            while ((Console.ReadLine().ToLower()) != "q")
            {
                var m1 = new OrderMessage
                             {
                                 PurchaseOrderNumber = Guid.NewGuid().ToString(),
                                 ProvideBy = DateTime.Now,
                                 PartnerId = Guid.NewGuid(),
                                 OrderLines = new[] {new OrderLine {ProductId = Guid.NewGuid(), Quantity = 10F}},
                                 Done = true
                             };

                var toSend = new Message();
                serializer.Serialize(toSend.BodyStream, m1);
                toSend.ResponseQueue = new MessageQueue(string.Format("FormatName:DIRECT=OS:{0}\\private$\\PartnerInputQueue", Environment.MachineName));
                toSend.Label = label;

                q.Send(toSend, MessageQueueTransactionType.Single);
                Console.WriteLine("Sent order {0}", m1.PurchaseOrderNumber);
            }
        }
开发者ID:VirtueMe,项目名称:NNUG.NServiceBusSample,代码行数:32,代码来源:Program.cs

示例5: Send2WithLabelWithTransaction

		public void Send2WithLabelWithTransaction ()
		{
			String label1 = "label1";
			String label2 = "label2";
			Message sent1 = new Message ("Message 1", new BinaryMessageFormatter ());
			Message sent2 = new Message ("Message 2", new BinaryMessageFormatter ());
			MessageQueue mq = MQUtil.GetQueue (MQUtil.CreateQueueName (), true);
			mq.MessageReadPropertyFilter.SetAll ();
			Assert.IsTrue(mq.Transactional, "Message Queue should be transactional");
			using (MessageQueueTransaction tx = new MessageQueueTransaction ()) {
				tx.Begin ();
				
				mq.Send (sent1, label1, tx);
				mq.Send (sent2, label2, tx);
				
				tx.Commit ();
				
				Message received1 = mq.Receive ();
				Assert.IsNotNull (received1.TransactionId, "TransactionId not set");
				Message received2 = mq.Receive ();
				Assert.IsNotNull (received2.TransactionId, "TransactionId not set");
				
				Assert.AreEqual (received1.TransactionId, received2.TransactionId, "Messages have differing TransactionIds");
				Assert.IsTrue (received1.TransactionId.Length > 1);
				Assert.AreEqual (sent1.Body, received1.Body, "Message 1 not delivered correctly");
				Assert.AreEqual (sent2.Body, received2.Body, "Message 2 not delivered correctly");
				Assert.AreEqual (label1, received1.Label, "Label 1 not passed correctly");
				Assert.AreEqual (label2, received2.Label, "Label 2 not passed correctly");
			}
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:30,代码来源:TransactionMessagingTest.cs

示例6: Loop

        private void Loop()
        {
            //q2.Purge();
            var start = Stopwatch.StartNew();
            while (true)
            {
                batchCountdownEvent.Reset();
                var sp = Stopwatch.StartNew();

                Parallel.For(0, batchSize, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, i =>
                {
                    var current = Interlocked.Increment(ref total);
                    var msg = new Message
                    {
                        Recoverable = true,
                        Label = current.ToString(),
                        Body = body,
                        Extension = head,
                    };
                    writeQueue.Send(msg, MessageQueueTransactionType.Single);

                });
                batchCountdownEvent.Wait();
                var elapsed = sp.Elapsed.TotalSeconds;
                Console.WriteLine("{0:N0}msg/s ~{1:N0} +{2:N0} {3}s", batchSize / elapsed, total / start.Elapsed.TotalSeconds, total, start.Elapsed.TotalSeconds);
            }
        }
开发者ID:ramonsmits,项目名称:MsmqNativeStressTest,代码行数:27,代码来源:Program.cs

示例7: ToMessage

 /// <summary>
 /// Convert the given object to a Message.
 /// </summary>
 /// <param name="obj">The object to send.</param>
 /// <returns>Message to send</returns>
 public Message ToMessage(object obj)
 {
     Message m = new Message();
     m.Body = obj;
     m.Formatter = messageFormatter;
     return m;
 }
开发者ID:Binodesk,项目名称:spring-net,代码行数:12,代码来源:ActiveXMessageConverter.cs

示例8: Read

 /// <summary>
 /// When implemented in a class, reads the contents from the given message and creates an object that contains data from the message.
 /// </summary>
 /// <returns>
 /// The deserialized message.
 /// </returns>
 /// <param name="message">The <see cref="T:System.Messaging.Message"/> to deserialize. </param>
 public object Read(Message message)
 {
     using (var streamReader = new StreamReader(message.BodyStream, _encoding))
     {
         return streamReader.ReadToEnd();
     }
 }
开发者ID:petxo,项目名称:HermEsb,代码行数:14,代码来源:TextFormatter.cs

示例9: QueueMessagingTest

 public void QueueMessagingTest()
 {
     //Задаем путь тестовой очереди
     string testQueuePath = @".\QueueAccessTest";
     //Пытаемся создать новую очередь
     if (!MessageQueue.Exists(testQueuePath))
         MessageQueue.Create(testQueuePath);
     System.Threading.Thread.Sleep(20000); // Время, необходимое для создания очереди
     //Тест пройден, если очередь успешно создалась
     Assert.IsTrue(MessageQueue.Exists(testQueuePath));
     //Создаем представителя нашего сервиса по обработке ошибок Service.ExeptionService
     ExсeptionService serviceTest = new ExсeptionService();
     //Создаем новое сообщение с наивысшим приоритетом
     Message mes = new Message
     {
         Label = "QueueMessagingTest_Message_Label",
         Body = "QueueMessagingTest_Message_Body",
         Priority = MessagePriority.Highest
     };
     //Посылаем сообщение в очередь testQueuePath
     serviceTest.SendToQueue(mes, testQueuePath);
     //Забираем сообщение из очереди и если оно совпадает с тем, которое мы отправляли, то тест пройден
     Assert.AreEqual(new MessageQueue(testQueuePath).Receive().Label, mes.Label);
     //Пытаемся удалить ранее созданную очередь
     MessageQueue.Delete(testQueuePath);
     System.Threading.Thread.Sleep(5000); // Время, необходимое для удаления очереди
     //Если очереди больше нет, то тест пройден
     Assert.IsTrue(!MessageQueue.Exists(testQueuePath));
 }
开发者ID:TitovSP,项目名称:ExceptionService,代码行数:29,代码来源:QueueTest.cs

示例10: Send

        public void Send(Object message)
        {
            // Open the queue.
            using (var queue = new MessageQueue(_queueName.GetQueueFormatName()))
            {
                // Set the formatter to JSON.
                queue.Formatter = new MsmqMessageFormatter();

                // Since we're using a transactional queue, make a transaction.
                using (MessageQueueTransaction mqt = new MessageQueueTransaction())
                {
                    mqt.Begin();

                    // Create a simple text message.
                    Message myMessage = new Message(message, new MsmqMessageFormatter());
                    myMessage.Label = message.GetType().FullName;
                    myMessage.ResponseQueue = new MessageQueue(_queueName.GetQueueFormatName());

                    // Send the message.
                    queue.Send(myMessage, mqt);

                    mqt.Commit();
                }
            }
        }
开发者ID:paralect,项目名称:Paralect.ServiceBus,代码行数:25,代码来源:MsmqQueue.cs

示例11: MoveToDiscardedQueue

 /// <summary>
 /// Moves the <paramref name="message"/> to discarded queue.
 /// </summary>
 /// <param name="queue">The queue.</param>
 /// <param name="message">The message.</param>
 public void MoveToDiscardedQueue(MessageQueue queue, Message message)
 {
     using (var destinationQueue = new MessageQueue(GetDiscardedQueuePath(),QueueAccessMode.Send))
     {
         destinationQueue.Send(queue.ReceiveByLookupId(message.LookupId), destinationQueue.GetTransactionType());
     }
 }
开发者ID:brumschlag,项目名称:rhino-tools,代码行数:12,代码来源:FlatQueueStrategy.cs

示例12: GetPriority

 /// <summary>
 /// 生成带有级别的Message
 /// </summary>
 /// <param name="p_strPriority"></param>
 /// <returns></returns>
 public Message GetPriority(string p_strPriority)
 {
     Message queueMessage = new System.Messaging.Message();
     switch (p_strPriority)
     {
         case "AboveNormal":
             queueMessage.Priority = MessagePriority.AboveNormal;
             break;
         case "High":
             queueMessage.Priority = MessagePriority.High;
             break;
         case "Highest":
             queueMessage.Priority = MessagePriority.Highest;
             break;
         case "Low":
             queueMessage.Priority = MessagePriority.Low;
             break;
         case "Lowest":
             queueMessage.Priority = MessagePriority.Lowest;
             break;
         case "Normal":
             queueMessage.Priority = MessagePriority.Normal;
             break;
         case "VeryHigh":
             queueMessage.Priority = MessagePriority.VeryHigh;
             break;
         case "VeryLow":
             queueMessage.Priority = MessagePriority.VeryLow;
             break;
         default:
             queueMessage.Priority = MessagePriority.Normal;
             break;
     }
     return queueMessage;
 }
开发者ID:huzuohuyou,项目名称:DataUpload-EMR,代码行数:40,代码来源:MSSQ.cs

示例13: GetMSMQMessage

        internal static Message GetMSMQMessage(this PipeMessageEnvelope pipeMessage)
        {
            Message MSMQMessage = new Message();

            if (pipeMessage.CorrelationId != null)
            {
                MSMQMessage.CorrelationId = pipeMessage.CorrelationId;
            }
            if (pipeMessage.Label != null)
            {
                MSMQMessage.Label = pipeMessage.Label;
            }
            MSMQMessage.Body = pipeMessage.Body;

            MessageFlags appSpecific = MessageFlags.None;
            if (pipeMessage.IsPostback)
            {
                appSpecific |= MessageFlags.Postback;
            }
            MSMQMessage.AppSpecific = (int)appSpecific;

            // Debugging
            //long messageSize = Utils.BinSizeOf(pipeMessage.Body);
            //if (messageSize > 100000)
            //{
            //    Tracer.Trace(
            //        "Message label = {0}, Message size = {1}", pipeMessage.Label, Utils.BinSizeOf(pipeMessage.Body));
            //}

            return MSMQMessage;
        }
开发者ID:Rajeshbharathi,项目名称:CGN.Paralegal,代码行数:31,代码来源:MSMQPipeMessage.cs

示例14: SendWithPathNotSet

		public void SendWithPathNotSet ()
		{
			MessageQueue q = new MessageQueue ();
			Message m = new Message ("foobar", new BinaryMessageFormatter ());
			
			q.Send (m);
		}
开发者ID:REALTOBIZ,项目名称:mono,代码行数:7,代码来源:FailuresTest.cs

示例15: HandlePeekedMessage

        public bool HandlePeekedMessage(IMsmqTransport transport, OpenedQueue queue, Message message)
        {
            bool doesNotHaveMessageId = message.Extension.Length < 16;
            if(doesNotHaveMessageId)
            {
                const string errorMessage = "Message does not have Extension set to at least 16 bytes, which will be used as the message id. Probably not a bus message.";
                transport.RaiseMessageSerializationException(queue,message,errorMessage);
                MoveToErrorQueue(queue, message, errorMessage);
                return true;
            }

            var id = message.GetMessageId();
            ErrorCounter errorCounter = null;

            failureCounts.Read(reader => reader.TryGetValue(id, out errorCounter));

            if (errorCounter == null)
                return false;

            if (errorCounter.FailureCount < numberOfRetries)
                return false;

            failureCounts.Write(writer =>
            {
                writer.Remove(id);
                MoveToErrorQueue(queue, message, errorCounter.ExceptionText);
            });

            return true;
        }
开发者ID:BiYiTuan,项目名称:rhino-esb,代码行数:30,代码来源:ErrorAction.cs


注:本文中的System.Messaging.Message类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。