Thursday, September 22, 2011

How to Serialize eConnect XML - Properly

I'm posting this for my own reference because I can never remember the full syntax and I regularly have to look it up.

I think I've seen at least 3 or 4 different code samples showing how to serialize eConnect XML in .NET.

One version, which I think is actually based on sample eConnect code that Microsoft provided years ago, writes the XML out to a file on the hard drive, then reads it back into memory.  The first time I saw this my eyes rolled in disbelief.  Clearly that is a terrible idea and is completely unnecessary.

The other versions, which I have used over the last few years, used in-memory techniques to serialize the XML using a combinations of a MemoryStream, XmlTextReader, and StringBuilder.  Although these worked fine, the process to use an XmlTextReader and StringBuilder never seemed ideal.

The best example I've seen so far is the one that Brian Prince posted on the MBS Guru blog back in December 2010.  The XML Document approach is simple and very clean, and it is the technique I've been using ever since he wrote about it.

Here is Brian's approach:

eConnectType eConnect = new eConnectType();
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xmlSerializer = new XmlSerializer(eConnect.GetType());
xmlSerializer.Serialize(memoryStream, eConnect);
memoryStream.Position = 0;

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(memoryStream);
memoryStream.Close();

econnectMethods.eConnect_EntryPoint(
connectionString, EnumTypes.ConnectionStringType.SqlClient, 
xmlDocument.OuterXml, EnumTypes.SchemaValidationType.None,  
string.Empty);


Steve Endow is a Dynamics GP Certified Trainer and Dynamics GP Certified IT Professional in Los Angeles.  He is also the owner of Precipio Services, which provides Dynamics GP integrations, customizations, and automation solutions.

http://www.precipioservices.com

No comments:

Post a Comment