开发者

How to receive messages formatted by The BinaryLogFormatter

I'm using the MS Patterns and Practices Enterprise Library MsmqTraceListener to log entries to a private queue using the BinaryLogFormatter.

I 开发者_StackOverflow中文版would now like to read those log entries off the queue. I need to set the Formatter property of the MessageQueue before I can look at the message.Body. I expected to be able to use the BinaryLogFormatter of the EnterpriseLibrary, but I can't cast that as an IMessageFormatter. (InvalidCastException)

What am I missing?


Have you looked at the Enterprise Library Distributor Service? It might do what you want out of the box. A short guide to implement: Enterprise Library 5 Logging using MSMQ.

If you don't want to use the full Distributor Service look at the source code to see how they access the queue. It looks like they are deserializing using the BinaryLogFormatter directly. From MsmqLogDistributor.cs:

using (MessageQueue msmq = CreateMessageQueue())
{
    Message message = msmq.Peek();

    string serializedEntry = message.Body.ToString();

    LogEntry logEntry = null;
    try
    {
        logEntry = BinaryLogFormatter.Deserialize(serializedEntry);
    }
    catch (FormatException formatException)
    {
        ...
    }
    catch (SerializationException serializationException)
    {
        ...
    }

    if (logEntry != null)
    {
        logWriter.Write(logEntry);
    }

    message = msmq.Receive();

    if (this.StopReceiving)
    {
        this.isCompleted = true;
        return;
    }
}


One thing to make sure to do is to include the following when setting up your messageQueue. If not the deserilizing will not work.

((XmlMessageFormatter)messageQueue.Formatter).TargetTypeNames = new string[] { "System.String" };

One waisted afternoon trying figure this one out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜