Running demo.cs
This section describes the requirements and procedure for running the demonstration application, demo.cs.
How to Run the Demonstration
To start the demo.cs demonstration:
Example 1
Example 1 converts a comma-separated values (CSV) file, one.csv, to an XML file, one.xml, using the CSV XML Converter. The conversion parameter for the new Converter object is specified as a converter: URL that indicates which XML Converter to use to convert the input file to the output file. Only two XML Converter property settings are expressed; default values are used for all properties unless you specify them in the converter: URL.
try { Source converterSource = new UriSource(exampleDir + "one.csv"); Result converterResult = new UriResult(exampleDir + "one.xml"); Converter toXml = factory.CreateConvertToXml("converter:CSV:sep=, :first=yes"); toXml.Convert(converterSource, converterResult); Console.WriteLine("test 1 finished: one.csv -> one.xml"); } catch(Exception e) { Console.WriteLine("test 1 failed with exception: " + e); }Both input and output streams are opened and closed by the Converter object.
Example 2
Example 2 is similar to Example 1, but instead of converting a non-XML file to XML, it does the opposite. It also shows how to use the URI resolver to create both the input stream and output stream:
try { ConverterResolver resolver = factory.CreateResolver(); Uri inputUri = resolver.ResolveUri(uriBase, "two.xml"); using (Stream inStream = (Stream) resolver.GetEntity(inputUri, null, typeof(Stream))) { Source converterSource = new InputStreamSource(inStream); using (Stream outStream = File.OpenWrite(exampleDir + "two.csv")) { Result converterResult = new OutputStreamResult(outStream); Converter fromXml = factory.CreateConvertFromXml ("converter:CSV:sep=,:first=yes"); fromXml.Convert(converterSource, converterResult); } } Console.WriteLine("test 2 finished: two.xml -> two.csv"); } catch(Exception e) { Console.WriteLine("test 2 failed with exception: " + e); }In this example, we need to close the input and output streams since we, and not the Converter object, opened them.
Example 3
Example 3 uses a custom XML conversion,
three.conv
, built using Stylus Studio XML Enterprise Suite, to convert a fixed-width file, three.txt, to XML. Here, we create our own Streams – because we are converting a local text file, there is no need to use the URI Resolver.try { using (Stream inStream = File.OpenRead(exampleDir + "three.txt") ) { using (Stream outStream = File.OpenWrite(exampleDir + "three.xml") ){ Source converterSource = new InputStreamSource(inStream); Result converterResult = new OutputStreamResult(outStream); String converter = "converter:" + exampleDir + "three.conv"; Converter toXml = factory.CreateConvertToXml(converter); toXml.Convert(converterSource, converterResult); } } Console.WriteLine("test 3 finished: three.txt -> three.xml"); } catch(Exception e) { Console.WriteLine("test 3 failed with exception: " + e); }Example 4
Examples 1, 2, and 3 performed simple conversion of one file type to another – some type of converter (either a DataDirect XML Converter or a user-defined custom XML conversion) was given an input and converted it to another format.
In Example 4, the Converter converterResult will make the Converter output available as an XmlReader. The XSLT Transformer will read the data from the XmlReader. The Converter will not actually process the input data until the XSLT Transformer starts to read from the XmlReader. The Converter will then begin converting the input data, as needed. If the transformer terminates early, without reading all the data, the Converter will also terminate without converting all the input data.
Here is the code for Example 4:
try { using(Stream inputStream = File.OpenRead(exampleDir + "one.csv"){ InputStreamSource converterSource = new InputStreamSource(inputStream); XmlReaderResult converterResult = new XmlReaderResult(); Converter toXml = factory.CreateConvertToXml("converter:///CSV:sep=, :first=yes"); toXml.Convert(converterSource, converterResult); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(exampleDir + "Copier.xslt"); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; XmlWriter writer = XmlWriter.Create(exampleDir + "four.xml", settings); xslt.Transform(converterResult.XmlReader, writer); converterResult.XmlReader.Close(); } Console.WriteLine("test 4 finished: one.csv -> four.xml"); } catch(Exception e) { Console.WriteLine("test 4 failed with exception: " + e); }XmlWriter writer is an XML document, four.xml. In this example, we used a copy/identity transformation, but you could specify any XSLT transformation here to perform any processing on the intermediate result you required.
Example 5
In Example 5, output from an XSLT transformation is sent to a converter, which takes the XML that is written to it (as a an XmlWriter) and converts it to CSV. This process is summarized in the following illustration.
Here is the code for Example 5:
try { UriResult converterResult = new UriResult(exampleDir + "five.csv"); XmlWriterSource converterSource = new XmlWriterSource(); ConvertFromXml fromXml =factory.CreateConvertFromXml("converter:CSV: sep=,:first=yes"); XmlWriter xmlWriter = fromXml.GetXmlWriter(converterResult); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(exampleDir + "Copier.xslt"); xslt.Transform(exampleDir + "two.xml", xmlWriter); Console.WriteLine("test 5 finished: two.xml -> five.csv"); } catch(Exception e) { Console.WriteLine("test 5 failed with exception: " + e); }To convert the transformation’s output to CSV, we have used an instance of the ConvertFromXML object. This object uses the XML Converters CSV converter.
Example 6
Example 6 shows the use of an EDI XML Converter (converter: EDI) to convert a file in the X12 dialect (831.x12) to XML (831.x12.xml), and then back to EDI (831.x12.xml.fromxml).
try{ Source converterSource = new UriSource(exampleDir + "831.x12"); Result converterResult = new UriResult(exampleDir + "831.x12.xml"); Converter toXml = factory.CreateConvertToXml("converter:EDI"); toXml.Convert(converterSource, converterResult); Console.WriteLine("test6 toXML finished: 831.x12 -> 831.x12.xml"); } catch (Exception e) { Console.WriteLine("test 6 toXML failed with exception: " + e); } try{ Source converterSource = new UriSource(exampleDir + "831.x12.xml"); Result converterResult = new UriResult(exampleDir + "831.x12.fromxml"); Converter fromXml = factory.CreateConvertFromXml("converter:EDI"); fromXml.Convert(converterSource, converterResult); Console.WriteLine("test6 fromXML finished: 831.x12.xml -> 831.x12.fromxml"); } catch (Exception e) { Console.WriteLine("test 6 fromXML failed with exception: " + e); }Example 7
This example shows how to use a Standard Exchange Format (SEF) extension file to convert EDI messages using a proprietary format. The SEF file used in this example adds 99 as a permitted code value in the 353 element of segment BGN in transaction set 831.
The URL of the SEF file is specified in the
user=
parameter of theconverter:
URL. It is also possible to specify the SEF file name as a relative pathname. If XML Converters has been installed in a directory PRODUCT_PATH, and the EDIconverter:
URL containsuser=relative.sef
, then the SEF file will be found atPRODUCT_PATH/lib/CustomEDI/relative.sef
.try{ XmlUrlResolver resolver = new XmlUrlResolver(); Uri sefUri = resolver.ResolveUri(uriBase, "proprietary.sef"); String ediUri = "converter:EDI:user=" + sefUri; Source converterSource = new UriSource(exampleDir + "proprietary.x12"); Result converterResult = new UriResult("proprietary.xml"); Converter toXml = factory.CreateConvertToXml(ediUri); toXml.Convert(converterSource, converterResult); Console.WriteLine("test 7 toXML finished: proprietary.x12 -> proprietary.xml"); } catch (Exception e) { Console.WriteLine("test 7 toXML failed with exception: " + e); }Example 8
This example shows how to register a
ConverterListener
, which is notified of warnings, errors, and fatal errors that occur during conversion. Also included in this example is a simple implementation of the threeConverterListener
methods (warning
,error
, andfatalError
). This implementation appears at the end of demo.cs.This example uses the proprietary data file (proprietary.xml) as Example 7, but it omits the proprietary.sef extension file. This will result in a error that is reported to the
ConverterListener
implementation.Sample Application
try{ Source converterSource = new UriSource(exampleDir + "proprietary.x12"); Result converterResult = new UriResult("proprietary.xml"); Converter toXml = factory.CreateConvertToXml("converter:EDI"); ConverterListener listener = new DemoListener(); toXml.Configuration.ConverterListener = listener; toXml.Convert(converterSource, converterResult); Console.WriteLine("test 8 toXML finished: proprietary.x12 -> proprietary.xml"); } catch (Exception e) { Console.WriteLine("test 8 toXML failed with exception: " + e); }ConverterListener Implementation in demo.cs
public class DemoListener : ConverterListener { public void Warning(ConverterException e) { Console.WriteLine("Converter warning notification: " + e); return; } public void Error(ConverterException e) { Console.WriteLine("Converter error notification: " + e); return; } public void FatalError(ConverterException e) { Console.WriteLine("Converter fatal error notification: " + e); return; } }Error Listener Output
After running demo.cs, the program generates the following output; note the error encountered after completing Example 7.
test 1 finished: one.csv -> one.xml test 2 finished: two.xml -> two.csv test 3 finished: three.txt -> three.xml test 4 finished: one.csv -> four.xml test 5 finished: two.xml -> five.csv test 6 toXML finished: 831.x12 -> 831.x12.xml test 6 fromXML finished: 831.x12.xml -> 831.x12.fromxml test 7 toXML finished: proprietary.x12 -> proprietary.xml Starting test 8. The ConverterListener will print a warning and an error. Converter warning notification: com.ddtek.xmlconverter.adapter.edi.EDIConverterException: [DDEW0063] WARNING Starting with 00402, the format of ISA11 changed. Adjusting 'U' to '^'. In X12 prior to 004020, ISA11 was element I10 and had to have the value "U". But from 004020 onwards, it is element I65 and is the repetition character. This fix has been automatically made to the data stream. Converter error notification: com.ddtek.xmlconverter.adapter.edi.EDIConverterException: [DDEE0008] ERROR Value 99 not in codelist 353. Dialect: X12 Version: syntax=00403/004030;message=00403/004030;agency=004030;table= 004030 Message: 831 Segment: BGN (line 4) Position: BGN01 Element: 353 (s) Transaction Set Purpose Code Value: "99" Native error: 7, in table: 723 The value for an element in the data stream cannot be found in the codelist associated with the element. Turning off codelist validation with "tbl=no" will eliminate the error. test 8 toXML finished: proprietary.x12 -> error.xml test 9 schema generator finished: one.csv -> one.xsd test 10 schema generator finished: --> edi.xsd test 11 finished: one.xml + one.csv -> eleven.xmlExample 9
This example shows how to use the DataDirect XML Converters™ API to create an XML Schema based on a comma-separated values (CSV) file. Note that an instance document is required in order to generate XML Schema for CSV and other file types. See Instance Documents for more information.
The XML Schema generator is used very much like an XML Converter – the program provides the sample input file as a
Source
object and the generated XML Schema is written to theResult
object.See XML Schema Generation for more information on this topic.
try{ Source sampleSource = new UriSource(exampleDir + "one.csv"); Result xsdResult = new UriResult("one.xsd"); SchemaGenerator generator = factory.CreateSchemaGenerator("converter:///CSV:sep=,:first=yes"); generator.GetSchema(sampleSource, xsdResult); Console.WriteLine("test 9 schema generator finished: one.csv -> one.xsd"); } catch (Exception e) { Console.WriteLine("test 9 schema generator failed with exception: " + e); }Example 10
This example shows how to use the DataDirect XML Converters™ API to create an XML Schema based on an EDI file. The generated XML Schema depends on the EDI dialect, version, and message being converted, but not on the actual data in the EDI message. This information can be provided
- Using a sample EDI input (as shown in Example 9). See Instance Documents for more information.
- As part of the
converter:
URL, as demonstrated in this example. Also, see URI Parameters That Affect XML Schema for more information.See XML Schema Generation for more information on this topic.
try{ Result xsdResult = new UriResult("edi.xsd"); String uri = "EDI:dialect=EDIFACT:version=D06B:message=INVOIC:tbl=no"; SchemaGenerator generator = factory.CreateSchemaGenerator(uri); generator.GetSchema(xsdResult); Console.WriteLine("test 10 schema generator finished: --> edi.xsd"); } catch (Exception e) { Console.WriteLine("test 10 schema generator failed with exception: " + e); }Example 11
This example shows how to use a document URI resolver (a .NET XmlResolver) to enable the XPath document() function in an XSLTstylesheet object to take a converter: URI as its argument.
The first statement uses CreateResolver() to get the XML Converters URI resolver, which is able to resolve converter: URIs for the document() function.
Next, the example creates a converter: URI like this:
converter:///CSV:sep=,:first=yes?file:///c:/examples/one.csv
The XML Converter will read its input from "one.csv", convert it to XML, return its document node to the document() function.
Previous examples used a converter: URI like this:
converter:///CSV:sep=,:first=yes
and the name of the input file was provided elsewhere. When using the document() function, you must provide the converter: URI and the input file URI all at once,separating them with a '?' character as shown in this example.
Here is the complete code for Example 11:
try { XmlResolver resolver = factory.CreateResolver(); String converterUrl = "converter:///CSV:sep=,:first=yes?" + exampleDir + "one.csv"; String xsltString = @"<xsl:stylesheet version='1.0' xmlns:xsl= 'http://www.w3.org/1999/XSL/Transform'> <xsl:output method='xml' indent='yes'/> <xsl:template match='/'> <root> <xsl:copy-of select='.'/> <xsl:copy-of select='document(""PUT THE URL HERE"")'/> </root> </xsl:template> </xsl:stylesheet>"; xsltString = xsltString.Replace("PUT THE URL HERE", converterUrl); XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(true, false); xslt.Load(XmlReader.Create(new StringReader(xsltString)), settings, null); xslt.Transform( XmlReader.Create(exampleDir + "one.xml"), new XsltArgumentList(), XmlWriter.Create(exampleDir + "eleven.xml"), resolver); Console.WriteLine("test 11 finished: one.xml + one.csv -> eleven.xml"); } catch (Exception e) { Console.WriteLine("test 11 failed with exception: " + e); } }Example 12
This example shows how to use XML Converters™ to convert an EDI file into an XPathDocument contained entirely in memory. In the example, the toXml.Convert call starts the conversion. The application can read results of the conversion with the converterResult.XmlReader. The application can do anything it chooses with the output data. In this example, it uses a new XPathDocument(...) to read the results directly into an XPathDocument object.
try{ Source converterSource = new UriSource(uriString + "831.x12"); XmlReaderResult converterResult = new XmlReaderResult(); Converter toXml = factory.CreateConvertToXml("converter:EDI"); toXml.Convert(converterSource, converterResult); XPathDocument xpathdoc = new XPathDocument(converterResult.XmlReader); Console.WriteLine("test 12 finished: 831.x12 --> XPathDocument in memory"); } catch (Exception e) { Console.WriteLine("test 12 failed with exception: " + e); }Example 13
This example shows how to use an XML Converter to convert an EDI file into an XmlReader, which can then be used to read the XML data. XmlReader processes data entirely in memory in a streaming fashion, allowing efficient processing of input files of literally unlimited size.
Note that there is no call to Convert(...) in this example. The GetXmlReader call is a convenience method which does the convert and returns the XmlReader in one call. The example then reads and counts all the parsing events from the XmlReader.
In a real application, the program would process those events as they are read.
try{ Source converterSource = new UriSource(uriString + "831.x12"); ConvertToXml toXml = factory.CreateConvertToXml("converter:EDI"); int eventCount = 0; using (XmlReader rdr = toXml.GetXmlReader(converterSource)) { while(rdr.Read()) { eventCount++; } } Console.WriteLine("test 13 finished: 831.x12 --> XmlReader containing " + eventCount + " events."); } catch (Exception e) { Console.WriteLine("test 13 failed with exception: " + e); } }Example 14
This example shows how to use the EDI Analyzer API to convert an input EDI document, threemsgs.x12, to XML. The source EDI contains three messages, one of which contains an error. This example shows how to use the EDI analysis report generated by the Analyze() method to filter the invalid message from the EDI while converting the rest of the EDI stream to XML. Finally, it shows how to convert the EDI analysis report’s Receipt and Acknowledgement elements to EDI for transmission back to the EDI sender.
For more information about using the EDI Analyzer API, see Chapter 3, Analyzing EDI to XML Conversions.
try { Source ediSource = new UriSource(uriString + "threemsgs.x12"); ConvertToXml toXml = factory.CreateConvertToXml("converter:EDI"); Result reportResult = new UriResult("report.xml"); toXml.Analyze(ediSource, reportResult); Source reportSource = new UriSource(new FileInfo("report.xml") .FullName); Result xmlResult = new UriResult("twomsgs.xml"); toXml.Convert(ediSource, xmlResult, reportSource); XmlReader rdr = XmlReader.Create("report.xml"); while(rdr.Read()) { if ( rdr.NodeType == XmlNodeType.Element && rdr.LocalName == "Receipt") break; } while(rdr.Read()) { if ( rdr.NodeType == XmlNodeType.Element && rdr.LocalName == "X12") break; } ConvertFromXml converter = factory.CreateConvertFromXml ("converter:EDI"); Source responseSource = new XmlReaderSource(rdr); Result receiptResult = new UriResult("receipt.x12"); converter.Convert(responseSource, receiptResult); while(rdr.Read()) { if ( rdr.NodeType == XmlNodeType.Element && rdr.LocalName == "Acknowledgement") break; } while(rdr.Read()) { if ( rdr.NodeType == XmlNodeType.Element && rdr.LocalName == "X12") break; } Result ackResult = new UriResult("acknowledgement.x12"); converter.Convert(responseSource, ackResult); rdr.Close(); Console.WriteLine("test 14 finished: threemsgs.x12 --> twomsgs.xml, receipt.x12, acknowledgement.x12"); } catch (Exception e) { Console.WriteLine("test 14 failed with exception: " + e); } }