by david
1. August 2010 17:25
The class below is my first attempt at being able to read the ebMS 3.0 headers in C#. It deserialises the xml into the objects I have created from the xsd files (see previous post). So you'll need the auto-generated C# classes to use this code. I'll post an example useage in another blog. So far I have tested it on all the examples extracted from the ebMS core spec and it seems to load the data OK.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.ServiceModel.Channels;
namespace ebMS3.Soap
{
public class MessageDecoder
{
private string _xmlnamespace = null;
public Message Message { get; private set; }
public MessageDecoder(Stream stream)
{
_xmlnamespace = GetXmlNamespace(typeof(Messaging));
Message = GetMessage(stream);
}
public MessageDecoder(byte[] rawbytes)
{
_xmlnamespace = GetXmlNamespace(typeof(Messaging));
MemoryStream ms = new MemoryStream(rawbytes);
Message = GetMessage(ms);
}
private string GetXmlNamespace(Type t)
{
XmlTypeAttribute[] attrs = (XmlTypeAttribute[])
t.GetCustomAttributes(typeof(XmlTypeAttribute), true);
if (attrs != null && attrs.Length > 0)
return attrs[0].Namespace;
else
return "";
}
public UserMessage[] GetHeaderUserMessages()
{
return GetHeaderMessages<UserMessage>();
}
public SignalMessage[] GetHeaderSignalMessages()
{
return GetHeaderMessages<SignalMessage>();
}
private T[] GetHeaderMessages<T>() where T : class
{
if (Message == null || Message.Headers == null) return default(T[]);
List<T> retval = new List<T>();
XmlSerializer xs = new XmlSerializer(typeof(T), _xmlnamespace);
XmlNode[] hdrs =
Message.Headers.GetHeader<XmlNode[]>("Messaging", _xmlnamespace);
foreach (XmlNode xn in hdrs)
{
if (xn.Name.EndsWith(typeof(T).Name))
{
T um = xs.Deserialize(new XmlNodeReader(xn)) as T;
if (um != null) retval.Add(um);
}
}
return retval.ToArray();
}
private Message GetMessage(Stream stream)
{
MessageVersion soap11 = MessageVersion.Soap11WSAddressingAugust2004;
XmlReader xreader = XmlReader.Create(stream);
return Message.CreateMessage(xreader, 5120, soap11); // 5Kb in headers
}
}
}