• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Messaging.Message类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Adding_then_removing_will_result_in_no_subscriptions

        public void Adding_then_removing_will_result_in_no_subscriptions()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel());
            var msg = new Message();
            serializer.Serialize(new object[]{new AddSubscription
            {
                Endpoint = TransactionalTestQueueUri.ToString(),
                Type = typeof(TestMessage).FullName,
            }}, msg.BodyStream);

            queue.Send(msg, MessageQueueTransactionType.None);
            msg = queue.Peek();
            queue.MoveToSubQueue("subscriptions",msg);

            var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(),
                serializer,
                TestQueueUri,
                new SubQueueStrategy());
            subscriptionStorage.Initialize();
            subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, TransactionalTestQueueUri.ToString());

            var uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage));

            Assert.Equal(0, uris.Count());
        }
开发者ID:brumschlag,项目名称:rhino-tools,代码行数:26,代码来源:MsmqSubscriptionTests.cs


示例17: Adding_then_removing_will_result_in_no_subscriptions

        public void Adding_then_removing_will_result_in_no_subscriptions()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(),
                                                      new CastleServiceLocator(new WindsorContainer()));
            var msg = new Message();
            serializer.Serialize(new object[]{new AddSubscription
                                                  {
                                                      Endpoint = transactionalTestQueueEndpoint,
                                                      Type = typeof(TestMessage).FullName,
                                                  }}, msg.BodyStream);

            msg.Extension = Guid.NewGuid().ToByteArray();
            queue.OpenSiblngQueue(SubQueue.Subscriptions, QueueAccessMode.Send).Send(msg);

            var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(),
                                                                  serializer,
                                                                  testQueueEndPoint.Uri,
                                                                  new EndpointRouter(),
                                                                  new FlatQueueStrategy(new EndpointRouter(),testQueueEndPoint.Uri));
            subscriptionStorage.Initialize();
            subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, transactionalTestQueueEndpoint.Uri.ToString());

            var uris = subscriptionStorage
                .GetSubscriptionsFor(typeof(TestMessage));

            Assert.Equal(0, uris.Count());
        }
开发者ID:BiYiTuan,项目名称:rhino-esb,代码行数:27,代码来源:MsmqFlatQueueSubscriptionTests.cs


示例18: Can_read_subscription_from_queue

        public void Can_read_subscription_from_queue()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel());

            var msg = new Message();
            serializer.Serialize(new object[]{new AddSubscription
            {
                Endpoint = TransactionalTestQueueUri.ToString(),
                Type = typeof(TestMessage).FullName,
            }}, msg.BodyStream);

            queue.Send(msg, MessageQueueTransactionType.None);
            msg = queue.Peek();
            queue.MoveToSubQueue("subscriptions", msg);

            var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(),
                serializer,
                TestQueueUri,
                new SubQueueStrategy());
            subscriptionStorage.Initialize();

            var uri = subscriptionStorage
                .GetSubscriptionsFor(typeof(TestMessage))
                .Single();

            Assert.Equal(TransactionalTestQueueUri, uri);
        }
开发者ID:brumschlag,项目名称:rhino-tools,代码行数:27,代码来源:MsmqSubscriptionTests.cs


示例19: Append

		override protected void Append(LoggingEvent loggingEvent) 
		{
			if (m_queue == null)
			{
				if (MessageQueue.Exists(m_queueName))
				{
					m_queue = new MessageQueue(m_queueName);
				}
				else
				{
					ErrorHandler.Error("Queue ["+m_queueName+"] not found");
				}
			}

			if (m_queue != null)
			{
				Message message = new Message();

				message.Label = RenderLabel(loggingEvent);

				using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
				{
					System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, new System.Text.UTF8Encoding(false, true));
					base.RenderLoggingEvent(writer, loggingEvent);
					writer.Flush();
					stream.Position = 0;
					message.BodyStream = stream;

					m_queue.Send(message);
				}
			}
		}
开发者ID:ittray,项目名称:LocalDemo,代码行数:32,代码来源:MsmqAppender.cs


示例20: SendToAllQueues

        private bool SendToAllQueues(Message message)
        {
            var success = true;
            for (var i = 0; i < _sendQueues.Count; i++)
            {
                // if a sender queue is not available at the moment due to a previous error, don't send the message
                if (!_sendQueuesAvailable[i])
                    continue;

                try
                {
                    _sendQueues[i].Send(message);
                }
                catch (MessageQueueException mex)
                {
                    Logger.WriteException(mex);
                    _sendQueuesAvailable[i] = false;    // indicate that the queue is out of order
                    success = false;
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    _sendQueuesAvailable[i] = false;    // indicate that the queue is out of order
                    success = false;
                }
            }
            return success;
        }
开发者ID:maxpavlov,项目名称:FlexNet,代码行数:28,代码来源:MsmqChannel.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Messaging.MessageQueue类代码示例发布时间:2022-05-26
下一篇:
C# Media.SoundPlayer类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap