本文整理汇总了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);
}
示例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;
}
示例3: MoveFromSubQueue
public void MoveFromSubQueue(Type messageType, Message message)
{
using (var pendingQueue = GetQueue(messageType))
{
pendingQueue.MoveFromSubQueue(message);
}
}
示例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);
}
}
示例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");
}
}
示例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);
}
}
示例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;
}
示例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();
}
}
示例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));
}
示例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();
}
}
}
示例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());
}
}
示例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;
}
示例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;
}
示例14: SendWithPathNotSet
public void SendWithPathNotSet ()
{
MessageQueue q = new MessageQueue ();
Message m = new Message ("foobar", new BinaryMessageFormatter ());
q.Send (m);
}
示例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;
}