Monday, August 22, 2011

Formatting to a String in Everest


I've never really liked strings for transporting data as they're memory pigs and introduce a huge performance penalty, however formatting to a string can be useful if you're debugging an application or just want to see the results of formatting. So I figured I'd do a short-ish post today and illustrate how this is done.

First, we'll need an instance, I've created a small sample message from the UV NE2008 assembly but it can be any instance that is IGraphable.

MCCI_IN000000UV01 instance = new MCCI_IN000000UV01(
    Guid.NewGuid(),
    DateTime.Now,
    MCCI_IN000000UV01.GetInteractionId(),
    ProcessingID.Training,
    "I",
    AcknowledgementCondition.Never);

Next, we'll define the formatter instance that is going to take this RMIM structure and render it using an ITS. I'm using XML ITS 1 with data types R1.

var formatter = new MARC.Everest.Formatters.XML.ITS1.Formatter();
formatter.ValidateConformance = false;
formatter.GraphAides.Add(typeof(MARC.Everest.Formatters.XML.ITS1.Formatter));


I've disabled conformance checking as I assume since we're formatting to a string, we're just fiddling with Everest. I'd recommend setting ValidateConformance to true if you're seriously trying to create a conformant message. Next, we create a StringWriter class and attach an XmlWriter with indentation turned on (makes it easier to read):

StringWriter sw = new StringWriter();
XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings()
      { Indent = true }
);


We could just format the instance as is, however it is always recommended you use an XmlStateWriter when dealing with Everest, so that what this next line does:

XmlStateWriter xsw = new XmlStateWriter(xw);

Next, we just format our instance and flush (or close) the XmlWriter.

try
{
   formatter.Graph(xsw, instance);
}
finally
{
   xw.Close();
   sw.Flush();
}

Notice I'm using the Graph() method, this is a new construct introduced in Everest RC3. If you're using RC2 or prior you can call GraphObject() instead. Finally, you can get your string by calling the ToString() method on the string writer. I've decided to print out to the console for demonstrative purposes:

Console.WriteLine(sw.ToString());
Console.ReadKey();

And there you have it! An XML Instance as a string. I wouldn't recommend using strings too heavily in your production code, like I said they're horrible from a memory consumption and performance POV. Streams and Writers/Readers are much faster and flexible.

Cheers

-Justin

No comments:

Post a Comment