public void EV_1102_DefaultSerializationDefaultLegacy() { ClinicalDocument document = new ClinicalDocument(); document.Component = new Component2(); document.Component.SetBodyChoice(new StructuredBody()); document.Component.GetBodyChoiceIfStructuredBody().Component.Add(new Component3()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section = new Section(); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry.Add(new Entry()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry[0].SetClinicalStatement( new ObservationWithConfidentialityCode() { ConfidentialityCode = x_BasicConfidentialityKind.Restricted } ); XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultLegacy; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { var result = formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); Assert.IsNotNull(result.Details.FirstOrDefault(o => o is NotSupportedChoiceResultDetail)); } }
public void EV_1087Test() { RelatedPerson person = new RelatedPerson( SET <PN> .CreateSET(new PN(EntityNameUse.Legal, "John Smith")), SET <TEL> .CreateSET((TEL)"mailto:[email protected]"), "F", DateTime.Now, DateTime.Today, SET <AD> .CreateSET(AD.CreateAD(PostalAddressUse.Direct, new ADXP("123 Main Street West, Hamilton, ON"))), null); person.DeceasedInd = true; // This fails try { XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.Settings = SettingsType.DefaultLegacy; fmtr.GraphAides.Add(new DatatypeFormatter()); StringWriter sw = new StringWriter(); using (XmlStateWriter writer = new XmlStateWriter(XmlWriter.Create(sw))) { writer.WriteStartElement("test", "urn:hl7-org:v3"); fmtr.Graph(writer, person); writer.WriteEndElement(); } } catch (Exception ex) { Assert.Fail(); } }
public void EV_1102_DefaultSerializationDefaultLegacy() { ClinicalDocument document = new ClinicalDocument(); document.Component = new Component2(); document.Component.SetBodyChoice(new StructuredBody()); document.Component.GetBodyChoiceIfStructuredBody().Component.Add(new Component3()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section = new Section(); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry.Add(new Entry()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry[0].SetClinicalStatement( new ObservationWithConfidentialityCode() { ConfidentialityCode = x_BasicConfidentialityKind.Restricted } ); XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultLegacy; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { var result = formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); Assert.IsNotNull(result.Details.FirstOrDefault(o=>o is NotSupportedChoiceResultDetail)); } }
public void XMLITS1_SettingsTest02() { try { // Create formatter and setup graph aides var formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new DatatypeFormatter() { CompatibilityMode = DatatypeFormatterCompatibilityMode.ClinicalDocumentArchitecture }); // Disable validation formatter.ValidateConformance = false; // Create Settings // Looks like all settings // can be assigned without issues. formatter.Settings = SettingsType.AllowFlavorImposing | SettingsType.AllowSupplierDomainImposing | SettingsType.AllowUpdateModeImposing | SettingsType.DefaultLegacy | SettingsType.DefaultMultiprocessor | SettingsType.DefaultUniprocessor | SettingsType.EnableDeepLearning | SettingsType.UseGeneratorFormat | SettingsType.UseReflectionFormat; // If no exceptions, pass assertion Assert.IsTrue(true); } catch (Exception e) { Assert.Fail(); Console.WriteLine(e); } }
public void EV_1102_AlwaysCheckForOverridesReflection() { ClinicalDocument document = new ClinicalDocument(); document.Component = new Component2(); document.Component.SetBodyChoice(new StructuredBody()); document.Component.GetBodyChoiceIfStructuredBody().Component.Add(new Component3()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section = new Section(); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry.Add(new Entry()); document.Component.GetBodyChoiceIfStructuredBody().Component[0].Section.Entry[0].SetClinicalStatement( new ObservationWithConfidentialityCode() { ConfidentialityCode = x_BasicConfidentialityKind.Restricted } ); XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultUniprocessor; formatter.RegisterXSITypeName("POCD_MT000040.Observation", typeof(ObservationWithConfidentialityCode)); formatter.Settings |= SettingsType.AlwaysCheckForOverrides; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { var result = formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); Assert.IsNull(result.Details.FirstOrDefault(o => o is NotSupportedChoiceResultDetail)); } }
/// <summary> /// Print a structure to the console /// </summary> public static void PrintStructure(IGraphable structure) { // Create a formatter, this takes a model in memory and outputs it in XML using (XmlIts1Formatter fmtr = new XmlIts1Formatter()) { fmtr.Settings = SettingsType.DefaultUniprocessor; // We want to use CDA data types using (ClinicalDocumentDatatypeFormatter dtfmtr = new ClinicalDocumentDatatypeFormatter()) { // This is a good idea to prevent validation errors fmtr.ValidateConformance = false; // This instructs the XML ITS1 Formatter we want to use CDA datatypes fmtr.GraphAides.Add(dtfmtr); // Output in a nice indented manner using (XmlWriter xw = XmlWriter.Create(Console.Out, new XmlWriterSettings() { Indent = true })) { fmtr.Graph(xw, structure); } } } }
public void EV_1089SETParseTest() { PRPA_IN201305UV02 test = new PRPA_IN201305UV02(); test.Sender = new RMIM.UV.NE2010.MCCI_MT100200UV01.Sender(); test.Sender.Device = new RMIM.UV.NE2010.MCCI_MT100200UV01.Device(); test.Sender.Device.Id = new SET <II>() { NullFlavor = NullFlavor.NoInformation }; XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new DatatypeFormatter()); var sw = new StringWriter(); XmlStateWriter writer = new XmlStateWriter(XmlWriter.Create(sw)); fmtr.Graph(writer, test); writer.Flush(); String xmlString = sw.ToString(); StringReader sr = new StringReader(xmlString); XmlStateReader rdr = new XmlStateReader(XmlReader.Create(sr)); var result = fmtr.Parse(rdr); Assert.IsNotNull(result.Structure as PRPA_IN201305UV02); Assert.IsNotNull((result.Structure as PRPA_IN201305UV02).Sender.Device.Id); //Assert.AreEqual(test, result.Structure); }
public void GraphingAidesTest01() { Stream s = null; try { // Create an instance of the primary formatter IStructureFormatter formatter = new XmlIts1Formatter(); Console.WriteLine("Number of graphing aides: {0}", formatter.GraphAides.Count()); // Assign a graph aides formatter.GraphAides.Add(new DatatypeR2Formatter()); // Make sure that the formatter has been properly assigned graphing aides Console.WriteLine("Number of graphing aides: {0}", formatter.GraphAides.Count()); Console.WriteLine("Graphing Aide: {0}", formatter.GraphAides.ToString()); // Test to ensure that a graphing aide has been assigned to the formatter. Assert.IsTrue(formatter.GraphAides.Count() > 0); } finally { if (s != null) { s.Close(); } } }
public void EV_1101_DefaultSerializationLegacy() { String expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><ClinicalDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" classCode=\"DOCCLIN\" moodCode=\"EVN\" xmlns=\"urn:hl7-org:v3\"><author nullFlavor=\"NI\" xsi:nil=\"true\" /></ClinicalDocument>"; ClinicalDocument document = new ClinicalDocument(); Author a = new Author(); a.Time = DateTime.Now; a.AssignedAuthor = new AssignedAuthor(SET <II> .CreateSET(Guid.NewGuid())); document.Author.Add(a); a.NullFlavor = NullFlavor.NoInformation; XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultLegacy; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); R2SerializationHelper.XmlIsEquivalent(expected, data); } }
public void EV_1101_SuppressXsiNilMultiprocessor() { String expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><ClinicalDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" classCode=\"DOCCLIN\" moodCode=\"EVN\" xmlns=\"urn:hl7-org:v3\"><author typeCode=\"AUT\" nullFlavor=\"NI\" contextControlCode=\"OP\"><time value=\"20140116103733.292-0500\" /><assignedAuthor classCode=\"ASSIGNED\"><id root=\"2BCF1373-9199-4574-A254-0E7558DE9825\" /></assignedAuthor></author></ClinicalDocument>"; ClinicalDocument document = new ClinicalDocument(); Author a = new Author(); a.Time = (TS)"20140116103733.292-0500"; a.AssignedAuthor = new AssignedAuthor(SET <II> .CreateSET(Guid.Parse("2BCF1373-9199-4574-A254-0E7558DE9825"))); document.Author.Add(a); a.NullFlavor = NullFlavor.NoInformation; XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.Settings = SettingsType.DefaultMultiprocessor; formatter.Settings |= SettingsType.SuppressXsiNil | SettingsType.SuppressNullEnforcement; formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { var results = formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); R2SerializationHelper.XmlIsEquivalent(expected, data); } }
public void XMLITS1_SettingsTest01() { try { // Create formatter and setup graph aides var formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new DatatypeFormatter() { CompatibilityMode = DatatypeFormatterCompatibilityMode.ClinicalDocumentArchitecture }); // Disable validation formatter.ValidateConformance = false; // Create settings formatter.Settings = SettingsType.UseReflectionFormat | SettingsType.AllowFlavorImposing; // If no exceptions, pass assertion Assert.IsTrue(true); } catch (Exception e) { Assert.Fail(); Console.WriteLine(e); } }
/// <summary> /// Logs the message. /// </summary> /// <param name="message">The message to log.</param> private static void LogMessage(IGraphable message) { XmlWriter writer = null; var formatter = new XmlIts1Formatter { ValidateConformance = true, }; var dtf = new DatatypeFormatter(); formatter.GraphAides.Add(dtf); var sb = new StringBuilder(); writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }); var stateWriter = new XmlStateWriter(writer); formatter.Graph(stateWriter, message); stateWriter.Flush(); traceSource.TraceEvent(TraceEventType.Verbose, 0, sb.ToString()); }
public void IInteractionTest01() { // Find the resource to be parsed. string neededResource = findResource("PRPA_IN101103CA.xml"); // Load the assembly into the current AppDomain Assembly.Load(new AssemblyName("MARC.Everest.RMIM.CA.R020402, Version=1.0.4366.42027, Culture=neutral")); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is PRPA_IN101103CA s = GetResourceStream(neededResource); if (s == null) { Console.WriteLine("Invalid input stream."); } // Setup the formatter as XML ITS 1 with Canadian Data Types R1 var formatter = new XmlIts1Formatter(); formatter.ValidateConformance = false; // Assign graphing aides to formatter formatter.GraphAides.Add(new DatatypeFormatter()); var instance = formatter.Parse(s).Structure as IInteraction; if (instance != null) // instance is an interaction { // Output instance information Console.WriteLine("Interaction ID: {0}\r\nCreated On: {1}\r\nProcessing Mode Code: {2}\r\nVersion: {3}", instance.InteractionId.Extension, instance.CreationTime, instance.ProcessingModeCode, instance.VersionCode ); // Ensure that we have a valid patient interaction instance Assert.IsTrue(instance.InteractionId.Extension.StartsWith("PRPA")); } else { // if instance is null, fail assertion Assert.Fail(); } } finally { if (s != null) { s.Close(); } } }
public void XmlStateWriterTest01() { // Initialize the XmlWriter & State writer StringWriter sw = new StringWriter(); var xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }); // Write something at the start xw.WriteStartElement("myHl7ExampleInstance"); xw.WriteAttributeString("interactionId", "MCCI_IN000000UV01"); // State writer should always be used XmlStateWriter xsw = new XmlStateWriter(xw); // Create a simple instance MCCI_IN000000UV01 instance = new MCCI_IN000000UV01( Guid.NewGuid(), DateTime.Now, MCCI_IN000000UV01.GetInteractionId(), ProcessingID.Production, "P", AcknowledgementCondition.Always); // Setup the formatter IXmlStructureFormatter structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; structureFormatter.GraphAides.Add(new DatatypeFormatter()); // Print current path of the xmlwriter before formatting instance var writeStatePreFormat = xsw.WriteState; Console.WriteLine("Write state pre-format: {0}", writeStatePreFormat); // Format var result = structureFormatter.Graph(xsw, instance); // Print current path of the xmlwriter after formatting instance var writeStatePostFormat = xsw.WriteState; Console.WriteLine("Write state post-format: {0}", writeStatePostFormat); // Test that the write states before and after formatting has changed. // This demonstrates how the state of the xml writer can be tracked while runnning. Assert.AreNotEqual(writeStatePreFormat, writeStatePostFormat); // Flush state writer xsw.Flush(); // finish the stream xw.WriteEndElement(); }
public void displayGraphResultsTest04() { // Flag used to verify if the graph result // contains details alongside its errors. bool noDetails = true; // Create a simple instance that PASSES ValidationConformance MCCI_IN000000UV01 instance = new MCCI_IN000000UV01( Guid.NewGuid(), DateTime.Now, MCCI_IN000000UV01.GetInteractionId(), ProcessingID.Production, "P", AcknowledgementCondition.Never, null, new Sender(new Device(new SET <II>(Guid.NewGuid()))), null ); // Create the Xml ITS1 formatter var formatter = new XmlIts1Formatter() { ValidateConformance = false }; // Assign R1 graphing aide formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); // Graph the instance where instance is any interaction type var graphResult = formatter.Graph(Console.OpenStandardOutput(), instance); // Get the results. // If there are any errors, list the details, // otherwise, acknowledge that instance creted is valid. if (graphResult.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", graphResult.Code); foreach (var detail in graphResult.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } noDetails = false; } else { Console.WriteLine("No errors. Instance created is a valid instance."); } // Assert that the returned instance is valid. Assert.AreEqual(graphResult.Code, ResultCode.Accepted); Assert.AreEqual(noDetails, true); } // end test method
private static XmlIts1Formatter CreateStructureFormater() { var structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; structureFormatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); structureFormatter.Settings |= SettingsType.AlwaysCheckForOverrides; structureFormatter.ValidateConformance = false; structureFormatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); structureFormatter.RegisterXSITypeName("custom:RecordTarget", typeof(RecordTarget)); //structureFormatter.RegisterXSITypeName("custom:ClinicalDocument", typeof(ClinicalDocument)); //structureFormatter.RegisterXSITypeName("custom:StructuredBody", typeof(StructuredBody)); return structureFormatter; }
public void InstanceCDAR2Test_XSD_ClinicalDocument() { MemoryStream stream = new MemoryStream(); try { IResultDetail[] details = null; TypeCreator tc = TypeCreator.GetCreator(typeof(ClinicalDocument)); tc.GenerateOptional = true; MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument original = tc.CreateInstance() as MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument; original.ComponentOf = TypeCreator.GetCreator(typeof(Component1)).CreateInstance() as Component1; original.Component = new Component2(); original.Component.SetBodyChoice(TypeCreator.GetCreator(typeof(StructuredBody)).CreateInstance() as StructuredBody); XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); fmtr.Graph(stream, original); stream.Seek(0, SeekOrigin.Begin); XMLGenerator.GenerateInstance(typeof(MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument), stream, out details); if (details.Length > 0) { foreach (var item in details) { if (item.Type == ResultDetailType.Error) { Tracer.Trace(item.Message); } } } } catch (Exception ex) { throw new Exception(ex.ToString(), ex); } stream.Flush(); stream.Seek(0, SeekOrigin.Begin); stream.Flush(); string xml = new StreamReader(stream).ReadToEnd(); stream.Seek(0, SeekOrigin.Begin); stream.Flush(); var result = XMLValidator.Validate("ClinicalDocument", stream, typeof(MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument)); if (result.Count > 0) { result.ForEach(item => Trace.WriteLine(item)); Assert.Fail("Validation failed"); } }
public void displayGraphResultsTest08() { bool noDetails = true; // Create a simple instance that FAILS ValidationConformance MCCI_IN000000UV01 instance = new MCCI_IN000000UV01( Guid.NewGuid(), DateTime.Now, MCCI_IN000000UV01.GetInteractionId(), ProcessingID.Production, "P", AcknowledgementCondition.Never, null, null, null ); // Create the Xml ITS1 formatter. var formatter = new XmlIts1Formatter() { ValidateConformance = false }; // Assign R1 graphing aide formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); // Graph the instance where instance is any interaction type. var graphResult = formatter.Graph(Console.OpenStandardOutput(), instance); // Get the results. if (graphResult.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", graphResult.Code); foreach (var detail in graphResult.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } noDetails = false; } else { Console.WriteLine("No errors. Instance created is a valid instance."); } // Assert: Errors are found. Assert.AreEqual(noDetails, true); Assert.AreEqual(graphResult.Code, ResultCode.Accepted); } // end test method
public void FormatPatient() { // Create a formatter with a graph aide XmlIts1Formatter fmtr = new XmlIts1Formatter(); // Gets or sets a list of aide formatters // that assist in the formatting of this instance fmtr.GraphAides.Add(new DatatypeFormatter()); // Format to a string StringWriter sw = new StringWriter(); XmlStateWriter xmlSw = new XmlStateWriter( XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }) ); // Call our method here... var patient = Utils.CreatePatient( Guid.NewGuid(), EN.CreateEN(EntityNameUse.Legal, new ENXP("John", EntityNamePartType.Given), new ENXP("Smith", EntityNamePartType.Family) ), AD.CreateAD(PostalAddressUse.HomeAddress, "123 Main Street West", "Hamilton", "Ontario", "Canada" ), "*****@*****.**" ); // Format to the formatter. // Details results in a result code // that indicates the outcome of the graph. var details = fmtr.Graph(xmlSw, patient); // Flush and close xmlSw.Close(); // Output to console Console.WriteLine("XML: "); Console.WriteLine(sw.ToString()); Console.WriteLine("Validation:"); foreach (var dtl in details.Details) { Console.WriteLine("{0} : {1}", dtl.Type, dtl.Message); } }
public void StreamParseTest02() { // Find the resource to be parsed. string neededResource = FindResource("PRPA_IN101103CA.xml"); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is MCCI_IN000000UV01 s = GetResourceStream(neededResource); if (s == null) { Console.WriteLine("Invalid input stream."); } // Setup the formatter ICodeDomStructureFormatter structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; // Add graphing aides structureFormatter.GraphAides.Add(new DatatypeFormatter()); // Parse Resource Stream var result = structureFormatter.Parse(s, typeof(PRPA_IN101103CA).Assembly); // Output the type of instance that was parsed Console.WriteLine("This file contains a '{0}' instance.", result.Structure.GetType().Name); // Main assertion Assert.IsFalse(result.Structure.GetType() == typeof(MCCI_IN000000UV01)); // Correct parsing verification. Assert.IsTrue(result.Structure.GetType() == typeof(PRPA_IN101103CA)); } finally { if (s != null) { s.Close(); } } }
static void Main(string[] args) { // This example uses the Everest File Connector to listen to a directory and validate messages that appear there // It can be used as a standalone application as a way of validating instance messages from other sources // copied the below code from the example in the dev guide page 50 Assembly.Load(new AssemblyName("MARC.Everest.RMIM.CA.R020401")); XmlIts1Formatter its1Formatter = new XmlIts1Formatter(); its1Formatter.GraphAides.Add( new DatatypeFormatter() ); // Select a folder string directory = String.Empty; while (String.IsNullOrEmpty(directory) || !Directory.Exists(directory)) { Console.Write("Enter directory to listen to:"); directory = Console.ReadLine(); } // We can use a connection string builder to make creating the connection string easier FileConnectionStringBuilder connStringBuilder = new FileConnectionStringBuilder(); connStringBuilder.Directory = directory; connStringBuilder.KeepFiles = true; connStringBuilder.Pattern = "*.xml"; // Create an instance of the connector FileListenConnector connector = new FileListenConnector(connStringBuilder.GenerateConnectionString()); connector.Formatter = its1Formatter; connector.Open(); // Assign message available event connector.MessageAvailable += new EventHandler <UnsolicitedDataEventArgs>(connector_MessageAvailable); connector.Start(); // Start watching the directory // Exit condition Console.Write("Press any key to quit...\n"); Console.ReadKey(); // Close connector connector.Close(); }
/// <summary> /// Format a data type into a string /// </summary> /// <param name="dataType">The data type to format</param> /// <param name="rootName">The name of the root element</param> /// <returns>A pretty-printed XML string</returns> internal static string FormatDataType(IGraphable dataType, string rootName) { MemoryStream ms = new MemoryStream(); // Format to XML Writer XmlWriter xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings() { Indent = true, Encoding = System.Text.Encoding.ASCII }); xmlWriter.WriteStartElement(rootName, "urn:hl7-org:v3"); // Don't worry about these lines right now XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new DatatypeFormatter()); fmtr.Graph(xmlWriter, dataType); // Finish the string xmlWriter.WriteEndElement(); xmlWriter.Close(); return System.Text.Encoding.UTF8.GetString(ms.GetBuffer()); }
public void StreamParseTest01() { // Find the resource to be parsed. string neededResource = FindResource("MCCI_IN000000UV01.xml"); // Load the assembly into the current AppDomain var asm = Assembly.Load(new AssemblyName("MARC.Everest.RMIM.UV.NE2008, Version=1.0.4366.42027, Culture=neutral")); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is MCCI_IN000000UV01 s = GetResourceStream(neededResource); if (s == null) { Console.WriteLine("Invalid input stream."); } // Setup the formatter var structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; // Add graphing aides structureFormatter.GraphAides.Add(new DatatypeFormatter()); // Parse Resource Stream var result = structureFormatter.Parse(s, asm); // Output the type of instance that was parsed Console.WriteLine("This file contains a '{0}' instance.", result.Structure.GetType().Name); Assert.IsTrue(result.Structure.GetType() == typeof(MCCI_IN000000UV01)); Assert.IsTrue(result.Structure.GetType().Name == "MCCI_IN000000UV01"); } finally { if (s != null) { s.Close(); } } }
static void Main(string[] args) { // This example uses the Everest File Connector to listen to a directory and validate messages that appear there // It can be used as a standalone application as a way of validating instance messages from other sources // copied the below code from the example in the dev guide page 50 Assembly.Load(new AssemblyName("MARC.Everest.RMIM.CA.R020401")); XmlIts1Formatter its1Formatter = new XmlIts1Formatter(); its1Formatter.GraphAides.Add( new DatatypeFormatter() ); // Select a folder string directory = String.Empty; while (String.IsNullOrEmpty(directory) || !Directory.Exists(directory)) { Console.Write("Enter directory to listen to:"); directory = Console.ReadLine(); } // We can use a connection string builder to make creating the connection string easier FileConnectionStringBuilder connStringBuilder = new FileConnectionStringBuilder(); connStringBuilder.Directory = directory; connStringBuilder.KeepFiles = true; connStringBuilder.Pattern = "*.xml"; // Create an instance of the connector FileListenConnector connector = new FileListenConnector(connStringBuilder.GenerateConnectionString()); connector.Formatter = its1Formatter; connector.Open(); // Assign message available event connector.MessageAvailable += new EventHandler<UnsolicitedDataEventArgs>(connector_MessageAvailable); connector.Start(); // Start watching the directory // Exit condition Console.Write("Press any key to quit...\n"); Console.ReadKey(); // Close connector connector.Close(); }
/// <summary> /// Send HL7v3 messages to a specified endpoint. /// </summary> /// <param name="message">The message.</param> /// <param name="endpointName">Name of the endpoint.</param> /// <returns><c>true</c> If the message sent successfully, <c>false</c> otherwise.</returns> public static bool Sendv3Messages(IGraphable message, string endpointName) { var retVal = true; var client = new WcfClientConnector($"endpointName={endpointName}"); var formatter = new XmlIts1Formatter { ValidateConformance = true }; client.Formatter = formatter; client.Formatter.GraphAides.Add(new DatatypeFormatter()); client.Open(); var sendResult = client.Send(message); traceSource.TraceEvent(TraceEventType.Verbose, 0, "Sending HL7v3 message to endpoint: " + client.ConnectionString); if (sendResult.Code != ResultCode.Accepted && sendResult.Code != ResultCode.AcceptedNonConformant) { traceSource.TraceEvent(TraceEventType.Error, 0, "Send result: " + Enum.GetName(typeof(ResultCode), sendResult.Code)); retVal = false; } var receiveResult = client.Receive(sendResult); if (receiveResult.Code != ResultCode.Accepted && receiveResult.Code != ResultCode.AcceptedNonConformant) { traceSource.TraceEvent(TraceEventType.Error, 0, "Receive result: " + Enum.GetName(typeof(ResultCode), receiveResult.Code)); retVal = false; } var result = receiveResult.Structure; if (result == null) { traceSource.TraceEvent(TraceEventType.Error, 0, "Receive result structure is null"); retVal = false; } client.Close(); return(retVal); }
private static XmlIts1Formatter CreateStructureFormater() { var structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; structureFormatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); structureFormatter.Settings |= SettingsType.AlwaysCheckForOverrides; structureFormatter.ValidateConformance = false; structureFormatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); structureFormatter.RegisterXSITypeName("custom:RecordTarget", typeof(RecordTarget)); //structureFormatter.RegisterXSITypeName("custom:ClinicalDocument", typeof(ClinicalDocument)); //structureFormatter.RegisterXSITypeName("custom:StructuredBody", typeof(StructuredBody)); return(structureFormatter); }
public void EV_1089SampleParseTest() { try { var instance = ParseFromStreamTest.FindResource("REPC_IN002120UV01.xml"); // Parse XmlIts1Formatter fmtr = new XmlIts1Formatter() { GraphAides = new List <Connectors.IStructureFormatter>() { new DatatypeFormatter() } }; XmlStateReader reader = new XmlStateReader(XmlReader.Create(ParseFromStreamTest.GetResourceStream(instance))); var result = fmtr.Parse(reader, typeof(PRPA_IN201301UV02).Assembly); Assert.IsNotNull(((((result.Structure as REPC_IN002120UV01).controlActProcess.Subject[0].act.PertinentInformation3[3].CareStatement as RMIM.UV.NE2010.REPC_MT000100UV01.Observation).TargetOf[1].CareEntry as MARC.Everest.RMIM.UV.NE2010.REPC_MT000100UV01.SubstanceAdministration).Consumable.ConsumableChoice as RMIM.UV.NE2010.COCT_MT230100UV.Medication).AdministerableMedicine.Name); } catch { } }
public static object Parse(string fileName) { using (XmlIts1Formatter fmtr = new XmlIts1Formatter()) { fmtr.Settings = SettingsType.DefaultUniprocessor; using (ClinicalDocumentDatatypeFormatter dtfmtr = new ClinicalDocumentDatatypeFormatter()) { // This is a good idea to prevent validation errors fmtr.ValidateConformance = false; // This instructs the XML ITS1 Formatter we want to use CDA datatypes fmtr.GraphAides.Add(dtfmtr); return(fmtr.Parse(new FileStream(fileName, FileMode.Open))); // Output in a nice indented manner return(dtfmtr.Parse(new FileStream(fileName, FileMode.Open))); } } }
/// <summary> /// Initialize the client connector /// </summary> private void InitializeConnector() { // Build connection string WcfConnectionStringBuilder csBuilder = new WcfConnectionStringBuilder(); csBuilder.EndpointName = "clientRegistry"; // Create formatter XmlIts1Formatter fmtr = new XmlIts1Formatter() { ValidateConformance = false }; fmtr.GraphAides.Add(new CanadianDatatypeFormatter() { ValidateConformance = false }); // Setup and open this.m_clientConnector = new WcfClientConnector(csBuilder.GenerateConnectionString()); this.m_clientConnector.Formatter = fmtr; this.m_clientConnector.Open(); }
public void EV_1089SampleReflectParseTest() { try { var instance = ParseFromStreamTest.FindResource("REPC_IN002120UV01.xml"); // Parse XmlIts1Formatter fmtr = new XmlIts1Formatter() { GraphAides = new List<Connectors.IStructureFormatter>() { new DatatypeFormatter() }, Settings = SettingsType.DefaultUniprocessor }; XmlStateReader reader = new XmlStateReader(XmlReader.Create(ParseFromStreamTest.GetResourceStream(instance))); var result = fmtr.Parse(reader, typeof(PRPA_IN201301UV02).Assembly); Assert.IsNotNull(((((result.Structure as REPC_IN002120UV01).controlActProcess.Subject[0].act.PertinentInformation3[3].CareStatement as RMIM.UV.NE2010.REPC_MT000100UV01.Observation).TargetOf[1].CareEntry as MARC.Everest.RMIM.UV.NE2010.REPC_MT000100UV01.SubstanceAdministration).Consumable.ConsumableChoice as RMIM.UV.NE2010.COCT_MT230100UV.Medication).AdministerableMedicine.Name); } catch { } }
/// <summary> /// Format a data type into a string /// </summary> /// <param name="dataType">The data type to format</param> /// <param name="rootName">The name of the root element</param> /// <returns>A pretty-printed XML string</returns> internal static string FormatDataType(IGraphable dataType, string rootName) { MemoryStream ms = new MemoryStream(); // Format to XML Writer XmlWriter xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings() { Indent = true, Encoding = System.Text.Encoding.ASCII }); xmlWriter.WriteStartElement(rootName, "urn:hl7-org:v3"); // Don't worry about these lines right now XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new DatatypeFormatter()); fmtr.Graph(xmlWriter, dataType); // Finish the string xmlWriter.WriteEndElement(); xmlWriter.Close(); return(System.Text.Encoding.UTF8.GetString(ms.GetBuffer())); }
public void WI1086_VerifyBugReflectTest() { // Load the XmlInstance into a string reader StringReader sr = new StringReader(this.m_xmlInstance); XmlStateReader xr = new XmlStateReader(XmlReader.Create(sr)); XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultUniprocessor; formatter.GraphAides.Add(new DatatypeFormatter() { CompatibilityMode = DatatypeFormatterCompatibilityMode.Canadian }); try { MCCI_IN000002CA instance = formatter.Parse(xr, typeof(MCCI_IN000002CA)).Structure as MCCI_IN000002CA; if (instance == null) { throw new InvalidOperationException("Invalid test data"); } // Test 1, /receiver should be null (xsi:nil = true) Assert.IsNull(instance.Receiver, "Receiver"); // Test 2, /sender should also be null (xsi:nil = true) Assert.IsNull(instance.Sender, "Sender"); // Test 3, /acknowledgement should not be null and should have a null flavor (a notification should be notified though) Assert.IsNotNull(instance.Acknowledgement); Assert.AreEqual((NullFlavor)instance.Acknowledgement.NullFlavor.Code, NullFlavor.Unavailable); } finally { formatter.Dispose(); } }
/// <summary> /// Initialize the client connector /// </summary> private void InitializeConnector() { // Build connection string WcfConnectionStringBuilder csBuilder = new WcfConnectionStringBuilder(); csBuilder.EndpointName = "pdqSupplier"; // Create formatter XmlIts1Formatter fmtr = new XmlIts1Formatter() { ValidateConformance = false }; fmtr.GraphAides.Add(new CanadianDatatypeFormatter() { ValidateConformance = false }); // Setup and open this.m_clientConnector = new WcfClientConnector(csBuilder.GenerateConnectionString()); this.m_clientConnector.Formatter = fmtr; this.m_clientConnector.Open(); }
/// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Initialize Everest XmlIts1Formatter its1 = new XmlIts1Formatter(); its1.AddFormatterAssembly(Assembly.GetExecutingAssembly()); // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Disable the application idle detection by setting the UserIdleDetectionMode property of the // application's PhoneApplicationService object to Disabled. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } }
/// <summary> /// Serialize query /// </summary> internal static byte[] SerializeQuery(IGraphable queryByParameter) { using (XmlIts1Formatter fmtr = new XmlIts1Formatter() { ValidateConformance = false }) { StringBuilder sb = new StringBuilder(); XmlStateWriter writer = new XmlStateWriter(XmlWriter.Create(sb)); // Write the start element writer.WriteStartElement("queryByParameter", "urn:hl7-org:v3"); fmtr.GraphAides.Add(new DatatypeFormatter() { CompatibilityMode = DatatypeFormatterCompatibilityMode.Universal, ValidateConformance = false }); fmtr.Graph(writer, queryByParameter); writer.WriteEndElement(); writer.Close(); // Return the constructed result return(Encoding.ASCII.GetBytes(sb.ToString())); } }
public void displayGraphResultsTest04() { // Flag used to verify if the graph result // contains details alongside its errors. bool noDetails = true; // Create a simple instance that PASSES ValidationConformance MCCI_IN000000UV01 instance = new MCCI_IN000000UV01( Guid.NewGuid(), DateTime.Now, MCCI_IN000000UV01.GetInteractionId(), ProcessingID.Production, "P", AcknowledgementCondition.Never, null, new Sender(new Device(new SET<II>(Guid.NewGuid()))), null ); // Create the Xml ITS1 formatter var formatter = new XmlIts1Formatter() { ValidateConformance = false }; // Assign R1 graphing aide formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); // Graph the instance where instance is any interaction type var graphResult = formatter.Graph(Console.OpenStandardOutput(), instance); // Get the results. // If there are any errors, list the details, // otherwise, acknowledge that instance creted is valid. if (graphResult.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", graphResult.Code); foreach (var detail in graphResult.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } noDetails = false; } else { Console.WriteLine("No errors. Instance created is a valid instance."); } // Assert that the returned instance is valid. Assert.AreEqual(graphResult.Code, ResultCode.Accepted); Assert.AreEqual(noDetails, true); } // end test method
public void WI1086_VerifyBugReflectTest() { // Load the XmlInstance into a string reader StringReader sr = new StringReader(this.m_xmlInstance); XmlStateReader xr = new XmlStateReader(XmlReader.Create(sr)); XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultUniprocessor; formatter.GraphAides.Add(new DatatypeFormatter() { CompatibilityMode = DatatypeFormatterCompatibilityMode.Canadian }); try { MCCI_IN000002CA instance = formatter.Parse(xr, typeof(MCCI_IN000002CA)).Structure as MCCI_IN000002CA; if (instance == null) throw new InvalidOperationException("Invalid test data"); // Test 1, /receiver should be null (xsi:nil = true) Assert.IsNull(instance.Receiver, "Receiver"); // Test 2, /sender should also be null (xsi:nil = true) Assert.IsNull(instance.Sender, "Sender"); // Test 3, /acknowledgement should not be null and should have a null flavor (a notification should be notified though) Assert.IsNotNull(instance.Acknowledgement); Assert.AreEqual((NullFlavor)instance.Acknowledgement.NullFlavor.Code, NullFlavor.Unavailable); } finally { formatter.Dispose(); } }
static void Main(string[] args) { // This layer of the Everest Framework maps 1:1 with the underlying HL7v3 structures, so it requires a detailed understanding of HL7v3 // This example shows some of the Mohawk Everest Framework features, such as: // // - overloaded constructors // - structural validation // - vocabulary support with enumerations // - smart datatype support with helper methods // - intellisense support including MIF documentation pass-thru // - built-in XML ITS formatting // - and other features (see API documentation) // // Higher levels of an API Framework would provide abstraction from these message details // // Create a client registry "find candidates query" message structure using the required parameters constructor // This constructor looks complicated at first, but it ensures that all required elements are present in the message structure PRPA_IN101103CA FindCandidatesStructure = new PRPA_IN101103CA( // use the required elements version of the constructor new MARC.Everest.DataTypes.II(new Guid("6AE2BD87-332A-3B99-4EAD-FAF9CE012843")), // message id new DateTime(2009, 03, 14, 19, 58, 55, 218), ResponseMode.Immediate, // response mode selected from enumeration new MARC.Everest.DataTypes.II("2.16.840.1.113883.1.18", "PRPA_IN101103CA"), // interaction id new MARC.Everest.DataTypes.LIST<II>() { new MARC.Everest.DataTypes.II("2.16.840.1.113883.2.20.2", "R02.04.00") }, // profileID new CS<ProcessingID>(ProcessingID.Debugging), // processing ID code new CS<AcknowledgementCondition>(AcknowledgementCondition.Never), // ack type new MARC.Everest.RMIM.CA.R020401.MCCI_MT002300CA.Receiver( new MARC.Everest.RMIM.CA.R020401.MCCI_MT002300CA.Device2(new II("2.16.840.1.113883.19.3.297.15.37.0.47", "DIS01"))), new MARC.Everest.RMIM.CA.R020401.MCCI_MT002300CA.Sender( new MARC.Everest.RMIM.CA.R020401.MCCI_MT002300CA.Device1(new II("2.16.840.1.113883.19.3.207.15.1.0.3", "DIS01")))); // prepare a coded value representing the trigger event - this will be attached to the control act event CV<String> triggerevent = new CV<String>() { Code = "PRPA_TE101103CA", CodeSystem = "2.16.840.1.113883.1.18" }; // Create the control act event required for this message and attach it to the structure // Since this is a "Query" interaction type, we create a QueryByParameter structure and attach it to the control act // We will later fill in this query block with our specific parameters FindCandidatesStructure.controlActEvent = PRPA_IN101103CA.CreateControlActEvent( new II("2.16.840.1.113883.19.3.207.15.1.1", "0245285594892"), triggerevent, new MARC.Everest.RMIM.CA.R020401.MFMI_MT700751CA.Author(new TS(DateTime.Parse("2009-03-14 19:58:55.218"))), new MARC.Everest.RMIM.CA.R020401.MFMI_MT700746CA.QueryByParameter<MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.ParameterList>( II.CreateToken(Guid.NewGuid()), new MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.ParameterList() )); // add the name to search for and attach it to the parameter list List<ENXP> namelist = new List<ENXP>(); namelist.Add(new ENXP("Nuclear", EntityNamePartType.Family)); namelist.Add(new ENXP("Nancy", EntityNamePartType.Given)); PN pn1 = new PN(namelist); MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.PersonName persname = new MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.PersonName(pn1); // notice we use .Add() to attach a name to the parameter list - this is due to the fact that a person name is actually a list of names FindCandidatesStructure.controlActEvent.QueryByParameter.parameterList.PersonName.Add(persname); // add the birthday to search for and add it to the parameter list TS birthdate = new TS(new DateTime(1990, 1, 1)); MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.PersonBirthtime pbt = new MARC.Everest.RMIM.CA.R020401.PRPA_MT101103CA.PersonBirthtime(birthdate); // notice we use assignment to attach the populated object pdt (no .Add() method as above since it is a simple object -- see PersonName.Add() for contrasting example) FindCandidatesStructure.controlActEvent.QueryByParameter.parameterList.PersonBirthtime = pbt; FindCandidatesStructure.controlActEvent.LanguageCode = new CE<string>() { NullFlavor = MARC.Everest.DataTypes.NullFlavor.AskedUnknown }; // Create an XML formatter XmlIts1Formatter its1Formatter = new XmlIts1Formatter(); // Add the datatypes R1 graph aide its1Formatter.GraphAides.Add(new DatatypeFormatter()); // Check the structure for conformance by forcing the formatter to render to a memory stream // Result.Code will then indicate if the message is conformant var Result = its1Formatter.Graph(new MemoryStream(), FindCandidatesStructure); if (Result.Code == MARC.Everest.Connectors.ResultCode.AcceptedNonConformant) { // we have a conformant message, so let's save it // print the XML to STDOUT its1Formatter.Graph(Console.OpenStandardOutput(), FindCandidatesStructure); // if we stream it through an XML writer and set the indent property the output will contain line breaks and indentation which makes it much easier to read (not necessaily required for machine-machine transmission) System.Xml.XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter x = XmlWriter.Create(@"PRPA_IN101103CA_Everest.xml", settings); // XmlStateWriter is required here to get around some complicated formatting issues MARC.Everest.Xml.XmlStateWriter sw = new MARC.Everest.Xml.XmlStateWriter(x); its1Formatter.Graph(sw, FindCandidatesStructure); sw.Flush(); } else { Console.WriteLine("Error trying to save structure PRPA_IN101103CA. Formatter response: {0}", Result.Code.ToString()); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public void EV_1101_SuppressXsiNilMultiprocessor() { String expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><ClinicalDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" classCode=\"DOCCLIN\" moodCode=\"EVN\" xmlns=\"urn:hl7-org:v3\"><author typeCode=\"AUT\" nullFlavor=\"NI\" contextControlCode=\"OP\"><time value=\"20140116103733.292-0500\" /><assignedAuthor classCode=\"ASSIGNED\"><id root=\"2BCF1373-9199-4574-A254-0E7558DE9825\" /></assignedAuthor></author></ClinicalDocument>"; ClinicalDocument document = new ClinicalDocument(); Author a = new Author(); a.Time = (TS)"20140116103733.292-0500"; a.AssignedAuthor = new AssignedAuthor(SET<II>.CreateSET(Guid.Parse("2BCF1373-9199-4574-A254-0E7558DE9825"))); document.Author.Add(a); a.NullFlavor = NullFlavor.NoInformation; XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.Settings = SettingsType.DefaultMultiprocessor; formatter.Settings |= SettingsType.SuppressXsiNil | SettingsType.SuppressNullEnforcement; formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { var results = formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); R2SerializationHelper.XmlIsEquivalent(expected, data); } }
public void EV_1101_DefaultSerializationLegacy() { String expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><ClinicalDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" classCode=\"DOCCLIN\" moodCode=\"EVN\" xmlns=\"urn:hl7-org:v3\"><author nullFlavor=\"NI\" xsi:nil=\"true\" /></ClinicalDocument>"; ClinicalDocument document = new ClinicalDocument(); Author a = new Author(); a.Time = DateTime.Now; a.AssignedAuthor = new AssignedAuthor(SET<II>.CreateSET(Guid.NewGuid())); document.Author.Add(a); a.NullFlavor = NullFlavor.NoInformation; XmlIts1Formatter formatter = new XmlIts1Formatter(); formatter.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); formatter.ValidateConformance = false; formatter.Settings = SettingsType.DefaultLegacy; StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw)) { formatter.Graph(xw, document); xw.Flush(); String data = sw.ToString(); R2SerializationHelper.XmlIsEquivalent(expected, data); } }
public void StreamParseTest02() { // Find the resource to be parsed. string neededResource = FindResource("PRPA_IN101103CA.xml"); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is MCCI_IN000000UV01 s = GetResourceStream(neededResource); if (s == null) Console.WriteLine("Invalid input stream."); // Setup the formatter ICodeDomStructureFormatter structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; // Add graphing aides structureFormatter.GraphAides.Add(new DatatypeFormatter()); // Parse Resource Stream var result = structureFormatter.Parse(s, typeof(PRPA_IN101103CA).Assembly); // Output the type of instance that was parsed Console.WriteLine("This file contains a '{0}' instance.", result.Structure.GetType().Name); // Main assertion Assert.IsFalse(result.Structure.GetType() == typeof(MCCI_IN000000UV01)); // Correct parsing verification. Assert.IsTrue(result.Structure.GetType() == typeof(PRPA_IN101103CA)); } finally { if (s != null) s.Close(); } }
public void EV_1110_DefaultUniprocessorCustomTypeTest() { // Load a sample because I don't want to write a full construction method ClinicalDocument clinicalDocument = null; using (Stream inStream = typeof(EV_1110).Assembly.GetManifestResourceStream("MARC.Everest.Test.Resources.phrDocTesting_140219112155-0500.xml")) { XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.ValidateConformance = false; fmtr.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); var result = fmtr.Parse(XmlReader.Create(inStream), typeof(ClinicalDocument)); clinicalDocument = result.Structure as ClinicalDocument; } var observation = new ObservationMyProfile() { MoodCode = x_ActMoodDocumentObservation.Eventoccurrence, Code = "3202-20", EntryRelationship = new List<EntryRelationship>() { new EntryRelationship(x_ActRelationshipEntryRelationship.HasComponent, true) { ClinicalStatement = new ObservationMyProfile() } } } ; CascadeNullFlavor(observation.EntryRelationship[0], NullFlavor.Unknown); // Cascade a null flavor on one of the entries clinicalDocument.Component.GetBodyChoiceIfStructuredBody().Component[1].Section.Entry.Add(new Entry( x_ActRelationshipEntry.HasComponent, false, observation )); // Cascade a null flavor on one of the entries clinicalDocument.Component.GetBodyChoiceIfStructuredBody().Component[2].Section.Entry.Add(new Entry( x_ActRelationshipEntry.HasComponent, false, observation )); // Cascade a null flavor on one of the entries clinicalDocument.Component.GetBodyChoiceIfStructuredBody().Component[3].Section.Entry.Add(new Entry( x_ActRelationshipEntry.HasComponent, false, observation )); StringWriter sw = new StringWriter(); using (XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true })) { XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.ValidateConformance = false; fmtr.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); fmtr.Settings = SettingsType.DefaultUniprocessor; fmtr.Settings |= SettingsType.SuppressXsiNil; fmtr.Settings |= SettingsType.SuppressNullEnforcement; fmtr.Settings |= SettingsType.AlwaysCheckForOverrides; fmtr.RegisterXSITypeName("POCD_MT000040.Observation", typeof(MARC.Everest.Test.Regressions.EV_1102.ObservationWithConfidentialityCode)); using (XmlStateWriter xsw = new XmlStateWriter(xw)) { xsw.WriteStartElement("hl7", "ClinicalDocument", "urn:hl7-org:v3"); xsw.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI); xsw.WriteAttributeString("schemaLocation", XmlIts1Formatter.NS_XSI, @"urn:hl7-org:v3 Schemas/CDA-PITO-E2E.xsd"); xsw.WriteAttributeString("xmlns", null, null, @"urn:hl7-org:v3"); xsw.WriteAttributeString("xmlns", "hl7", null, @"urn:hl7-org:v3"); xsw.WriteAttributeString("xmlns", "e2e", null, @"http://standards.pito.bc.ca/E2E-DTC/cda"); xsw.WriteAttributeString("xmlns", "xs", null, @"http://www.w3.org/2001/XMLSchema"); IFormatterGraphResult result = fmtr.Graph(xsw, clinicalDocument); foreach (ResultDetail itm in result.Details) Trace.WriteLine(String.Format("{0}:{1} @ {2}", itm.Type, itm.Message, itm.Location)); xsw.WriteEndElement(); // clinical document xsw.Flush(); } } Trace.WriteLine(sw.ToString()); Regex re = new Regex(@"\<entryRelationship.*/\>"); if (re.IsMatch(sw.ToString())) Assert.Fail("Output of entry relationship is not as expected"); }
public void displayGraphResultsTest10() { bool noDetails = true; // Find the necessary resource string neededResource = findResource("MCCI_IN000000UV01.xml"); // StreamReader is for outputting result to console Stream s = null; try { // Set the stream by reading from a file // whose datatype is MCCI_IN000000UV01 s = GetResourceStream(neededResource); if (s == null) Console.WriteLine("Invalid input stream."); // Setup the formatter var formatter = new XmlIts1Formatter() { ValidateConformance = true }; formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false }); // Parse and print result type. var graphResult = formatter.Parse(s); Console.WriteLine("Instance type: {0}", graphResult.Structure.GetType().Name); // Get the results. if (graphResult.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", graphResult.Code); foreach (var detail in graphResult.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } noDetails = false; } else { Console.WriteLine("No errors. Instance created is a valid instance."); } // Make sure the parsed file gives us an instance of MCCI_IN000000UV01 //Assert.AreEqual(graphResult.Structure.GetType(), typeof(MCCI_IN000000UV01)); // See if there are any errors in our results. Assert.AreEqual(noDetails, false); Assert.AreEqual(graphResult.Code, ResultCode.Rejected); } finally { if (s != null) s.Close(); } // end try-catch } // end test method
public void InstanceCDAR2Test_XSD_ClinicalDocument() { MemoryStream stream = new MemoryStream(); try { IResultDetail[] details = null; TypeCreator tc = TypeCreator.GetCreator(typeof(ClinicalDocument)); tc.GenerateOptional = true; MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument original = tc.CreateInstance() as MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument; original.ComponentOf = TypeCreator.GetCreator(typeof(Component1)).CreateInstance() as Component1; original.Component = new Component2(); original.Component.SetBodyChoice(TypeCreator.GetCreator(typeof(StructuredBody)).CreateInstance() as StructuredBody); XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new ClinicalDocumentDatatypeFormatter()); fmtr.Graph(stream, original); stream.Seek(0, SeekOrigin.Begin); XMLGenerator.GenerateInstance(typeof(MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument), stream, out details); if (details.Length > 0) foreach (var item in details) if (item.Type == ResultDetailType.Error) Tracer.Trace(item.Message); } catch (Exception ex) { throw new Exception(ex.ToString(), ex); } stream.Flush(); stream.Seek(0, SeekOrigin.Begin); stream.Flush(); string xml = new StreamReader(stream).ReadToEnd(); stream.Seek(0, SeekOrigin.Begin); stream.Flush(); var result = XMLValidator.Validate("ClinicalDocument", stream, typeof(MARC.Everest.RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument)); if (result.Count > 0) { result.ForEach(item => Trace.WriteLine(item)); Assert.Fail("Validation failed"); } }
public void EV_1089SETParseTest() { PRPA_IN201305UV02 test = new PRPA_IN201305UV02(); test.Sender = new RMIM.UV.NE2010.MCCI_MT100200UV01.Sender(); test.Sender.Device = new RMIM.UV.NE2010.MCCI_MT100200UV01.Device(); test.Sender.Device.Id = new SET<II>() { NullFlavor = NullFlavor.NoInformation }; XmlIts1Formatter fmtr = new XmlIts1Formatter(); fmtr.GraphAides.Add(new DatatypeFormatter()); var sw = new StringWriter(); XmlStateWriter writer = new XmlStateWriter(XmlWriter.Create(sw)); fmtr.Graph(writer, test); writer.Flush(); String xmlString = sw.ToString(); StringReader sr = new StringReader(xmlString); XmlStateReader rdr = new XmlStateReader(XmlReader.Create(sr)); var result = fmtr.Parse(rdr); Assert.IsNotNull(result.Structure as PRPA_IN201305UV02); Assert.IsNotNull((result.Structure as PRPA_IN201305UV02).Sender.Device.Id); //Assert.AreEqual(test, result.Structure); }
public void ExtractingUnsupportedPropertiesTest01() { XmlWriter xw = null; try { XmlIts1Formatter its1Formatter = new XmlIts1Formatter() { ValidateConformance = false, CreateRequiredElements = true }; // Assign R1 graphing aide its1Formatter.GraphAides.Add(new DatatypeFormatter(){ ValidateConformance = true, CompatibilityMode = DatatypeFormatterCompatibilityMode.Universal }); // initialize the XmlWriter & State Writer StringWriter sw = new StringWriter(); // Initialize XmlWriter and state writer xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }); XmlStateWriter xsw = new XmlStateWriter(xw); // Create and populate an instance of type 'Patient' var instance = Utils.CreatePatient( Guid.NewGuid(), new EN(), new AD(PostalAddressUse.VacationHome, new ADXP[] { } ) { // populate AD properties to see which are not supported ControlActExt = "populated", ControlActRoot = "populated", Flavor = "AD.BASIC", IsNotOrdered = true, UpdateMode = new CS<UpdateMode>(), Use = new SET<CS<PostalAddressUse>>(), UseablePeriod = new GTS(), ValidTimeHigh = new TS(), ValidTimeLow = new TS(), NullFlavor = null }, new TEL() ); // Format var result = its1Formatter.Graph(xsw, instance); // Iterate through the result details and get the unsupported details foreach (var dtl in result.Details) { if (dtl is UnsupportedDatatypeR1PropertyResultDetail) { var unsupp = dtl as UnsupportedDatatypeR1PropertyResultDetail; Console.WriteLine("The porperty '{0}' in datatype '{1}' was not formatted!", unsupp.PropertyName, unsupp.DatatypeName); } } // Flush the xml state writer xsw.Flush(); } finally { if (xw != null) xw.Close(); } }// end test method
public void GraphingAidesTest01() { Stream s = null; try { // Create an instance of the primary formatter IStructureFormatter formatter = new XmlIts1Formatter(); Console.WriteLine("Number of graphing aides: {0}", formatter.GraphAides.Count()); // Assign a graph aides formatter.GraphAides.Add(new DatatypeR2Formatter()); // Make sure that the formatter has been properly assigned graphing aides Console.WriteLine("Number of graphing aides: {0}", formatter.GraphAides.Count()); Console.WriteLine("Graphing Aide: {0}", formatter.GraphAides.ToString()); // Test to ensure that a graphing aide has been assigned to the formatter. Assert.IsTrue(formatter.GraphAides.Count() > 0); } finally { if (s != null) s.Close(); } }
public void StreamParseTest01() { // Find the resource to be parsed. string neededResource = FindResource("MCCI_IN000000UV01.xml"); // Load the assembly into the current AppDomain var asm = Assembly.Load(new AssemblyName("MARC.Everest.RMIM.UV.NE2008, Version=1.0.4366.42027, Culture=neutral")); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is MCCI_IN000000UV01 s = GetResourceStream(neededResource); if (s == null) Console.WriteLine("Invalid input stream."); // Setup the formatter var structureFormatter = new XmlIts1Formatter() { ValidateConformance = false }; // Add graphing aides structureFormatter.GraphAides.Add(new DatatypeFormatter()); // Parse Resource Stream var result = structureFormatter.Parse(s, asm); // Output the type of instance that was parsed Console.WriteLine("This file contains a '{0}' instance.", result.Structure.GetType().Name); Assert.IsTrue(result.Structure.GetType() == typeof(MCCI_IN000000UV01)); Assert.IsTrue(result.Structure.GetType().Name == "MCCI_IN000000UV01"); } finally { if (s != null) s.Close(); } }
public void IInteractionTest01() { // Find the resource to be parsed. string neededResource = findResource("PRPA_IN101103CA.xml"); // Load the assembly into the current AppDomain Assembly.Load(new AssemblyName("MARC.Everest.RMIM.CA.R020402, Version=1.0.4366.42027, Culture=neutral")); // Initialize stream that will read the needed resource file. Stream s = null; try { // Set the stream by reading from a file // whose datatype is PRPA_IN101103CA s = GetResourceStream(neededResource); if (s == null) Console.WriteLine("Invalid input stream."); // Setup the formatter as XML ITS 1 with Canadian Data Types R1 var formatter = new XmlIts1Formatter(); formatter.ValidateConformance = false; // Assign graphing aides to formatter formatter.GraphAides.Add(new DatatypeFormatter()); var instance = formatter.Parse(s).Structure as IInteraction; if (instance != null) // instance is an interaction { // Output instance information Console.WriteLine("Interaction ID: {0}\r\nCreated On: {1}\r\nProcessing Mode Code: {2}\r\nVersion: {3}", instance.InteractionId.Extension, instance.CreationTime, instance.ProcessingModeCode, instance.VersionCode ); // Ensure that we have a valid patient interaction instance Assert.IsTrue(instance.InteractionId.Extension.StartsWith("PRPA")); } else { // if instance is null, fail assertion Assert.Fail(); } } finally { if (s != null) s.Close(); } }
public void CreateReqElemOutputTest02() { XmlWriter xw = null; Stream s = null; try { /* STREAMWRITER CODE * s = File.Create("C:/Test Files/example85Data2.xml"); * StreamWriter sw1 = new StreamWriter(s); * * /* END STREAMWRITER CODE */ // Setup the formatter var its1Formatter = new XmlIts1Formatter() { ValidateConformance = true, CreateRequiredElements = true }; its1Formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false } ); // Initialize the XmlWriter & State writer StringWriter sw = new StringWriter(); xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }); // State writer should always be used XmlStateWriter xsw = new XmlStateWriter(xw); // Create an instance REPC_IN000076CA instance = new REPC_IN000076CA( Guid.NewGuid(), DateTime.Now, ResponseMode.Immediate, REPC_IN000076CA.GetInteractionId(), REPC_IN000076CA.GetProfileId(), ProcessingID.Production, AcknowledgementCondition.Always, new MARC.Everest.RMIM.CA.R020402.MCCI_MT002200CA.Receiver(), new MARC.Everest.RMIM.CA.R020402.MCCI_MT002200CA.Sender() ); instance.controlActEvent = new MARC.Everest.RMIM.CA.R020402.MCAI_MT700210CA.ControlActEvent <MARC.Everest.RMIM.CA.R020402.REPC_MT220001CA.Document>(); // Format var result = its1Formatter.Graph(xsw, instance); /* STREAMWRITER CODE * var result2 = its1Formatter.Graph(s, instance); * // Close streamwriter * sw1.Close(); * /* END STREAMWRITER CODE */ // Flush the xml state writer xsw.Flush(); if (result.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", result.Code); foreach (var detail in result.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } } // Assert: Instance is not conformant. Assert.AreEqual(ResultCode.Rejected, result.Code); /* STREAMWRITER CODE * // Validate that the written file contains the two injected strings. * StreamReader sr = new StreamReader("C:/Test Files/example85Data2.xml"); * * String xmlFromFile = ""; * // write everything in the stream to the console * while (!sr.EndOfStream) * { * // store lines into a string * xmlFromFile += sr.ReadLine(); * } * * // Write xml from the file onto the console * Console.WriteLine(xmlFromFile); * /* END STREAMWRITER CODE */ } finally { if (xw != null) { xw.Close(); } } }// end test method
public void CreateReqElemOutputTest02() { XmlWriter xw = null; Stream s = null; try { /* STREAMWRITER CODE s = File.Create("C:/Test Files/example85Data2.xml"); StreamWriter sw1 = new StreamWriter(s); /* END STREAMWRITER CODE */ // Setup the formatter var its1Formatter = new XmlIts1Formatter() { ValidateConformance = true, CreateRequiredElements = true }; its1Formatter.GraphAides.Add(new DatatypeFormatter() { ValidateConformance = false } ); // Initialize the XmlWriter & State writer StringWriter sw = new StringWriter(); xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }); // State writer should always be used XmlStateWriter xsw = new XmlStateWriter(xw); // Create an instance REPC_IN000076CA instance = new REPC_IN000076CA( Guid.NewGuid(), DateTime.Now, ResponseMode.Immediate, REPC_IN000076CA.GetInteractionId(), REPC_IN000076CA.GetProfileId(), ProcessingID.Production, AcknowledgementCondition.Always, new MARC.Everest.RMIM.CA.R020402.MCCI_MT002200CA.Receiver(), new MARC.Everest.RMIM.CA.R020402.MCCI_MT002200CA.Sender() ); instance.controlActEvent = new MARC.Everest.RMIM.CA.R020402.MCAI_MT700210CA.ControlActEvent <MARC.Everest.RMIM.CA.R020402.REPC_MT220001CA.Document>(); // Format var result = its1Formatter.Graph(xsw, instance); /* STREAMWRITER CODE var result2 = its1Formatter.Graph(s, instance); // Close streamwriter sw1.Close(); /* END STREAMWRITER CODE */ // Flush the xml state writer xsw.Flush(); if (result.Code != ResultCode.Accepted) { Console.WriteLine("RESULT CODE: {0}", result.Code); foreach (var detail in result.Details) { Console.WriteLine("{0}: {1}", detail.Type, detail.Message); } } // Assert: Instance is not conformant. Assert.AreEqual(ResultCode.Rejected, result.Code); /* STREAMWRITER CODE // Validate that the written file contains the two injected strings. StreamReader sr = new StreamReader("C:/Test Files/example85Data2.xml"); String xmlFromFile = ""; // write everything in the stream to the console while (!sr.EndOfStream) { // store lines into a string xmlFromFile += sr.ReadLine(); } // Write xml from the file onto the console Console.WriteLine(xmlFromFile); /* END STREAMWRITER CODE */ } finally { if (xw != null) xw.Close(); } }// end test method
static void Main(string[] args) { // Create a formatter with a graph aide XmlIts1Formatter fmtr = new XmlIts1Formatter(); // Gets or sets a list of aide formatters // that assist in the formatting of this instance fmtr.GraphAides.Add(new DatatypeFormatter()); // Format to a string StringWriter sw = new StringWriter(); XmlStateWriter xmlSw = new XmlStateWriter( XmlWriter.Create(sw, new XmlWriterSettings(){Indent = true}) ); // Call our method here... var patient = CreatePatient( Guid.NewGuid(), EN.CreateEN(EntityNameUse.Legal, new ENXP ("John", EntityNamePartType.Given), new ENXP ("Smith", EntityNamePartType.Family) ), AD.CreateAD(PostalAddressUse.HomeAddress, "123 Main Street West", "Hamilton", "Ontario", "Canada" ), "*****@*****.**" ); // Format to the formatter var details = fmtr.Graph(xmlSw, patient); // Flush and close xmlSw.Close(); // Output to console Console.WriteLine("XML: "); Console.WriteLine(sw.ToString()); Console.WriteLine("Validation:"); foreach (var dtl in details.Details) { Console.WriteLine("{0} : {1}", dtl.Type, dtl.Message); } Console.ReadKey(); }
public void BuildPatientTest02() { // Flag used to verify if the graph result // contains details alongside its errors. bool noDetails = true; // Flag used to verify that the create instance is valid. bool valInstance = false; // Create a formatter with a graph aide XmlIts1Formatter fmtr = new XmlIts1Formatter(); // Gets or sets a list of aide formatters // that assist in the formatting of this instance fmtr.GraphAides.Add(new DatatypeFormatter()); // Format to a string StringWriter sw = new StringWriter(); XmlStateWriter xmlSw = new XmlStateWriter( XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }) ); // Call our method here with invalid instance identifier. var patient = Utils.CreatePatient( new II(), EN.CreateEN(EntityNameUse.Legal, new ENXP("John", EntityNamePartType.Given), new ENXP("Smith", EntityNamePartType.Family) ), AD.CreateAD(PostalAddressUse.HomeAddress, "123 Main Street West", "Hamilton", "Ontario", "Canada" ), "*****@*****.**" ); // Format to the formatter var result = fmtr.Graph(xmlSw, patient); // Flush and close xmlSw.Close(); // Output to console Console.WriteLine("XML:"); Console.WriteLine(sw.ToString()); // If we get errors, set error catching flag to false and // print the details of each error. if (result.Details.Count() > 0) { noDetails = false; Console.WriteLine("validation:"); foreach (var dtl in result.Details) Console.WriteLine("{0} : {1}", dtl.Type, dtl.Message); } else { valInstance = true; } // Assert: Either there are no errors, // or there are details in the 'details' collection. if (noDetails) { Assert.AreEqual(valInstance, true); } else if (!valInstance) { Assert.AreEqual(noDetails, false); } else { // Test fails Assert.Fail(); } }