private static XmlDocument Serialize(IGraphable graph)
        {
            using (var ms = new MemoryStream())
            using (var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true }))
            using (var xsw = new XmlStateWriter(xmlWriter))
            {
                var structureFormatter = CreateStructureFormater();
                xsw.WriteStartElement("ClinicalDocument", "urn:hl7-org:v3");
                xsw.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI);
                xsw.WriteAttributeString("xmlns", null, null, "urn:hl7-org:v3");
                xsw.WriteAttributeString("xmlns", "custom", null, CustomNamespace);
                xsw.WriteAttributeString("xsi", "type", XmlIts1Formatter.NS_XSI, "custom:ClinicalDocument");

                structureFormatter.Graph(xsw, graph);
                xsw.Close();
                ms.Seek(0, SeekOrigin.Begin);
                Debug.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
                using (var reader = new XmlTextReader(ms))
                {
                    var result = new XmlDocument();
                    result.Load(reader);
                    return result;
                }
            }
        }
        internal static bool GenerateInstance(Type instanceType, Stream outputStream, out IResultDetail[] details)
        {
            string resourceName = String.Format(instanceType.FullName).Replace(".", "");

            var formatter = new MARC.Everest.Formatters.XML.ITS1.XmlIts1Formatter();

            formatter.Settings            = MARC.Everest.Formatters.XML.ITS1.SettingsType.DefaultUniprocessor;
            formatter.ValidateConformance = false;
            // Testing pregen
            formatter.GraphAides.Add(new MARC.Everest.Formatters.XML.Datatypes.R1.DatatypeFormatter());
            formatter.BuildCache(Assembly.Load("MARC.Everest.RMIM.CA.R020402").GetTypes());

            IGraphable result = TypeCreator.GetCreator(instanceType).CreateInstance() as IGraphable;

            Trace.WriteLine("Starting Serialization");
            DateTime start   = DateTime.Now;
            var      gresult = formatter.Graph(outputStream, result);

            Trace.WriteLine(String.Format("            ->{0}", DateTime.Now.Subtract(start).TotalMilliseconds));
            Trace.WriteLine(String.Format("            ->{0} bytes", outputStream.Length));
            List <IResultDetail> dlist = new List <IResultDetail>();

            dlist.AddRange(gresult.Details);
            details = dlist.ToArray();

            return(gresult.Code == MARC.Everest.Connectors.ResultCode.Accepted);
        }
        private string GenerateTargetFile(IGraphable data)
        {
            // Is this directory even open?
            if (!IsOpen())
            {
                throw new InvalidOperationException("Can't call send operation before .Open is called!");
            }

            string fn = targetFile;

            // Find a functiod (example: Guid/ID/etc...) that can be used to generate the name of the file
            if (targetFunctiod != null)
            {
                fn = targetFunctiod(data).ToString();
            }

            // Non overwrite, get a new fn (filename)
            string origFn = fn;
            int    i      = 0;

            while (System.IO.File.Exists(Path.Combine(targetDir, fn)) && !overwriteFile)
            {
                fn = string.Format("{0}.{1}", origFn, i);
                i++;
            }

            // Combine & return
            return(Path.Combine(targetDir, fn));
        }
Exemple #4
0
        /// <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);
                    }
                }
            }
        }
Exemple #5
0
 /// <summary>
 /// Write the specified message to the memory stream
 /// </summary>
 /// <param name="conn">The connector that received the message</param>
 /// <param name="ms">The memory stream</param>
 /// <param name="msg">The message</param>
 void WriteMessageToStream(IFormattedConnector conn, IGraphable msg, MemoryStream ms)
 {
     //var fmtr = conn.Formatter.Clone() as IStructureFormatter;
     conn.Formatter.Graph(ms, msg);
     ms.Flush();
     ms.Seek(0, SeekOrigin.Begin);
 }
        /// <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());
        }
        private static XmlDocument Serialize(IGraphable graph)
        {
            using (var ms = new MemoryStream())
                using (var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings {
                    Indent = true
                }))
                    using (var xsw = new XmlStateWriter(xmlWriter))
                    {
                        var structureFormatter = CreateStructureFormater();
                        xsw.WriteStartElement("ClinicalDocument", "urn:hl7-org:v3");
                        xsw.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI);
                        xsw.WriteAttributeString("xmlns", null, null, "urn:hl7-org:v3");
                        xsw.WriteAttributeString("xmlns", "custom", null, CustomNamespace);
                        xsw.WriteAttributeString("xsi", "type", XmlIts1Formatter.NS_XSI, "custom:ClinicalDocument");

                        structureFormatter.Graph(xsw, graph);
                        xsw.Close();
                        ms.Seek(0, SeekOrigin.Begin);
                        Debug.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
                        using (var reader = new XmlTextReader(ms))
                        {
                            var result = new XmlDocument();
                            result.Load(reader);
                            return(result);
                        }
                    }
        }
        /// <summary>
        /// Send a <paramref name="request "/>on the specified <paramref name="connector"/>
        /// and await a response
        /// </summary>
        public IGraphable SendReceive(ISendReceiveConnector connector, IGraphable request)
        {
            // Ensure the connector is open
            if (!connector.IsOpen())
            {
                connector.Open();
            }

            // Send the request
            ISendResult sendResult = connector.Send(request);

            // Was the send successful?
            if (sendResult.Code != ResultCode.Accepted &&
                sendResult.Code != ResultCode.AcceptedNonConformant)
            {
                return(null);
            }

            // Await the response
            IReceiveResult receiveResult = connector.Receive(sendResult);

            // Debug information
            #if DEBUG
            foreach (var itm in receiveResult.Details)
            {
                Trace.WriteLine(String.Format("{0}: {1} @ {2}", itm.Type, itm.Message, itm.Location));
            }
            #endif
            // Structure
            return(receiveResult.Structure);
        }
        public ResultCode GraphObject(XmlWriter s, IGraphable o)
        {
            var result = Graph(s, o);

            this.Details = result.Details;
            return(result.Code);
        }
        /// <summary>
        /// Send a <paramref name="request "/>on the specified <paramref name="connector"/>
        /// and await a response
        /// </summary>
        public IGraphable SendReceive(ISendReceiveConnector connector, IGraphable request)
        {

            // Ensure the connector is open
            if (!connector.IsOpen())
                connector.Open();

            // Send the request
            ISendResult sendResult = connector.Send(request);

            // Was the send successful?
            if (sendResult.Code != ResultCode.Accepted &&
                sendResult.Code != ResultCode.AcceptedNonConformant)
                return null;

            // Await the response
            IReceiveResult receiveResult = connector.Receive(sendResult);

            // Debug information
            #if DEBUG
            foreach (var itm in receiveResult.Details)
                Trace.WriteLine(String.Format("{0}: {1} @ {2}", itm.Type, itm.Message, itm.Location));
            #endif
            // Structure
            return receiveResult.Structure;

        }
Exemple #11
0
        public MARC.Everest.Interfaces.IGraphable HandleMessageReceived(object sender, MARC.Everest.Connectors.UnsolicitedDataEventArgs e, MARC.Everest.Connectors.IReceiveResult receivedMessage)
        {
            IGraphable response = null;

            if (receivedMessage.Structure is PRPA_IN201301UV02) // Activates the patient record
            {
                response = HandlePatientRegistryRecordAdded(e, receivedMessage);
            }
            else if (receivedMessage.Structure is PRPA_IN201302UV02) // Revises the patient record
            {
                response = HandlePatientRegistryRecordRevised(e, receivedMessage);
            }
            else if (receivedMessage.Structure is PRPA_IN201304UV02)
            {
                response = HandlePatientRegistryDuplicatesResolved(e, receivedMessage);
            }
            else if (receivedMessage.Structure is PRPA_IN201309UV02)
            {
                response = PatientRegistryGetIdentifiers(e, receivedMessage);
            }
            else
            {
                var msgr = new NotSupportedMessageReceiver();
                msgr.Context = this.Context;
                response     = msgr.HandleMessageReceived(sender, e, receivedMessage);
            }

            return(response);
        }
        /// <summary>
        /// Graphs object <paramref name="o"/> onto <paramref name="s"/>
        /// </summary>
        /// <param name="s">The stream to graph to</param>
        /// <param name="o">The object to graph</param>
        /// <returns>A formatter graphing result</returns>
        public IFormatterGraphResult Graph(XmlWriter s, IGraphable o)
        {
            if (o == null)
            {
                return(new DatatypeR2FormatterGraphResult(ResultCode.Accepted, null, this.ValidateConformance));
            }


            try
            {
                IDatatypeFormatter formatter = GetFormatter(o.GetType());

                if (formatter == null)
                {
                    return(new DatatypeR2FormatterGraphResult(ResultCode.NotAvailable, new IResultDetail[] {
                        new NotImplementedResultDetail(ResultDetailType.Error, String.Format("Could not find formatter for '{0}'", o.GetType().FullName), null)
                    }, this.ValidateConformance));
                }

                // Set the host
                formatter.Host = (IXmlStructureFormatter)(this.Host ?? this);

                var result = new DatatypeR2FormatterGraphResult(ResultCode.Accepted, null, this.ValidateConformance);

                formatter.Graph(s, o, result);

                return(result);
            }
            catch (Exception e)
            {
                return(new DatatypeR2FormatterGraphResult(ResultCode.Error, new IResultDetail[] {
                    new ResultDetail(ResultDetailType.Error, e.Message, s.ToString(), e)
                }, this.ValidateConformance));
            }
        }
Exemple #13
0
 /// <summary>
 /// Graph the object
 /// </summary>
 /// <param name="s">The stream to graph to</param>
 /// <param name="o">The IGraphable object to graph</param>
 /// <returns>The result of the operation</returns>
 public ResultCode GraphObject(Stream s, IGraphable o)
 {
     // Everest 1.0 changed the way formatters work so this method really only
     // exists to be backwards compatible
     var result = Graph(s, o);
     this.Details = result.Details;
     return result.Code;
 }
Exemple #14
0
        /// <summary>
        /// Graph the object
        /// </summary>
        /// <param name="s">The stream to graph to</param>
        /// <param name="o">The IGraphable object to graph</param>
        /// <returns>The result of the operation</returns>
        public ResultCode GraphObject(Stream s, IGraphable o)
        {
            // Everest 1.0 changed the way formatters work so this method really only
            // exists to be backwards compatible
            var result = Graph(s, o);

            this.Details = result.Details;
            return(result.Code);
        }
Exemple #15
0
        /// <summary>
        /// Illustrates formatting a message
        /// </summary>
        private static void FormatInstance(IGraphable message)
        {
            Console.WriteLine("Formatting...");

            // We'll indent the output
            XmlStateWriter xw = new XmlStateWriter(XmlWriter.Create(Console.OpenStandardOutput(), new XmlWriterSettings() { Indent = true }));
            m_formatter.Graph(xw, message);
            xw.Flush();
        }
Exemple #16
0
        /// <summary>
        /// Format a data type into a string in a localisation namespace
        /// </summary>
        /// <param name="dataType">The data type to format</param>
        /// <param name="elementName">The name of the element</param>
        public static void SerialiseDataType(IGraphable dataType, XmlWriter xmlWriter, string elementName, string localNamespace)
        {
            if (dataType != null)
            {
                xmlWriter.WriteStartElement(elementName, localNamespace);

                DatatypeFormatter ft = new DatatypeFormatter(DatatypeFormatterCompatibilityMode.ClinicalDocumentArchitecture);
                ft.GraphObject(xmlWriter, dataType);
                xmlWriter.WriteEndElement();
            }
        }
Exemple #17
0
        /// <summary>
        /// Format a data type into a string in a localisation namespace
        /// </summary>
        /// <param name="dataType">The data type to format</param>
        /// <param name="elementName">The name of the element</param>
        public static void SerialiseDataType(IGraphable dataType, XmlWriter xmlWriter, string elementName, string localNamespace)
        {
            if (dataType != null)
            {
                xmlWriter.WriteStartElement(elementName, localNamespace);

                DatatypeFormatter ft = new DatatypeFormatter(DatatypeFormatterCompatibilityMode.ClinicalDocumentArchitecture);
                ft.GraphObject(xmlWriter, dataType);
                xmlWriter.WriteEndElement();
            }
        }
        private void AddQuestionToReport(Question question)
        {
            // Make sure that the question point to its reference when available.
            if (question is ReferenceQuestion referenceQuestion)
            {
                question = referenceQuestion.Question;
            }

            IGraphable converter = _graphFactory.GetConverter(question.GraphType);

            if (converter == null && !(question is UploadPictureQuestion || question is StringQuestion))
            {
                return;
            }

            if (question is UploadPictureQuestion || question is StringQuestion)
            {
                Controls.Add(CreateLabel(question.Contents));
                AddAnswers(question.Answers);

                return;
            }

            List <GraphableSeries> chartValues = converter.TypeToChart(question);

            if (chartValues.Count < 1)
            {
                return;
            }

            Control lineControl = question.GraphType switch
            {
                GraphType.Line => new LineChartControl(chartValues),
                GraphType.Pie => new PieChartControl(chartValues),
                GraphType.Column => new ColumnChartControl(chartValues),
                _ => new Control()
            };

            lineControl.Height = 300;
            lineControl.HorizontalContentAlignment = HorizontalAlignment.Stretch;

            Controls.Add(CreateLabel(question.Contents));
            Controls.Add(lineControl);
            Controls.Add(new TextBox
            {
                Height        = 150,
                Width         = 700,
                Margin        = new Thickness(10),
                AcceptsReturn = true,
                AcceptsTab    = true,
                TextWrapping  = TextWrapping.Wrap
            });
        }
Exemple #19
0
        /// <summary>
        /// Format a data type into a string in a localisation namespace
        /// </summary>
        /// <param name="dataType">The data type to format</param>
        /// <param name="elementName">The name of the element</param>
        public static void SerialiseDataType(IGraphable dataType, XmlWriter xmlWriter, string elementName, string localNamespace)
        {
            if (dataType != null)
            {
                xmlWriter.WriteStartElement(elementName, localNamespace);
                Formatter fmtr = new Formatter();
                fmtr.GraphAides.Add(typeof(MARC.Everest.Formatters.XML.Datatypes.R1.Formatter));
                fmtr.GraphObject(xmlWriter, dataType);

                xmlWriter.WriteEndElement();
            }
        }
Exemple #20
0
        /// <summary>
        /// Illustrates formatting a message
        /// </summary>
        private static void FormatInstance(IGraphable message)
        {
            Console.WriteLine("Formatting...");

            // We'll indent the output
            XmlStateWriter xw = new XmlStateWriter(XmlWriter.Create(Console.OpenStandardOutput(), new XmlWriterSettings()
            {
                Indent = true
            }));

            m_formatter.Graph(xw, message);
            xw.Flush();
        }
Exemple #21
0
 /// <summary>
 /// Default message
 /// </summary>
 /// <returns></returns>
 public MARC.Everest.RMIM.CA.R020402.Interactions.MCCI_IN000002CA Anything(IGraphable request)
 {
     return(new MARC.Everest.RMIM.CA.R020402.Interactions.MCCI_IN000002CA(
                Guid.NewGuid(),
                DateTime.Now,
                ResponseMode.Immediate,
                MCCI_IN000002CA.GetInteractionId(),
                MCCI_IN000002CA.GetProfileId(),
                ProcessingID.Production,
                AcknowledgementCondition.Never,
                new Receiver(
                    new TEL()
     {
         NullFlavor = NullFlavor.NoInformation
     },
                    new Device2(
                        new II()
     {
         NullFlavor = NullFlavor.NoInformation
     }
                        )
                    ),
                new Sender(
                    new TEL(OperationContext.Current.Channel.LocalAddress.Uri.ToString()),
                    new Device1(
                        new II("1.2.3.4", "1234"),
                        "Sample Service",
                        "A sample service",
                        null,
                        "Mohawk College of Applied Arts and Technology",
                        "Everest"
                        )
                    ),
                new Acknowledgement(
                    AcknowledgementType.ApplicationAcknowledgementAccept,
                    new TargetMessage()
     {
         NullFlavor = NullFlavor.NoInformation
     },
                    new AcknowledgementDetail(
                        AcknowledgementDetailType.Information,
                        AcknowledgementDetailCode.InternalSystemError,
                        String.Format("You just used the Everest Serializer! Received a '{0}'", request.GetType().Name),
                        null
                        )
                    )
                ));
 }
Exemple #22
0
        /// <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());
        }
        /// <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);
        }
        internal static void XmlIsEquivalentAndDeserializable(string expectedXml, IGraphable actualXml)
        {
            XmlDocument e = new XmlDocument(),
                        a = Serialize(actualXml);

            e.LoadXml(expectedXml);
            R2SerializationHelper.XmlIsEquivalent(e.DocumentElement, a.DocumentElement);
            R2SerializationHelper.XmlIsEquivalent(a.DocumentElement, e.DocumentElement);

            using (var xw = new XmlNodeReader(a))
            {
                var structureFormatter = CreateStructureFormater();

                var document = structureFormatter.Parse(xw, typeof(RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument));
                Assert.AreEqual(ResultCode.Accepted, document.Code);
            }
        }
Exemple #25
0
        public MARC.Everest.Interfaces.IGraphable HandleMessageReceived(object sender, MARC.Everest.Connectors.UnsolicitedDataEventArgs e, MARC.Everest.Connectors.IReceiveResult receivedMessage)
        {
            IGraphable response = null;

            if (receivedMessage.Structure is QUQI_IN000003UV01)
            {
                response = ProcessQueryContinuation(sender, e, receivedMessage);
            }

            // Last ditch effort to create a response
            if (response == null)
            {
                response = new NotSupportedMessageReceiver()
                {
                    Context = this.Context
                }
            }
Exemple #26
0
        /// <summary>
        /// Handle a PDQ message
        /// </summary>
        public MARC.Everest.Interfaces.IGraphable HandleMessageReceived(object sender, MARC.Everest.Connectors.UnsolicitedDataEventArgs e, MARC.Everest.Connectors.IReceiveResult receivedMessage)
        {
            IGraphable response = null;

            if (receivedMessage.Structure is PRPA_IN201305UV02) // Activates the patient record
            {
                response = HandleQueryPatientDemographics(e, receivedMessage);
            }

            if (response == null)
            {
                var msgr = new NotSupportedMessageReceiver();
                msgr.Context = this.Context;
                response     = msgr.HandleMessageReceived(sender, e, receivedMessage);
            }

            return(response);
        }
Exemple #27
0
 /// <summary>
 /// Default message
 /// </summary>
 /// <returns></returns>
 public MARC.Everest.RMIM.CA.R020402.Interactions.MCCI_IN000002CA Anything(IGraphable request)
 {
     
     return new MARC.Everest.RMIM.CA.R020402.Interactions.MCCI_IN000002CA(
         Guid.NewGuid(),
         DateTime.Now,
         ResponseMode.Immediate,
         MCCI_IN000002CA.GetInteractionId(),
         MCCI_IN000002CA.GetProfileId(),
         ProcessingID.Production,
         AcknowledgementCondition.Never,
         new Receiver(
             new TEL() { NullFlavor = NullFlavor.NoInformation },
             new Device2(
                 new II() { NullFlavor = NullFlavor.NoInformation }
             )
         ),
         new Sender(
             new TEL(OperationContext.Current.Channel.LocalAddress.Uri.ToString()),
             new Device1(
                 new II("1.2.3.4", "1234"),
                 "Sample Service",
                 "A sample service",
                 null,
                 "Mohawk College of Applied Arts and Technology",
                 "Everest"
             )
         ),
         new Acknowledgement(
             AcknowledgementType.ApplicationAcknowledgementAccept,
             new TargetMessage() { NullFlavor = NullFlavor.NoInformation },
             new AcknowledgementDetail(
                 AcknowledgementDetailType.Information,
                 AcknowledgementDetailCode.InternalSystemError,
                 String.Format("You just used the Everest Serializer! Received a '{0}'", request.GetType().Name),
                 null
             )
         )
     );
             
             
 }
        /// <summary>
        /// Serialize as a string
        /// </summary>
        internal static String SerializeAsString(IGraphable graph)
        {
            DatatypeR2Formatter fmtr = new DatatypeR2Formatter();
            StringWriter        sw   = new StringWriter();
            XmlStateWriter      xsw  = new XmlStateWriter(XmlWriter.Create(sw, new XmlWriterSettings()
            {
                Indent = true
            }));

            xsw.WriteStartElement("test", "urn:hl7-org:v3");
            xsw.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
            var result = fmtr.Graph(xsw, graph);

            xsw.WriteEndElement();
            xsw.Flush();
            sw.Flush();
            System.Diagnostics.Trace.WriteLine(sw.ToString());
            Assert.AreEqual(ResultCode.Accepted, result.Code);
            return(sw.ToString());
        }
        /// <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()));
        }
Exemple #30
0
 /// <summary>
 /// Graph object <paramref name="o"/> onto stream <paramref name="s"/>
 /// </summary>
 public IFormatterGraphResult Graph(Stream s, IGraphable o)
 {
     try
     {
         BinaryFormatter fmt = new BinaryFormatter();
         fmt.Serialize(s, o);
         return(new BinaryFormatterGraphResult()
         {
             Code = ResultCode.Accepted,
             Details = new IResultDetail[0]
         });
     }
     catch (Exception e)
     {
         return(new BinaryFormatterGraphResult() // Invalid result
         {
             Details = new IResultDetail[] {
                 new ResultDetail(ResultDetailType.Error, e.Message, e)
             },
             Code = ResultCode.Error
         });
     }
 }
        /// <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()));
            }
        }
 //DOC: Documentation Required
 /// <summary>
 /// 
 /// </summary>
 /// <param name="message"></param>
 /// <param name="offender"></param>
 public MessageValidationException(string message, IGraphable offender)
     : base(message)
 {
     this.Offender = offender;
 }
Exemple #33
0
        /// <summary>
        /// Graphs object <paramref name="o"/> onto stream <paramref name="s"/>
        /// </summary>
        /// <param name="s">The stream to which <paramref name="o"/> is to be graphed</param>
        /// <param name="o">The object to be graphed</param>
        /// <returns>A <see cref="T:MARC.Everest.Formatters.XML.ITS1.Its1FormatterGraphResult"/> structure contianing the 
        /// results of formatting</returns>
        /// <seealso cref="F:Graph(System.Xml.XmlWriter,MARC.Everest.Interfaces.IGraphable)"/>
        public IFormatterGraphResult Graph(Stream s, IGraphable o)
        {
            ThrowIfDisposed();

            XmlWriter xwtr = XmlWriter.Create(s);
            XmlStateWriter xw = new XmlStateWriter(xwtr);

            if (o == null)
                return new XmlIts1FormatterGraphResult(ResultCode.AcceptedNonConformant, null);


            //TODO: Length will never be less than 0 so the logic should be > 0 instead of != 0.
            bool needsRoot = o.GetType().GetCustomAttributes(typeof(InteractionAttribute), true).Length == 0;
            if (needsRoot)
            {
                object[] sa = o.GetType().GetCustomAttributes(typeof(StructureAttribute), true);
                needsRoot = sa.Length == 0 || !(sa[0] as StructureAttribute).IsEntryPoint;
                if (needsRoot)
                {
                    xw.WriteStartElement(o.GetType().FullName, "urn:hl7-org:v3");
                    xw.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI);

                }

            }

            // Determine if this is not an interaction
            var result = Graph(xw, o);

            if (needsRoot)
                xw.WriteEndElement();

            xw.Flush();
            return result;
        }
Exemple #34
0
        public virtual void WriteNullFlavorUtil(XmlWriter s, IGraphable nullFlavor)
        {
            ThrowIfDisposed();

            if((this.Settings & SettingsType.SuppressXsiNil) == 0)
                s.WriteAttributeString("xsi", "nil", XmlIts1Formatter.NS_XSI, "true");
            s.WriteAttributeString("nullFlavor", Util.ToWireFormat(nullFlavor));
        }
        /// <summary>
        /// Write a value as an element
        /// </summary>
        private IFormatterGraphResult WriteValueAsElement(XmlWriter s, String element, IGraphable value, Type expectedType, params KeyValuePair <String, String>[] attrs)
        {
            s.WriteStartElement(element, "urn:hl7-org:v3");

            // Value value xsi type
            if (expectedType != null && value.GetType() != expectedType)
            {
                s.WriteAttributeString("xsi", "type", DatatypeFormatter.NS_XSI, Util.CreateXSITypeName(value.GetType()));
            }

            if (attrs != null)
            {
                foreach (var attr in attrs)
                {
                    s.WriteAttributeString(attr.Key, attr.Value);
                }
            }

            var hostResult = Host.Graph(s, value);

            s.WriteEndElement();
            return(hostResult);
        }
Exemple #36
0
 /// <summary>
 /// Graph <paramref name="o"/> onto <paramref name="s"/>
 /// </summary>
 public IFormatterGraphResult Graph(System.IO.Stream s, IGraphable o)
 {
     return new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.Rejected, new IResultDetail[] {
         new NotImplementedResultDetail(ResultDetailType.Error, "Can't use the datatypes R1 formatter on a stream", null)
     }, this.ValidateConformance);
 }
Exemple #37
0
        /// <summary>
        /// Graphs object <paramref name="o"/> onto <paramref name="s"/>
        /// </summary>
        /// <param name="s">The stream to graph to</param>
        /// <param name="o">The object to graph</param>
        /// <returns>A formatter graphing result</returns>
        public IFormatterGraphResult Graph(XmlWriter s, IGraphable o)
        {
            if (o == null)
                return new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.Accepted, null, this.ValidateConformance);

            try
            {
                IDatatypeFormatter formatter = GetFormatter(o.GetType());

                if (formatter == null)
                    return new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.NotAvailable, new IResultDetail[] {
                        new NotImplementedResultDetail(ResultDetailType.Error, String.Format("Could not find formatter for '{0}'", o.GetType().FullName), null)
                    }, this.ValidateConformance);

                // Set the host
                formatter.Host = (IXmlStructureFormatter)(this.Host ?? this);

                var result = new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.Accepted, null, this.ValidateConformance);

                formatter.Graph(s, o, result);

                return result;
            }
            catch (Exception e)
            {
                return new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.Error, new IResultDetail[] {
                    new ResultDetail(ResultDetailType.Error, e.Message, s.ToString(), e)
                }, this.ValidateConformance);
            }
        }
 /// <summary>
 /// Creates a new instance of the VocabularyException
 /// </summary>
 /// <param name="message">The textual message of the exception</param>
 /// <param name="offender">The <see cref="T:MARC.Everest.Interfaces.IGrapable"/> instance which caused the exception to be thrown</param>
 /// <param name="innerException">The exception that caused this exception to be thrown</param>
 public VocabularyException(string message, Exception innerException, IGraphable offender) : base(message, innerException, offender) { }
 /// <summary>
 /// Creates a new instance of the VocabularyException
 /// </summary>
 /// <param name="message">The textual message describing the exception</param>
 /// <param name="mnemonic">The code mnemonic that caused the vocabulary exception to be thrown</param>
 /// <param name="codeSet">The code set from which the <paramref name="mnemonic"/> was drawn</param>
 /// <param name="offender">The <see cref="T:MARC.Everest.Interfaces.IGraphable"/> instance which caused the exception to be thrown</param>
 public VocabularyException(string message, string mnemonic, string codeSet, IGraphable offender)
     : base(message, offender)
 {
     this.Mnemonic = mnemonic;
     this.CodeSet  = codeSet;
 }
 /// <summary>
 /// Graph <paramref name="o"/> onto <paramref name="s"/>
 /// </summary>
 public IFormatterGraphResult Graph(System.IO.Stream s, IGraphable o)
 {
     return(new DatatypeFormatterGraphResult(this.CompatibilityMode, ResultCode.Rejected, new IResultDetail[] {
         new NotImplementedResultDetail(ResultDetailType.Error, "Can't use the datatypes R1 formatter on a stream", null)
     }, this.ValidateConformance));
 }
Exemple #41
0
 /// <summary>
 /// Graph object <paramref name="o"/> onto stream <paramref name="s"/>
 /// </summary>
 public IFormatterGraphResult Graph(Stream s, IGraphable o)
 {
     try
     {
         BinaryFormatter fmt = new BinaryFormatter();
         fmt.Serialize(s, o);
         return new BinaryFormatterGraphResult()
         {
             Code = ResultCode.Accepted,
             Details = new IResultDetail[0]
         };
     }
     catch (Exception e)
     {
         return new BinaryFormatterGraphResult() // Invalid result
         {
             Details = new IResultDetail[] {
                     new ResultDetail(ResultDetailType.Error, e.Message, e)
                     },
             Code = ResultCode.Error
         };
     }
 }
Exemple #42
0
        /// <summary>
        /// Write a value as an element
        /// </summary>
        private IFormatterGraphResult WriteValueAsElement(XmlWriter s, String element, IGraphable value, Type expectedType, params KeyValuePair<String, String>[] attrs)
        {
            s.WriteStartElement(element, "urn:hl7-org:v3");

            // Value value xsi type
            if (expectedType != null && value.GetType() != expectedType)
                s.WriteAttributeString("xsi", "type", DatatypeFormatter.NS_XSI, Util.CreateXSITypeName(value.GetType()));

            if (attrs != null)
                foreach (var attr in attrs)
                    s.WriteAttributeString(attr.Key, attr.Value);

            var hostResult = Host.Graph(s, value);
            s.WriteEndElement();
            return hostResult;
        }
Exemple #43
0
            public void Work(object state)
            {
                IGraphable data                 = (IGraphable)state;
                MessageQueueTransaction tx      = null;
                IFormatterGraphResult   gResult = null;

                try
                {
                    // Create a message and prepare for sending
                    Message msg = new Message();
                    Result = new MsmqSendResult();

                    // Format and prepare result
                    gResult        = Formatter.Graph(msg.BodyStream, data);
                    Result.Code    = gResult.Code;
                    Result.Details = gResult.Details;

                    // Accepted messages get sent
                    if (Result.Code == ResultCode.Accepted || Result.Code == ResultCode.AcceptedNonConformant)
                    {
                        // Create a transaction if the queue is transactional
                        if (Queue.Transactional)
                        {
                            tx = new MessageQueueTransaction();
                            tx.Begin();
                        }

                        // Publish
                        if (tx != null)
                        {
                            Queue.Send(msg, tx);
                        }
                        else
                        {
                            Queue.Send(msg);
                        }

                        // Commit the transaction
                        if (tx != null)
                        {
                            tx.Commit();
                        }
                    }
                }
                catch (MessageValidationException e)
                {
                    Result.Code = ResultCode.Rejected;
                    List <IResultDetail> dtl = new List <IResultDetail>(new IResultDetail[] { new ResultDetail(ResultDetailType.Error, e.Message, e) });
                    dtl.AddRange(gResult.Details ?? new IResultDetail[0]);
                    Result.Details = dtl.ToArray();
                    if (tx != null && tx.Status == MessageQueueTransactionStatus.Pending)
                    {
                        tx.Abort();
                    }
                }
                catch (FormatException e)
                {
                    Result.Code    = ResultCode.Rejected;
                    Result.Details = new IResultDetail[] { new ResultDetail(ResultDetailType.Error, e.Message, e) };
                    if (tx != null && tx.Status == MessageQueueTransactionStatus.Pending)
                    {
                        tx.Abort();
                    }
                }
                catch (Exception e)
                {
                    Result.Code    = ResultCode.Error;
                    Result.Details = new IResultDetail[] { new ResultDetail(ResultDetailType.Error, e.Message, e) };
                    if (tx != null && tx.Status == MessageQueueTransactionStatus.Pending)
                    {
                        tx.Abort();
                    }
                }
                finally
                {
                }

                // Fire completed event
                if (Completed != null)
                {
                    Completed(this);
                }
            }
 public ResultCode GraphObject(XmlWriter s, IGraphable o)
 {
     var result = Graph(s, o);
     this.Details = result.Details;
     return result.Code;
 }
Exemple #45
0
        /// <summary>
        /// Graphs <paramref name="o"/> onto the <see cref="T:System.Xml.XmlWriter"/> <paramref name="s"/>
        /// </summary>
        /// <param name="s">The <see cref="T:System.Xml.XmlWriter"/> that should be used to graph the object</param>
        /// <param name="o">The <see cref="T:MARC.Everest.Interfaces.IGraphable"/> that should be graphed</param>
        /// <returns>A <see cref="T:MARC.Everest.Formatters.XML.ITS1.Its1FormatterGraphResult"/> containing the results of the graph</returns>
        /// <remarks>
        /// <para>
        /// This particular overload of the Graph method can be used to graph objects into a <see cref="T:System.Xml.XmlWriter"/> and can provide
        /// an opportunity to use Everest as an assistant (or XmlSerializerSurrogate) for more complex systems like WCF.
        /// </para>
        /// <example>
        /// <code lang="cs" title="Using Everest as a Serializer Assistant">
        /// <![CDATA[
        /// StringWriter sw = new StringWriter();
        /// XmlWriter writer = XmlWriter.Create(sw);
        /// writer.WriteStartElement("hello", "urn:my-org");
        /// 
        /// Formatter f = new Formatter();
        /// f.GraphAides.Add(typeof(MARC.Everest.Formatters.XML.DataTypes.R1.Formatter));
        /// f.ValidateConformance = false;
        /// f.Graph(writer, new MCCI_IN000002CA());
        /// 
        /// writer.WriteEndElement();
        /// writer.Close();
        /// Console.WriteLine(sw.ToString());
        /// 
        /// ]]>
        /// </code>
        /// outputs
        /// <code lang="xml" title="Output of example">
        /// <![CDATA[
        /// <hello xmlns="urn:my-org">
        ///     <MCCI_IN000002CA xmlns="urn:hl7-org:v3"/>
        /// </hello>
        /// ]]>
        /// </code>
        /// </example>
        /// <para>
        /// When using this method, it is recommended that you pass a <see cref="T:MARC.Everest.Xml.XmlStateWriter"/> as it 
        /// will allow the formatter to give additional location information when reporting issues.
        /// </para>
        /// </remarks>
        public IFormatterGraphResult Graph(XmlWriter s, IGraphable o)
        {
            ThrowIfDisposed();

            var resultContext = new XmlIts1FormatterGraphResult(ResultCode.Accepted, null);

            IGraphable context = null;
            // Clear out result cache
            if (s.WriteState == WriteState.Start || String.IsNullOrEmpty(s.ToString()) || o is IInteraction)
                context = o;

            if (!(s is XmlStateWriter))
                s = new XmlStateWriter(s);

            if (o == null)
                resultContext.Code = ResultCode.AcceptedNonConformant;
            else
            {
                GraphObject(s, o, o.GetType(), context, resultContext);
                resultContext.Code = CalculateResultCode(resultContext.Details);
            }

            return resultContext;
        }
        internal static void XmlIsEquivalentAndDeserializable(string expectedXml, IGraphable actualXml)
        {
            XmlDocument e = new XmlDocument(),
                a = Serialize(actualXml);
            e.LoadXml(expectedXml);
            R2SerializationHelper.XmlIsEquivalent(e.DocumentElement, a.DocumentElement);
            R2SerializationHelper.XmlIsEquivalent(a.DocumentElement, e.DocumentElement);

            using (var xw = new XmlNodeReader(a))
            {
                var structureFormatter = CreateStructureFormater();
                
                var document = structureFormatter.Parse(xw, typeof(RMIM.UV.CDAr2.POCD_MT000040UV.ClinicalDocument));
                Assert.AreEqual(ResultCode.Accepted, document.Code);
            }
        }
Exemple #47
0
        public void ValidateHelper(XmlWriter s, IGraphable o, ITypeFormatter formatter, XmlIts1FormatterGraphResult resultContext)
        {
            IResultDetail[] details = null;

            if (ValidateConformance && (!formatter.Validate(o, s.ToString(), out details)))
                resultContext.AddResultDetail(details.Length > 0 ? details : new IResultDetail[] { new DatatypeValidationResultDetail(ValidateConformance ? ResultDetailType.Error : ResultDetailType.Warning, o.GetType().ToString(), s.ToString()) });
        }
Exemple #48
0
        public System.ServiceModel.Channels.Message ProcessInboundMessage(System.ServiceModel.Channels.Message m)
        {
            #if DEBUG
            Trace.TraceInformation("Received message on transport...");
            #endif

            if (ListenConnector == null && OperationContext.Current.Host is WcfServiceHost)
            {
                ListenConnector = (OperationContext.Current.Host as WcfServiceHost).ConnectorHost;
            }

            if (ListenConnector != null) // In process
            {
                // Is this channel one way or two way?
                if (!(OperationContext.Current.Channel is IOutputChannel)) // Input only
                {
                    return(null);
                }

                #if DEBUG
                Trace.TraceInformation("Message handoff to WcfServerConnector completed");
                #endif

                WcfSendResult processResult = ListenConnector.ProcessMessage(m);
                Message       retVal        = null;

                // There is an error, so the return value must be a fault!
                if (processResult == null || processResult.Code != ResultCode.Accepted && processResult.Code != ResultCode.AcceptedNonConformant)
                {
                    // Web based context?
                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode        = System.Net.HttpStatusCode.InternalServerError;
                        WebOperationContext.Current.OutgoingResponse.StatusDescription = "Internal Server Error";
                    }

                    List <String> details = new List <string>();
                    if (processResult != null)
                    {
                        details = new List <String>();
                        foreach (var dtl in processResult.Details)
                        {
                            details.Add(dtl.Message); // Append details
                        }
                    }

                    if (processResult == null)
                    {
                        retVal = Message.CreateMessage(m.Version, MessageFault.CreateFault(FaultCode.CreateReceiverFaultCode(processResult.Code.ToString(), "http://marc.mohawkcollege.ca/hi"), new FaultReason("The receiver has constructed an invalid response that cannot be sent to the sender"), details), m.Headers.Action);
                    }
                    else
                    {
                        retVal = Message.CreateMessage(m.Version, MessageFault.CreateFault(FaultCode.CreateSenderFaultCode("EPIC", "http://marc.mohawkcollege.ca/hi"), new FaultReason("Catastrophic failure occurred in the WcfServer send pipeline. This usually occurs when the connector does not receive a message in the allocated amount of time"), details), m.Headers.Action);
                    }
                }
                else
                {
                    retVal = processResult.Message;

                    if (processResult.Headers != null)
                    {
                        retVal.Headers.Clear();
                        retVal.Headers.CopyHeadersFrom(processResult.Headers);
                    }
                }

                #if DEBUG
                Trace.TraceInformation("Message sent to client");
                #endif

                return(retVal);
            }
            else
            {
                // Get settings
                if (settings == null)
                {
                    settings = System.Web.Configuration.WebConfigurationManager.GetSection("marc.everest.connectors.wcf") as MARC.Everest.Connectors.WCF.Configuration.ConfigurationSection;
                }

                // Now format the message and pass it on ...
                MemoryStream         ms = new MemoryStream();
                System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms); // Write to message memory stream for classification matching
                m.WriteMessage(xw);
                xw.Flush();                                                // Flush the Xml Writer

                ms.Seek(0, SeekOrigin.Begin);                              // Seek to start
                XPathDocument  xpd = new XPathDocument(ms);                // load xpath document
                XPathNavigator xpn = xpd.CreateNavigator();

                IMessageReceiver receiver = null; // The receiver to use

                // Determine the receiver
                foreach (KeyValuePair <String, IMessageReceiver> kv in settings.Receiver)
                {
                    if (xpn.SelectSingleNode(kv.Key) != null)
                    {
                        receiver = kv.Value;
                        break;
                    }
                }

                // Was a receiver found?
                if (receiver == null)
                {
                    // Create a not implemented exception
                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotImplemented;
                    }
                    return(Message.CreateMessage(m.Version, MessageFault.CreateFault(FaultCode.CreateSenderFaultCode(
                                                                                         "NotImplemented", "http://marc.mohawkcollege.ca/hi"), new FaultReason("No receiver understands the request message.")),
                                                 m.Headers.Action));
                }

                // Create a streams for deserialization
                ms = new MemoryStream();
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.Indent = true;
                xw         = XmlWriter.Create(ms, xws);

                // Deserialize body
                WcfReceiveResult rcv = new WcfReceiveResult();
                try
                {
                    // Because of classification, we need to process this in a wierd way,
                    // Basically the formatter will classify the message based on the root element name
                    // it receives. Because a SOAP message's root isn't what we really want to process,
                    // the first child node under the 'body' must be passed to the xml writer
                    xpn.SelectSingleNode("//*[local-name() = 'Body']/child::node()").WriteSubtree(xw);
                    xw.Flush();
                    ms.Seek(0, SeekOrigin.Begin);

                    var serResult = settings.Formatter.Parse(ms);
                    rcv.Structure = serResult.Structure;
                    rcv.Details   = serResult.Details;
                    if (rcv.Details.Count() == 0)
                    {
                        rcv.Code = ResultCode.Accepted;
                    }
                    else
                    {
                        rcv.Code = ResultCode.AcceptedNonConformant;
                    }
                }
                catch (Exception e)
                {
                    rcv.Code    = ResultCode.Error;
                    rcv.Details = new IResultDetail[] { new ResultDetail(ResultDetailType.Error, e.Message, e) };
                }

                // Process on the receiver
                IGraphable obj = receiver.MessageReceived(rcv.Structure, rcv.Code, rcv.Details);

                // Graph this back
                XmlSerializerSurrogate surrogate = new XmlSerializerSurrogate((IXmlStructureFormatter)settings.Formatter);

                // Serialize the response
                Message result = Message.CreateMessage(m.Version, m.Headers.Action, obj, surrogate);

                // Validate
                surrogate.WriteObject(new MemoryStream(), obj);

                // Surrogate result code is acceptable?
                if (surrogate.ResultCode != ResultCode.Accepted && surrogate.ResultCode != ResultCode.AcceptedNonConformant)
                {
                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.StatusCode        = System.Net.HttpStatusCode.InternalServerError;
                        WebOperationContext.Current.OutgoingResponse.StatusDescription = "Internal Server Error";
                    }

                    List <string> details = new List <String>();
                    foreach (var itm in surrogate.Details)
                    {
                        details.Add(itm.Message); // Append details
                    }
                    return(Message.CreateMessage(m.Version, MessageFault.CreateFault(FaultCode.CreateReceiverFaultCode(surrogate.ResultCode.ToString(), "http://marc.mohawkcollege.ca/hi"), new FaultReason("The receiver has constructed an invalid response that cannot be returned to the sender"), details), m.Headers.Action));
                }
                else
                {
                    return(result);
                }
            }
        }
 /// <summary>
 /// Creates a new instance of the VocabularyException
 /// </summary>
 /// <param name="message">The textual message of the exception</param>
 /// <param name="offender">The <see cref="T:MARC.Everest.Interfaces.IGrapable"/> instance which caused the exception to be thrown</param>
 /// <param name="innerException">The exception that caused this exception to be thrown</param>
 public VocabularyException(string message, Exception innerException, IGraphable offender) : base(message, innerException, offender)
 {
 }
 /// <summary>
 /// Creates a new instance of the VocabularyException
 /// </summary>
 /// <param name="message">The textual message describing the exception</param>
 /// <param name="mnemonic">The code mnemonic that caused the vocabulary exception to be thrown</param>
 /// <param name="codeSet">The code set from which the <paramref name="mnemonic"/> was drawn</param>
 /// <param name="offender">The <see cref="T:MARC.Everest.Interfaces.IGraphable"/> instance which caused the exception to be thrown</param>
 public VocabularyException(string message, string mnemonic, string codeSet, IGraphable offender)
     : base(message, offender)
 {
     this.Mnemonic = mnemonic;
     this.CodeSet = codeSet;
 }
Exemple #51
0
        protected virtual void GraphObject(XmlWriter s, IGraphable o, Type useType, IGraphable context, XmlIts1FormatterGraphResult resultContext)
        {

            // Find the HL7 alias for the type and build the cache for the type
            string typeName = GetStructureName(useType);

            // Find a helper
            IXmlStructureFormatter ixsf = (IXmlStructureFormatter)this.GraphAides.Find(t => t.HandleStructure.Contains(typeName));

            // Does the helper graph aide have a handler?
            if (ixsf != null)
            {
                ixsf.Host = this;
                var rv = ixsf.Graph(s, o);

                resultContext.AddResultDetail(rv.Details);

                return;
            }

#if WINDOWS_PHONE
            ITypeFormatter formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            if (formatter == null)
                formatter = new ReflectFormatter();
#else
            ITypeFormatter formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            // Is there a formatter and if there is not a formatter 
            // can we create one?
            if (formatter == null && (Settings & SettingsType.UseGeneratorFormat) == SettingsType.UseGeneratorFormat)
                s_threadPool.QueueUserWorkItem((WaitCallback)delegate(object state)
                {
                    BuildCache(new Type[] { (Type)state });
                }, useType);
            // If there is no connector can we use reflection?
            if (formatter == null && (Settings & SettingsType.UseReflectionFormat) == SettingsType.UseReflectionFormat)
                formatter = new ReflectFormatter();
            else if (formatter == null && (Settings & SettingsType.UseGeneratorFormat) == SettingsType.UseGeneratorFormat)
            {
                s_threadPool.WaitOne();
                formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            }
#endif
            if(formatter == null)
                throw new InvalidOperationException(string.Format("Couldn't format '{0}' at {1}, verify formatter settings!", useType.FullName, s.ToString()));

            // Validate the instance
            formatter.Host = this;
            
            // Graph using helper
            formatter.Graph(s, o, context, resultContext);

        }
Exemple #52
0
        public AoACurve()
        {
            graphables.Clear();
            Vector2[] blank = new Vector2[0];
            graphables.Add(new LineGraph(blank)
            {
                Name = "Lift", YName = "Force", YUnit = "kN", StringFormat = "N0", Color = Color.green
            });
            graphables.Add(new LineGraph(blank)
            {
                Name = "Drag", YName = "Force", YUnit = "kN", StringFormat = "N0", Color = Color.green
            });
            graphables.Add(new LineGraph(blank)
            {
                Name = "Lift/Drag Ratio", YUnit = "", StringFormat = "F2", Color = Color.green
            });
            graphables.Add(new LineGraph(blank)
            {
                Name = "Lift Slope", YUnit = "m^2/°", StringFormat = "F3", Color = Color.green
            });
            IGraphable[] pitch = new IGraphable[] {
                new LineGraph(blank)
                {
                    Name = "Pitch Input (Wet)", YUnit = "", StringFormat = "F2", Color = Color.green
                },
                new LineGraph(blank)
                {
                    Name = "Pitch Input (Dry)", YUnit = "", StringFormat = "F2", Color = Color.yellow
                }
            };
            //graphables.Add(pitch[0]);
            //graphables.Add(pitch[1]);
            graphables.Add(new GraphableCollection(pitch)
            {
                Name = "Pitch Input"
            });
            IGraphable[] torque = new IGraphable[] {
                new LineGraph(blank)
                {
                    Name = "Torque (Wet)", YUnit = "kNm", StringFormat = "N0", Color = Color.green
                },
                new LineGraph(blank)
                {
                    Name = "Torque (Dry)", YUnit = "kNm", StringFormat = "N0", Color = Color.yellow
                }
            };
            //graphables.Add(torque[0]);
            //graphables.Add(torque[1]);
            graphables.Add(new GraphableCollection(torque)
            {
                Name = "Torque"
            });

            var e = graphables.GetEnumerator();

            while (e.MoveNext())
            {
                e.Current.XUnit   = "°";
                e.Current.XName   = "Angle of Attack";
                e.Current.Visible = false;
            }
        }
Exemple #53
0
        public virtual void WriteElementUtil(XmlWriter s, string namespaceUri, string elementName, IGraphable g, Type propType, IGraphable context, XmlIts1FormatterGraphResult resultContext)
        {
            ThrowIfDisposed();

            
            // Graph is nothing
            if (g == null)
                return;

            // Normalize
            if (g is INormalizable)
                g = (g as INormalizable).Normalize();

            // Write start of element
            s.WriteStartElement(elementName, namespaceUri);
            
            // JF: Output XSI:Type
            if (!g.GetType().Equals(propType) )
            {
                // TODO: This may cause issue when assigning a QSET to an R1 or
                //       SXPR to R2 instance as the XSI:TYPE will be inappropriately
                //       assigned.

                string xsiType = String.Empty;
                if (typeof(ANY).IsAssignableFrom(g.GetType()))
                {
                    xsiType += s.LookupPrefix("urn:hl7-org:v3");
                    if (!String.IsNullOrEmpty(xsiType))
                        xsiType += ":";
                    xsiType += Util.CreateXSITypeName(g.GetType());
                }
                else if (propType != null && g.GetType().Assembly.FullName != propType.Assembly.FullName)
                {
                    string typeName = this.CreateXSITypeName(g.GetType(), context != null ? context.GetType() : null, s as IXmlNamespaceResolver);

                    // If there is no different then don't output
                    if (typeName != String.Format("{0}.{1}", this.GetModelName(propType), this.GetStructureName(propType)))
                    {

                        lock (this.m_syncRoot)
                            if (!this.s_typeNameMaps.ContainsKey(typeName))
                                this.RegisterXSITypeName(typeName, g.GetType());
                    }
                    xsiType = typeName;
                }
                if(!String.IsNullOrEmpty(xsiType))
                    s.WriteAttributeString("xsi", "type", XmlIts1Formatter.NS_XSI, xsiType);

                //string xsdTypeName = String.Empty;
                //object[] sa = g.GetType().GetCustomAttributes(typeof(StructureAttribute), false);
                //if (sa.Length > 0 && (sa[0] as StructureAttribute).StructureType == StructureAttribute.StructureAttributeType.DataType)
                //    s.WriteAttributeString("xsi", "type", null, (sa[0] as StructureAttribute).Name);
            }

            // Result code of the
            GraphObject(s, g, g.GetType(), context, resultContext);
            s.WriteEndElement();
        }
        private string GenerateTargetFile(IGraphable data)
        {

            // Is this directory even open?
            if (!IsOpen())
                throw new InvalidOperationException("Can't call send operation before .Open is called!");

            string fn = targetFile;

            // Find a functiod (example: Guid/ID/etc...) that can be used to generate the name of the file
            if (targetFunctiod != null)
                fn = targetFunctiod(data).ToString();

            // Non overwrite, get a new fn (filename)
            string origFn = fn;
            int i = 0;
            while(System.IO.File.Exists(Path.Combine(targetDir, fn)) && !overwriteFile)
            {
                fn = string.Format("{0}.{1}", origFn, i);
                i++;
            }

            // Combine & return
            return Path.Combine(targetDir, fn);
        }