public void Can_Generate_Api_Xml()
        {
            //Arrange
            var expected = new XElement("StructureAttribute",
                                        new XAttribute("id", "46"),
                                        new XAttribute("name", "bar"),
                                        new XElement("StructureValue",
                                                     new XAttribute("langId", "10"),
                                                     new XAttribute("scope", "global"),
                                                     new XCData("foo")));

            var value = new StructureValue {
                LanguageId = 10, Value = "foo"
            };
            var attr = new StructureAttribute {
                DefinitionId = 46, Name = "bar", Values = new List <StructureValue> {
                    value
                }
            };

            //Act
            var actual = attr.ToAdsml();

            //Assert
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.ToString(), Is.EqualTo(expected.ToString()));
        }
Ejemplo n.º 2
0
        public void Can_Combine_All_Operations()
        {
            //Arrange
            var builder = new ModifyRequestBuilder();

            //Act
            builder.Context("/foo/bar")
            .ReturnNoAttributes()
            .FailOnError()
            .AddModification(Modifications.RemoveAttribute, SimpleAttribute.New(AttributeTypes.Integer, "objectId"))
            .AddModifications(() => new List <ModificationItem> {
                ModificationItem.New(
                    Modifications.AdvanceState, StructureAttribute.New(390, new StructureValue(10))
                    ),
                ModificationItem.New(
                    Modifications.RegressState, StructureAttribute.New(24, new StructureValue(10))
                    )
            })
            .ConfigureLookupControls()
            .ReturnAttributes(390, 24)
            .ReturnLanguages(10);

            var request = new BatchRequest(builder.Build());

            Console.WriteLine(builder.Build().ToAdsml().ToString());

            //Assert
            Assert.DoesNotThrow(() => builder.Build());
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
Ejemplo n.º 3
0
        public void Can_Generate_Api_Xml()
        {
            //Arrange
            string expected =
                new XElement("ModifyRequest",
                             new XAttribute("name", "/foo/bar"),
                             new XElement("ModificationItem",
                                          new XAttribute("operation", "addValue"),
                                          new XElement("AttributeDetails",
                                                       new XElement("StructureAttribute",
                                                                    new XAttribute("id", "31"),
                                                                    new XElement("StructureValue",
                                                                                 new XAttribute("langId", "10"),
                                                                                 new XAttribute("scope", "global"),
                                                                                 new XCData("foo")))))).ToString();

            //Act
            var modReq = new ModifyRequest("/foo/bar", new List <ModificationItem> {
                ModificationItem.New(
                    Modifications.AddValue,
                    StructureAttribute.New(31, new StructureValue(10, "foo"))
                    )
            });

            var actual  = modReq.ToAdsml();
            var request = new BatchRequest(modReq);

            Console.WriteLine(actual.ToString());

            //Assert
            Assert.That(actual.ToString(), Is.EqualTo(expected));
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
        /// <summary>
        /// Get formatter
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static IDatatypeFormatter GetFormatter(Type type)
        {
            // Get the struct attribute
            IDatatypeFormatter formatter = null;
            Type cType = type;

            // Find a structure attribute to format...
            while (formatter == null)
            {
                StructureAttribute sta = cType.GetCustomAttributes(typeof(StructureAttribute), true)[0] as StructureAttribute;

                // Find the object that we want to render
                Type formatterType = null;
                if (formatters.TryGetValue(sta.Name ?? "", out formatterType))
                {
                    formatter = (IDatatypeFormatter)formatterType.Assembly.CreateInstance(formatterType.FullName);
                }

                // Swap cType
                cType = cType.BaseType;
                if (cType == null)
                {
                    return(null);               // Not available
                }
            }

            // Populate the generic arguments
            formatter.GenericArguments = type.GetGenericArguments();


            return(formatter);
        }
        public void CanBuildCreateRequest()
        {
            //Arrange
            var builder = new CreateRequestBuilder();

            //Act
            builder
            .NewContextName("/foo/bar")
            .ObjectTypeToCreate("baz")
            .ReturnNoAttributes()
            .FailOnError()
            .UpdateIfExists()
            .AttributesToSet(
                StructureAttribute.New(215, new StructureValue(10, "169010"))
                )
            .ConfigureLookupControls()
            .ReturnAttributes(AttributeToReturn.WithName("Artikelnummer"))
            .ReturnLanguages(LanguageToReturn.WithLanguageId(10))
            .ConfigureReferenceHandling(
                ReferenceOptions.ReturnValuesOnly()
                );

            var request = new BatchRequest(builder.Build());

            //Assert
            Assert.That(builder.Build(), Is.Not.Null);
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates one instance of the Relation Object from the PropertyInfo object of the reflected class
        /// </summary>
        /// <param name="propInfo"></param>
        /// <returns></returns>
        public static Structure CreateStructureObject(Type structureType)
        {
            Structure result = new VSPlugin.Structure();

            StructureAttribute structAttribute = structureType.GetCustomAttribute <StructureAttribute>();


            result.Type       = structAttribute == null ? "object" : structAttribute.Type;
            result.Properties = new Dictionary <string, StructureProperty>();
            foreach (PropertyInfo pinfo in structureType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
            {
                PropertyAttribute propertyAttribute = pinfo.GetCustomAttribute <PropertyAttribute>();

                string            itemsType = "";
                StructureProperty structure = new StructureProperty();
                structure.Required = propertyAttribute == null ? false : propertyAttribute.Required;
                Structure includedStructure;
                structure.Type = Utility.HandleProperty(pinfo, out itemsType, out includedStructure);
                if (!string.IsNullOrEmpty(itemsType))
                {
                    structure.Items = new ArraySchema()
                    {
                        Type = itemsType
                    };
                }
                result.Properties.Add(pinfo.Name, structure);
            }

            return(result);
        }
        public void CanSetAttributesToBeCreatedWithParamsOverload()
        {
            //Act
            _builder.AttributesToSet(StructureAttribute.New(10, new StructureValue(10, "foo")));

            //Assert
            Assert.That(_builder.Attributes.Count(), Is.EqualTo(1));
        }
        public void Can_Instantiate_New_StructureAttribute()
        {
            //Act
            var sAttr = new StructureAttribute();

            //Assert
            Assert.That(sAttr, Is.Not.Null);
        }
        public void ToApiXml_Throws_ASVE_If_DefinitionId_And_Name_Are_Not_Set()
        {
            //Arrange
            var attr = new StructureAttribute();

            //Act
            attr.ToAdsml();
        }
        public void Can_Create_New_StructureAttribute_Using_Factory_Method_Providing_DefinitionId()
        {
            //Act
            var sa = StructureAttribute.New(10, new StructureValue(10, "bar"));

            //Assert
            Assert.That(sa.DefinitionId, Is.EqualTo(10));
            Assert.That(sa.Values.Count(), Is.EqualTo(1));
            Assert.That(sa.Values[0].Value, Is.EqualTo("bar"));
        }
Ejemplo n.º 11
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
            string inFile  = dataDir + "TH.pdf";
            string outFile = dataDir + "TH_out.pdf";
            string logFile = dataDir + "TH_out.xml";

            // Open document
            Document document = new Document(inFile);

            // Gets tagged content and root structure element
            ITaggedContent   taggedContent = document.TaggedContent;
            StructureElement rootElement   = taggedContent.RootElement;

            // Set title for tagged pdf document
            taggedContent.SetTitle("Document with images");

            foreach (FigureElement figureElement in rootElement.FindElements <FigureElement>(true))
            {
                // Set Alternative Text  for Figure
                figureElement.AlternativeText = "Figure alternative text (technique 2)";


                // Create and Set BBox Attribute
                StructureAttribute bboxAttribute = new StructureAttribute(AttributeKey.BBox);
                bboxAttribute.SetRectangleValue(new Rectangle(0.0, 0.0, 100.0, 100.0));

                StructureAttributes figureLayoutAttributes = figureElement.Attributes.GetAttributes(AttributeOwnerStandard.Layout);
                figureLayoutAttributes.SetAttribute(bboxAttribute);
            }

            // Move Span Element into Paragraph (find wrong span and paragraph in first TD)
            TableElement     tableElement   = rootElement.FindElements <TableElement>(true)[0];
            SpanElement      spanElement    = tableElement.FindElements <SpanElement>(true)[0];
            TableTDElement   firstTdElement = tableElement.FindElements <TableTDElement>(true)[0];
            ParagraphElement paragraph      = firstTdElement.FindElements <ParagraphElement>(true)[0];

            // Move Span Element into Paragraph
            spanElement.ChangeParentElement(paragraph);


            // Save document
            document.Save(outFile);



            // Checking PDF/UA Compliance for out document
            document = new Document(outFile);

            bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);

            Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
        }
        public void CanGenerateApiXmlWithLookupControl()
        {
            //Arrange
            var expected =
                new XElement("CreateRequest",
                             new XAttribute("name", "fooPath"),
                             new XAttribute("type", "fooObjectTypeName"),
                             new XElement("LookupControls",
                                          new XElement("AttributesToReturn",
                                                       new XElement("Attribute",
                                                                    new XAttribute("name", "fooAttributeName")))),
                             new XElement("AttributesToSet",
                                          new XElement("StructureAttribute",
                                                       new XAttribute("id", "215"),
                                                       new XAttribute("name", "fooAttributeName"),
                                                       new XElement("StructureValue",
                                                                    new XAttribute("langId", "10"),
                                                                    new XAttribute("scope", "global"),
                                                                    new XCData("fooValue")))));

            var value = new StructureValue {
                LanguageId = 10, Value = "fooValue"
            };
            var attribute = new StructureAttribute {
                DefinitionId = 215,
                Name         = "fooAttributeName",
                Values       = new List <StructureValue> {
                    value
                }
            };

            var lcb = new LookupControlBuilder();

            lcb.ReturnAttributes(AttributeToReturn.WithName("fooAttributeName"));
            var lc = lcb.Build();

            var create = new CreateRequest("fooObjectTypeName", "fooPath", null, attribute)
            {
                LookupControl = lc
            };

            //Act
            var actual  = create.ToAdsml();
            var request = new BatchRequest(create);

            Console.WriteLine(actual);

            //Assert
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.ToString(), Is.EqualTo(expected.ToString()));
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
        public void CanSetAttributesToBeCreatedWithListOverload()
        {
            //Arrange
            var builder    = new CreateRequestBuilder();
            var attributes = new List <StructureAttribute> {
                StructureAttribute.New(10, new StructureValue(10, "foo"))
            };

            //Act
            builder.AttributesToSet(attributes);

            //Assert
            Assert.That(builder.Attributes.Count(), Is.EqualTo(1));
        }
        public void CanGenerateApiXmlWithRequestFilters()
        {
            //Arrange
            var expected =
                new XElement("CreateRequest",
                             new XAttribute("name", "fooPath"),
                             new XAttribute("type", "fooObjectTypeName"),
                             new XAttribute("returnNoAttributes", "true"),
                             new XAttribute("failOnError", "true"),
                             new XAttribute("updateIfExists", "true"),
                             new XElement("AttributesToSet",
                                          new XElement("StructureAttribute",
                                                       new XAttribute("id", "215"),
                                                       new XAttribute("name", "fooAttributeName"),
                                                       new XElement("StructureValue",
                                                                    new XAttribute("langId", "10"),
                                                                    new XAttribute("scope", "global"),
                                                                    new XCData("fooValue")))));

            var value = new StructureValue {
                LanguageId = 10, Value = "fooValue"
            };
            var attribute = new StructureAttribute {
                DefinitionId = 215,
                Name         = "fooAttributeName",
                Values       = new List <StructureValue> {
                    value
                }
            };

            var create = new CreateRequest("fooObjectTypeName", "fooPath", null, attribute)
            {
                RequestFilters =
                    new List <ICreateRequestFilter> {
                    Filter.ReturnNoAttributes(),
                Filter.FailOnError(),
                Filter.UpdateIfExists()
                }
            };

            //Act
            var actual  = create.ToAdsml();
            var request = new BatchRequest(create);

            //Assert
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.ToString(), Is.EqualTo(expected.ToString()));
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
Ejemplo n.º 15
0
        public void Can_Generate_Api_Xml_With_LookupControls()
        {
            //Arrange
            string expected =
                new XElement("ModifyRequest",
                             new XAttribute("name", "/foo/bar"),
                             new XElement("ModificationItem",
                                          new XAttribute("operation", "addValue"),
                                          new XElement("AttributeDetails",
                                                       new XElement("StructureAttribute",
                                                                    new XAttribute("id", "31"),
                                                                    new XElement("StructureValue",
                                                                                 new XAttribute("langId", "10"),
                                                                                 new XAttribute("scope", "global"),
                                                                                 new XCData("foo"))))),
                             new XElement("LookupControls",
                                          new XElement("AttributesToReturn",
                                                       new XElement("Attribute",
                                                                    new XAttribute("name", "Artikelnummer"))),
                                          new XElement("LanguagesToReturn",
                                                       new XElement("Language",
                                                                    new XAttribute("id", "10"))))).ToString();

            var lookupBuilder = new LookupControlBuilder();

            lookupBuilder.ReturnAttributes(AttributeToReturn.WithName("Artikelnummer"))
            .ReturnLanguages(LanguageToReturn.WithLanguageId(10));

            //Act
            var modReq = new ModifyRequest("/foo/bar", new List <ModificationItem> {
                ModificationItem.New(
                    Modifications.AddValue,
                    StructureAttribute.New(31, new StructureValue(10, "foo"))
                    )
            })
            {
                LookupControl = lookupBuilder.Build()
            };

            var actual  = modReq.ToAdsml();
            var request = new BatchRequest(modReq);

            Console.WriteLine(actual.ToString());

            //Assert
            Assert.That(actual.ToString(), Is.EqualTo(expected));
            Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd"));
        }
Ejemplo n.º 16
0
        public void Validate_Throws_ApiSerializationValidationException_When_Context_Is_Empty()
        {
            //Arrange
            var modReq = new ModifyRequest(string.Empty, new List <ModificationItem> {
                ModificationItem.New(
                    Modifications.AddValue,
                    StructureAttribute.New(31, new StructureValue(10, "foo"))
                    )
            });

            //Act
            modReq.ToAdsml();

            //Assert
            Assert.Fail("Expected exception not thrown.");
        }
        public void CanSetAttributesToBeCreatedWithListFactoryOverload()
        {
            //Arrange
            var builder = new CreateRequestBuilder();

            //Act
            builder.AttributesToSet(
                () => new List <IAdsmlAttribute> {
                StructureAttribute.New(10, new StructureValue(10, "foo")),
                SimpleAttribute.New(AttributeTypes.Text, "objectName", "foo")
            }
                );

            //Assert
            Assert.That(builder.Attributes.Count(), Is.EqualTo(2));
        }
        public void Can_Generate_Api_Xml_Without_Specifying_Value()
        {
            //Arrange
            var expected = new XElement("StructureAttribute",
                                        new XAttribute("name", "foo"));

            var attr = new StructureAttribute {
                Name = "foo"
            };

            //Act
            var actual = attr.ToAdsml();

            //Assert
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.ToString(), Is.EqualTo(expected.ToString()));
        }
        public void Should_Be_Able_To_Add_StructureValues_In_Constructor()
        {
            //Act
            var structAttribute =
                new StructureAttribute(new List <StructureValue>
            {
                new StructureValue
                {
                    LanguageId = 10,
                    Scope      = Scopes.Global,
                    Value      = "foo"
                }
            });

            //Assert
            Assert.That(structAttribute, Is.Not.Null);
            Assert.That(structAttribute.Values.Count, Is.EqualTo(1));
        }
Ejemplo n.º 20
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion



        public void EverestManualExample116Test()
        {
            Type scanType = typeof(PRPA_IN201305UV02);

            foreach (var property in scanType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                Console.WriteLine("{0} = ", property.Name);

                var structureAtt = property.PropertyType.GetCustomAttributes(typeof(StructureAttribute), false);

                if (structureAtt.Length == 0)
                {
                    Console.WriteLine("?");
                }
                else
                {
                    StructureAttribute sa = structureAtt[0] as StructureAttribute;
                    Console.WriteLine(sa.StructureType.ToString());
                }
            }
        }
Ejemplo n.º 21
0
        public void Can_Generate_Api_Xml()
        {
            //Arrange
            var expected = new XElement("ModificationItem",
                                        new XAttribute("operation", "replaceValue"),
                                        new XElement("AttributeDetails",
                                                     new XElement("StructureAttribute",
                                                                  new XAttribute("id", "421"),
                                                                  new XAttribute("name", "yy Artikelstatus MMS001"),
                                                                  new XElement("StructureValue",
                                                                               new XAttribute("langId", "10"),
                                                                               new XAttribute("scope", "global"),
                                                                               new XCData("60"))))).ToString();


            //Act
            var actual = ModificationItem.New(Modifications.ReplaceValue,
                                              StructureAttribute.New("yy Artikelstatus MMS001", 421, new StructureValue(10, "60"))).ToAdsml().ToString();

            Console.WriteLine(actual);

            //Assert
            Assert.That(actual, Is.EqualTo(expected));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Graphs an object to the specified stream
        /// </summary>
        public void Graph(System.Xml.XmlWriter s, object o, MARC.Everest.Interfaces.IGraphable context, XmlIts1FormatterGraphResult resultContext)
        {
            ResultCode rc           = ResultCode.Accepted;
            Type       instanceType = o.GetType();

            // Verify o is not null
            if (o == null)
            {
                throw new System.ArgumentNullException("o");
            }

            // Attempt to get null flavor

            var  nfp            = o.GetType().GetProperty("NullFlavor");
            bool isInstanceNull = false,
                 isEntryPoint   = false;

            if (nfp != null)
            {
                isInstanceNull = nfp.GetValue(o, null) != null;
            }

            // Interaction?
            object[]           structureAttributes = instanceType.GetCustomAttributes(typeof(StructureAttribute), false);
            StructureAttribute structureAttribute  = structureAttributes[0] as StructureAttribute;

            if (structureAttribute.StructureType == StructureAttribute.StructureAttributeType.Interaction)
            {
                isEntryPoint = true;
                s.WriteStartElement(structureAttribute.Name, structureAttribute.NamespaceUri);
                s.WriteAttributeString("ITSVersion", "XML_1.0"); // Add ITS version
                s.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI);
            }
            else if (structureAttribute.IsEntryPoint && (s is MARC.Everest.Xml.XmlStateWriter && (s as MARC.Everest.Xml.XmlStateWriter).ElementStack.Count == 0 || s.WriteState == System.Xml.WriteState.Start))
            {
                isEntryPoint = true;
                if (isEntryPoint)
                {
                    s.WriteStartElement(structureAttribute.Name, structureAttribute.NamespaceUri);
                    s.WriteAttributeString("xmlns", "xsi", null, XmlIts1Formatter.NS_XSI);
                }
            }

            // Validate
            this.Host.ValidateHelper(s, o as IGraphable, this, resultContext);

            // Reflect the properties and ensure they are in the appropriate order
            List <PropertyInfo> buildProperties = GetBuildProperties(instanceType);

            // Attributes first
            foreach (var pi in buildProperties)
            {
                object[] propertyAttributes = pi.GetCustomAttributes(typeof(PropertyAttribute), false);
                object   instance           = pi.GetValue(o, null);

                if (propertyAttributes.Length == 1) // Not a choice
                {
                    PropertyAttribute pa = propertyAttributes[0] as PropertyAttribute;

                    // Validation Rule Change: We'll require the user to perform this
                    // Is this a required attribute that is null? We'll set a null flavor
                    if ((pa.Conformance == PropertyAttribute.AttributeConformanceType.Required || pa.Conformance == PropertyAttribute.AttributeConformanceType.Populated) &&
                        pa.PropertyType != PropertyAttribute.AttributeAttributeType.Structural &&
                        pi.PropertyType.GetProperty("NullFlavor") != null &&
                        !pi.PropertyType.IsAbstract &&
                        pi.CanWrite)
                    {
                        var nullFlavorProperty = pi.PropertyType.GetProperty("NullFlavor");
                        // Locate the default property
                        if (instance == null && Host.CreateRequiredElements && nullFlavorProperty != null)
                        {
                            ConstructorInfo ci = pi.PropertyType.GetConstructor(Type.EmptyTypes);
                            instance = ci.Invoke(null);
                            nullFlavorProperty.SetValue(instance, Util.FromWireFormat("NI", nullFlavorProperty.PropertyType), null);
                        }
                    }


                    // Property type
                    switch (pa.PropertyType)
                    {
                    case PropertyAttribute.AttributeAttributeType.Structural:
                        if ((Host.Settings & SettingsType.SuppressNullEnforcement) == 0)
                        {
                            if (instance != null && !isInstanceNull)
                            {
                                s.WriteAttributeString(pa.Name, Util.ToWireFormat(instance));
                            }
                            else if (isInstanceNull && pi.Name == "NullFlavor")
                            {
                                Host.WriteNullFlavorUtil(s, (IGraphable)instance);
                            }
                        }
                        else if (instance != null)
                        {
                            if (instance != null && pi.Name == "NullFlavor")
                            {
                                Host.WriteNullFlavorUtil(s, (IGraphable)instance);
                            }
                            else if (instance != null)
                            {
                                s.WriteAttributeString(pa.Name, Util.ToWireFormat(instance));
                            }
                        }

                        break;

                    default:

                        // Instance is null
                        if (instance == null)
                        {
                            continue;
                        }
                        else if (isInstanceNull && (Host.Settings & (SettingsType.SuppressNullEnforcement | SettingsType.SuppressXsiNil)) != 0)
                        {
                            resultContext.AddResultDetail(new FormalConstraintViolationResultDetail(ResultDetailType.Information, "The context is null however SuppressNullEnforcement and SuppressXsiNil are set, therefore elements will be graphed. This is not necessarily HL7v3 compliant", s.ToString(), null));
                        }
                        else if (isInstanceNull)
                        {
                            continue;
                        }

                        // Impose flavors or code?
                        if (pa.DefaultUpdateMode != MARC.Everest.DataTypes.UpdateMode.Unknown &&
                            pi.PropertyType.GetProperty("UpdateMode") != null &&
                            pi.PropertyType.GetProperty("UpdateMode").GetValue(instance, null) == null &&
                            (this.Host.Settings & SettingsType.AllowUpdateModeImposing) == SettingsType.AllowUpdateModeImposing)
                        {
                            pi.PropertyType.GetProperty("UpdateMode").SetValue(instance, Util.FromWireFormat(pa.DefaultUpdateMode, pi.PropertyType.GetProperty("UpdateMode").PropertyType), null);
                        }
                        if (pa.ImposeFlavorId != null &&
                            instance is IAny &&
                            (Host.Settings & SettingsType.AllowFlavorImposing) == SettingsType.AllowFlavorImposing)
                        {
                            (instance as IAny).Flavor = pa.ImposeFlavorId;
                        }
                        if (pa.SupplierDomain != null &&
                            instance is ICodedValue &&
                            (instance as ICodedSimple).CodeValue != null &&
                            (instance as ICodedValue).CodeSystem == null &&
                            (instance as IImplementsNullFlavor).NullFlavor == null &&
                            (Host.Settings & SettingsType.AllowSupplierDomainImposing) == SettingsType.AllowSupplierDomainImposing)
                        {
                            (instance as ICodedValue).CodeSystem = pa.SupplierDomain;
                        }

                        // Instance is graphable
                        if (instance is IGraphable)
                        {
                            // Ensure the data is not empty
                            if (instance is IColl && (instance as IColl).IsEmpty && (instance as IImplementsNullFlavor).NullFlavor == null)
                            {
                                continue;
                            }
                            Host.WriteElementUtil(s, pa.NamespaceUri, pa.Name, instance as IGraphable, pi.PropertyType, context, resultContext);
                        }
                        else if (instance is ICollection)
                        {
                            Type genType = pi.PropertyType.GetGenericArguments()[0];
                            foreach (object itm in (instance as ICollection))
                            {
                                Host.WriteElementUtil(s, pa.NamespaceUri, pa.Name, itm as IGraphable, genType, context, resultContext);
                            }
                        }
                        else
                        {
                            s.WriteElementString(pa.Name, instance.ToString());
                        }
                        break;
                    }
                }
                else if (propertyAttributes.Length > 1) // Choice
                {
                    // Instance is null
                    if (instance == null)
                    {
                        continue;
                    }
                    else if (isInstanceNull && (Host.Settings & (SettingsType.SuppressNullEnforcement | SettingsType.SuppressXsiNil)) != 0)
                    {
                        resultContext.AddResultDetail(new FormalConstraintViolationResultDetail(ResultDetailType.Information, "The context is null however SuppressNullEnforcement and SuppressXsiNil are set, therefore elements will be graphed. This is not necessarily HL7v3 compliant", s.ToString(), null));
                    }
                    else if (isInstanceNull)
                    {
                        continue;
                    }
#if WINDOWS_PHONE
                    PropertyAttribute formatAs = propertyAttributes.Find(cpa => (cpa as PropertyAttribute).Type == null) as PropertyAttribute;
#else
                    PropertyAttribute formatAs = Array.Find(propertyAttributes, cpa => (cpa as PropertyAttribute).Type == null) as PropertyAttribute;
#endif
                    // Search by type and interaction
                    foreach (PropertyAttribute pa in propertyAttributes)
                    {
                        if (pa.Type != null && instance.GetType() == pa.Type && (context != null && context.GetType() == pa.InteractionOwner || (pa.InteractionOwner == null && formatAs == null)))
                        {
                            formatAs = pa;
                            if (context == null || context.GetType() == formatAs.InteractionOwner)
                            {
                                break;
                            }
                        }
                    }

                    // Slow check
                    if (formatAs == null && (this.Host.Settings & SettingsType.AlwaysCheckForOverrides) != 0)
                    {
                        foreach (PropertyAttribute pa in propertyAttributes)
                        {
                            if (pa.Type != null && pa.Type.IsAssignableFrom(instance.GetType()) && (context != null && context.GetType() == pa.InteractionOwner || (pa.InteractionOwner == null && formatAs == null)))
                            {
                                formatAs = pa;
                                if (context == null || context.GetType() == formatAs.InteractionOwner)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    //if(formatAs == null) // try to find a regular choice
                    //    foreach(PropertyAttribute pa in propertyAttributes)
                    //        if (pa.Type != null && instance.GetType() == pa.Type)
                    //        {
                    //            formatAs = pa;
                    //            break;
                    //        }


                    // Format
                    if (formatAs == null)
                    {
                        resultContext.AddResultDetail(new NotSupportedChoiceResultDetail(ResultDetailType.Error, String.Format("Type {0} is not a valid choice according to available choice elements and won't be formatted", instance.GetType()), s.ToString(), null));
                    }
                    else if (instance.GetType().GetInterface("MARC.Everest.Interfaces.IGraphable", false) != null) // Non Graphable
                    {
                        Host.WriteElementUtil(s, formatAs.NamespaceUri, formatAs.Name, (MARC.Everest.Interfaces.IGraphable)instance, formatAs.Type, context, resultContext);
                    }
                    else if (instance.GetType().GetInterface("System.Collections.IEnumerable", false) != null) // List
                    {
                        foreach (MARC.Everest.Interfaces.IGraphable ig in instance as IEnumerable)
                        {
                            Host.WriteElementUtil(s, formatAs.NamespaceUri, formatAs.Name, ig, instance.GetType(), context, resultContext);
                        }
                    }
                    else // Not recognized
                    {
                        s.WriteElementString(formatAs.Name, formatAs.NamespaceUri, instance.ToString());
                    }
                }
            }

            // Is Entry point
            if (isEntryPoint)
            {
                s.WriteEndElement();
            }
        }
Ejemplo n.º 23
0
        public static Property CreatePropertyObject(PropertyInfo propInfo, out Dictionary <string, Structure> structures)
        {
            structures = new Dictionary <string, Structure>();

            Property result = new VSPlugin.Property();

            string    itemsType = "";
            Structure structure = null;

            // we need to verify if we have a structure in this property
            StructureAttribute structureAttribute = propInfo.GetCustomAttribute <StructureAttribute>();

            if (structureAttribute != null)
            {
                result.Type = structureAttribute.Type;
            }
            else
            {
                result.Type = Utility.HandleProperty(propInfo, out itemsType, out structure);
            }

            if (!string.IsNullOrEmpty(itemsType))
            {
                result.Items      = new ArraySchema();
                result.Items.Type = itemsType;
            }
            if (structure != null)
            {
                structures.Add(propInfo.PropertyType.Name, structure);
            }

            PropertyAttribute propAttrib = propInfo.GetCustomAttribute <PropertyAttribute>();

            if (propAttrib == null)
            {
                return(result);
            }

            result.Description = propAttrib.Description;
            result.Required    = propAttrib.Required;
            result.Readonly    = propAttrib.ReadOnly;
            result.Final       = propAttrib.Final;
            result.Encrypted   = propAttrib.Encrypted;
            result.Unit        = propAttrib.Unit;
            result.Default     = propAttrib.Default;
            result.Format      = propAttrib.Format;
            result.Pattern     = propAttrib.Pattern;
            result.Title       = propAttrib.Title;
            result.Headline    = propAttrib.Headline;
            result.MinLength   = propAttrib.MinLength;
            result.MaxLength   = propAttrib.MaxLength;
            result.MinItems    = propAttrib.MinItems;
            result.MaxItems    = propAttrib.MaxItems;
            result.UniqueItems = propAttrib.UniqueItems;
            result.EnumValues  = propAttrib.Enum;
            result.EnumTitles  = propAttrib.EnumTitles;

            result.Access = Access.GetAccess(propInfo);

            return(result);
        }
Ejemplo n.º 24
0
        public static void Initialize(String apiNs)
        {
            defaultTypeParms.Clear();
            flavMaps.Clear();
            builtinVocab.Clear();
            codeTypes.Clear();
            collectionTypes.Clear();
            // Try to scan the AppDomain for the API
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type t in a.GetTypes())
                {
                    // Determine if the type implements IGraphable and is a structure
                    if (t.GetCustomAttributes(typeof(StructureAttribute), false).Length > 0 &&
                        t.FullName.StartsWith(apiNs))
                    {
                        // Get the structure and flavor map attributes
                        StructureAttribute sta = t.GetCustomAttributes(typeof(StructureAttribute), false)[0] as StructureAttribute;

                        // Setup the type parameter info
                        if (t.IsGenericTypeDefinition)
                        {
                            defaultTypeParms.Add(new TypeParameterInformation()
                            {
                                Type = t,
                                StructureAttribute = sta
                            });
                        }

                        if (sta.StructureType == StructureAttribute.StructureAttributeType.CodeSystem ||
                            sta.StructureType == StructureAttribute.StructureAttributeType.ConceptDomain ||
                            sta.StructureType == StructureAttribute.StructureAttributeType.ValueSet)
                        {
                            builtinVocab.Add(sta.Name, t.FullName);
                        }

                        if (sta.StructureType == StructureAttribute.StructureAttributeType.DataType &&
                            t.GetProperty("Code") != null &&
                            t.IsGenericTypeDefinition)
                        {
                            codeTypes.Add(sta.Name);
                        }
                        else if (sta.StructureType == StructureAttribute.StructureAttributeType.DataType &&
                                 t.GetMethod("Add") != null &&
                                 t.IsGenericTypeDefinition)
                        {
                            collectionTypes.Add(sta.Name);
                        }

                        Object[] flv = t.GetCustomAttributes(typeof(FlavorMapAttribute), false);

                        // Process the STA
                        if (flavMaps.ContainsKey(sta.Name ?? Guid.NewGuid().ToString()))
                        {
                            throw new InvalidOperationException(String.Format("Can't add duplicate datatype '{0}' to type maps", sta.Name));
                        }

                        flavMaps.Add(sta.Name ?? Guid.NewGuid().ToString(), t); // Map Structure Name to the type

                        // Process the flavor maps
                        foreach (FlavorMapAttribute fma in flv)
                        {
                            if (flavMaps.ContainsKey(String.Format("{0}.{1}", sta.Name, fma.FlavorId)))
                            {
                                throw new InvalidOperationException(String.Format("Can't add duplicate flavor map '{0}' to type maps", fma.FlavorId));
                            }
                            flavMaps.Add(String.Format("{0}.{1}", sta.Name, fma.FlavorId), fma.Implementer); // Map Structure Name to the type
                        }
                    }

                    var ttypeMapes = t.GetCustomAttributes(typeof(TypeMapAttribute), false);
                    foreach (TypeMapAttribute tma in ttypeMapes)
                    {
                        if (typeMaps.ContainsKey(tma.Name))
                        {
                            throw new InvalidOperationException("Can't add duplicate type map");
                        }
                        typeMaps.Add(String.Format("{0}#{1}", tma.Name, tma.ArgumentType), t);
                    }
                }
            }
            ;
        }
Ejemplo n.º 25
0
        public static void EnumToDataset(String[] args)
        {
            var parms = new ParameterParser <ConsoleParameters>().Parse(args);

            var asm = Assembly.LoadFile(parms.AssemblyFile);

            foreach (var en in asm.ExportedTypes.Where(o => o.IsEnum && o.GetCustomAttribute <StructureAttribute>() != null))
            {
                StructureAttribute sta = en.GetCustomAttribute <StructureAttribute>();

                DatasetInstall conceptDataset = new DatasetInstall()
                {
                    Id = String.Format("HL7v3 {0} Concept Set", sta.Name)
                };

                // Create vaccine code concept set
                var conceptSet = new DataUpdate()
                {
                    InsertIfNotExists = true,
                    Element           = new ConceptSet()
                    {
                        Key      = Guid.NewGuid(),
                        Mnemonic = en.Name,
                        Name     = sta.Name,
                        Oid      = sta.CodeSystem,
                        Url      = String.Format("http://openiz.org/valuset/v3-{0}", en.Name)
                    },
                    Association = new List <DataAssociation>()
                };

                var codeSystem = new DataUpdate()
                {
                    InsertIfNotExists = true,
                    Element           = new CodeSystem(sta.Name, sta.CodeSystem, en.Name)
                    {
                        Url = String.Format("http://hl7.org/fhir/v3-{0}", en.Name),
                        Key = Guid.NewGuid(),
                    }
                };
                conceptDataset.Action.Add(codeSystem);

                foreach (var enm in en.GetFields())
                {
                    var ena = enm.GetCustomAttribute <EnumerationAttribute>();

                    if (ena == null)
                    {
                        continue;
                    }

                    var dsa = enm.GetCustomAttribute <DescriptionAttribute>();

                    ReferenceTerm refTerm = new ReferenceTerm()
                    {
                        CodeSystemKey = codeSystem.Element.Key,
                        Mnemonic      = ena.Value,
                        DisplayNames  = new List <ReferenceTermName>()
                        {
                            new ReferenceTermName()
                            {
                                Language = "en", Name = dsa?.Description ?? enm.Name
                            }
                        },
                        Key = Guid.NewGuid()
                    };

                    var mnemonic = String.Format("{0}-{1}", en.Name, enm.Name);
                    if (mnemonic.Length > 64)
                    {
                        mnemonic = mnemonic.Substring(0, 64);
                    }
                    Concept concept = new Concept()
                    {
                        Key          = Guid.NewGuid(),
                        Mnemonic     = mnemonic,
                        ClassKey     = ConceptClassKeys.Other,
                        ConceptNames = new List <ConceptName>()
                        {
                            new ConceptName()
                            {
                                Language = "en", Name = dsa?.Description
                            }
                        },
                        ReferenceTerms = new List <ConceptReferenceTerm>()
                        {
                            new ConceptReferenceTerm()
                            {
                                ReferenceTermKey    = refTerm.Key,
                                RelationshipTypeKey = ConceptRelationshipTypeKeys.SameAs
                            }
                        },
                        StatusConceptKey = StatusKeys.Active,
                        CreationTime     = DateTime.Now
                    };

                    conceptDataset.Action.Add(new DataUpdate()
                    {
                        InsertIfNotExists = true,
                        Element           = refTerm
                    });
                    conceptDataset.Action.Add(new DataUpdate()
                    {
                        InsertIfNotExists = true,
                        Element           = concept
                    });
                    (conceptSet.Element as ConceptSet).ConceptsXml.Add(concept.Key.Value);
                }

                conceptDataset.Action.Add(conceptSet);
                XmlSerializer xsz = new XmlSerializer(typeof(DatasetInstall));
                using (FileStream fs = File.Create(en.Name + ".dataset"))
                    xsz.Serialize(fs, conceptDataset);
            }
        }
        /// <summary>
        /// This feature is supported by version 19.6 or greater
        /// </summary>
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            // Create document
            Document       document      = new Document();
            ITaggedContent taggedContent = document.TaggedContent;

            taggedContent.SetTitle("Example table");
            taggedContent.SetLanguage("en-US");

            // Get root structure element
            StructureElement rootElement = taggedContent.RootElement;


            TableElement tableElement = taggedContent.CreateTableElement();

            rootElement.AppendChild(tableElement);

            tableElement.Border = new BorderInfo(BorderSide.All, 1.2F, Color.DarkBlue);

            TableTHeadElement tableTHeadElement = tableElement.CreateTHead();
            TableTBodyElement tableTBodyElement = tableElement.CreateTBody();
            TableTFootElement tableTFootElement = tableElement.CreateTFoot();
            int rowCount = 50;
            int colCount = 4;
            int rowIndex;
            int colIndex;

            TableTRElement headTrElement = tableTHeadElement.CreateTR();

            headTrElement.AlternativeText = "Head Row";

            headTrElement.BackgroundColor = Color.LightGray;

            for (colIndex = 0; colIndex < colCount; colIndex++)
            {
                TableTHElement thElement = headTrElement.CreateTH();
                thElement.SetText(String.Format("Head {0}", colIndex));

                thElement.BackgroundColor = Color.GreenYellow;
                thElement.Border          = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);

                thElement.IsNoBorder = true;
                thElement.Margin     = new MarginInfo(16.0, 2.0, 8.0, 2.0);

                thElement.Alignment = HorizontalAlignment.Right;
            }

            for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                TableTRElement trElement = tableTBodyElement.CreateTR();
                trElement.AlternativeText = String.Format("Row {0}", rowIndex);

                for (colIndex = 0; colIndex < colCount; colIndex++)
                {
                    int colSpan = 1;
                    int rowSpan = 1;

                    if (colIndex == 1 && rowIndex == 1)
                    {
                        colSpan = 2;
                        rowSpan = 2;
                    }
                    else if (colIndex == 2 && (rowIndex == 1 || rowIndex == 2))
                    {
                        continue;
                    }
                    else if (rowIndex == 2 && (colIndex == 1 || colIndex == 2))
                    {
                        continue;
                    }

                    TableTDElement tdElement = trElement.CreateTD();
                    tdElement.SetText(String.Format("Cell [{0}, {1}]", rowIndex, colIndex));


                    tdElement.BackgroundColor = Color.Yellow;
                    tdElement.Border          = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);

                    tdElement.IsNoBorder = false;
                    tdElement.Margin     = new MarginInfo(8.0, 2.0, 8.0, 2.0);

                    tdElement.Alignment = HorizontalAlignment.Center;

                    TextState cellTextState = new TextState();
                    cellTextState.ForegroundColor  = Color.DarkBlue;
                    cellTextState.FontSize         = 7.5F;
                    cellTextState.FontStyle        = FontStyles.Bold;
                    cellTextState.Font             = FontRepository.FindFont("Arial");
                    tdElement.DefaultCellTextState = cellTextState;

                    tdElement.IsWordWrapped     = true;
                    tdElement.VerticalAlignment = VerticalAlignment.Center;

                    tdElement.ColSpan = colSpan;
                    tdElement.RowSpan = rowSpan;
                }
            }

            TableTRElement footTrElement = tableTFootElement.CreateTR();

            footTrElement.AlternativeText = "Foot Row";

            footTrElement.BackgroundColor = Color.LightSeaGreen;

            for (colIndex = 0; colIndex < colCount; colIndex++)
            {
                TableTDElement tdElement = footTrElement.CreateTD();
                tdElement.SetText(String.Format("Foot {0}", colIndex));

                tdElement.Alignment = HorizontalAlignment.Center;
                tdElement.StructureTextState.FontSize  = 7F;
                tdElement.StructureTextState.FontStyle = FontStyles.Bold;
            }


            StructureAttributes tableAttributes  = tableElement.Attributes.GetAttributes(AttributeOwnerStandard.Table);
            StructureAttribute  summaryAttribute = new StructureAttribute(AttributeKey.Summary);

            summaryAttribute.SetStringValue("The summary text for table");
            tableAttributes.SetAttribute(summaryAttribute);


            // Save Tagged Pdf Document
            document.Save(dataDir + "CreateTableElement.pdf");

            // Checking PDF/UA compliance
            document = new Document(dataDir + "CreateTableElement.pdf");
            bool isPdfUaCompliance = document.Validate(dataDir + "table.xml", PdfFormat.PDF_UA_1);

            Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));

            // ExEnd:1
        }
Ejemplo n.º 27
0
 private void initBaseAttributes()
 {
     for( int b = 0 ; b < Enum.GetValues(typeof(StructureAttributeNames)).Length; b++ ){
         baseAttributes[b] = new StructureAttribute();
     }
 }
Ejemplo n.º 28
0
        public static void Run()
        {
            // ExStart:LinkStructureElements
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
            string outFile = dataDir + "LinkStructureElements_Output.pdf";
            string logFile = dataDir + "46035_log.xml";
            string imgFile = dataDir + "google-icon-512.png";

            // Creation document and getting Tagged Pdf Content
            Document       document      = new Document();
            ITaggedContent taggedContent = document.TaggedContent;


            // Setting Title and Nature Language for document
            taggedContent.SetTitle("Link Elements Example");
            taggedContent.SetLanguage("en-US");

            // Getting Root structure element (Document structure element)
            StructureElement rootElement = taggedContent.RootElement;


            ParagraphElement p1 = taggedContent.CreateParagraphElement();

            rootElement.AppendChild(p1);
            LinkElement link1 = taggedContent.CreateLinkElement();

            p1.AppendChild(link1);
            link1.Hyperlink = new WebHyperlink("http://google.com");
            link1.SetText("Google");
            link1.AlternateDescriptions = "Link to Google";


            ParagraphElement p2 = taggedContent.CreateParagraphElement();

            rootElement.AppendChild(p2);
            LinkElement link2 = taggedContent.CreateLinkElement();

            p2.AppendChild(link2);
            link2.Hyperlink = new WebHyperlink("http://google.com");
            SpanElement span2 = taggedContent.CreateSpanElement();

            span2.SetText("Google");
            link2.AppendChild(span2);
            link2.AlternateDescriptions = "Link to Google";


            ParagraphElement p3 = taggedContent.CreateParagraphElement();

            rootElement.AppendChild(p3);
            LinkElement link3 = taggedContent.CreateLinkElement();

            p3.AppendChild(link3);
            link3.Hyperlink = new WebHyperlink("http://google.com");
            SpanElement span31 = taggedContent.CreateSpanElement();

            span31.SetText("G");
            SpanElement span32 = taggedContent.CreateSpanElement();

            span32.SetText("oogle");
            link3.AppendChild(span31);
            link3.SetText("-");
            link3.AppendChild(span32);
            link3.AlternateDescriptions = "Link to Google";


            ParagraphElement p4 = taggedContent.CreateParagraphElement();

            rootElement.AppendChild(p4);
            LinkElement link4 = taggedContent.CreateLinkElement();

            p4.AppendChild(link4);
            link4.Hyperlink = new WebHyperlink("http://google.com");
            link4.SetText("The multiline link: Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google");
            link4.AlternateDescriptions = "Link to Google (multiline)";


            ParagraphElement p5 = taggedContent.CreateParagraphElement();

            rootElement.AppendChild(p5);
            LinkElement link5 = taggedContent.CreateLinkElement();

            p5.AppendChild(link5);
            link5.Hyperlink = new WebHyperlink("http://google.com");
            FigureElement figure5 = taggedContent.CreateFigureElement();

            figure5.SetImage(imgFile, 1200);
            figure5.AlternativeText = "Google icon";
            StructureAttributes linkLayoutAttributes = link5.Attributes.GetAttributes(AttributeOwnerStandard.Layout);
            StructureAttribute  placementAttribute   = new StructureAttribute(AttributeKey.Placement);

            placementAttribute.SetNameValue(AttributeName.Placement_Block);
            linkLayoutAttributes.SetAttribute(placementAttribute);
            link5.AppendChild(figure5);
            link5.AlternateDescriptions = "Link to Google";


            // Save Tagged Pdf Document
            document.Save(outFile);

            // Checking PDF/UA compliance
            document = new Document(outFile);
            bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);

            Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
            // ExEnd:LinkStructureElements
        }
        private CodeMemberMethod CreateGraphMethod(Type forType)
        {
            CodeMemberMethod method = new CodeMemberMethod();

            method.Name = "Graph";
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Xml.XmlWriter), "s"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Object), "o"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IGraphable), "context"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(XmlIts1FormatterGraphResult), "resultContext"));

            method.Attributes = MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(void));

            // Type reference to the forType
            CodeTypeReference tref = new CodeTypeReference(forType);
            string            trefTypeReference = CreateTypeReference(tref);

            // Build the method body
            CodeStatementCollection methodBodyEle = new CodeStatementCollection(), methodBodyAtt = new CodeStatementCollection();

            methodBodyAtt.Add(new CodeSnippetExpression("if(o == null) throw new System.ArgumentNullException(\"o\")"));
            methodBodyAtt.Add(new CodeSnippetExpression(String.Format("if(instance == null) throw new System.ArgumentException(System.String.Format(\"Could not cast type '{{0}}' to '{0}'!\", o.GetType().FullName))", trefTypeReference)));

            if (forType.GetProperty("NullFlavor") != null)
            {
                methodBodyAtt.Add(new CodeSnippetExpression("bool isInstanceNull = instance.NullFlavor != null"));
            }
            else
            {
                methodBodyAtt.Add(new CodeSnippetExpression("bool isInstanceNull = instance == null"));
            }

            methodBodyAtt.Add(new CodeSnippetStatement("bool suppressNull = (Host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.SuppressNullEnforcement) != 0;"));
            methodBodyAtt.Add(new CodeSnippetStatement("bool suppressXsiNil = (Host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.SuppressXsiNil) != 0;"));
            methodBodyAtt.Add(new CodeSnippetStatement("bool alwaysCheckForOverrides = (Host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.AlwaysCheckForOverrides) != 0;"));

            // Interaction?
            object[]           structureAttributes = forType.GetCustomAttributes(typeof(StructureAttribute), false);
            StructureAttribute structureAttribute  = structureAttributes[0] as StructureAttribute;

            if (structureAttribute.StructureType == StructureAttribute.StructureAttributeType.Interaction)
            {
                methodBodyAtt.Add(new CodeSnippetExpression(String.Format("bool isEntryPoint = true; s.WriteStartElement(\"{0}\", \"urn:hl7-org:v3\")", structureAttribute.Name)));
                methodBodyAtt.Add(new CodeSnippetExpression("s.WriteAttributeString(\"ITSVersion\",\"XML_1.0\")")); // Add ITS version
                methodBodyAtt.Add(new CodeSnippetExpression("if(isEntryPoint) s.WriteAttributeString(\"xmlns\", \"xsi\", null, MARC.Everest.Formatters.XML.ITS1.XmlIts1Formatter.NS_XSI)"));
            }
            else if (structureAttribute.IsEntryPoint)
            {
                methodBodyAtt.Add(new CodeSnippetExpression(String.Format("bool isEntryPoint = s is MARC.Everest.Xml.XmlStateWriter && (s as MARC.Everest.Xml.XmlStateWriter).ElementStack.Count == 0 || s.WriteState == System.Xml.WriteState.Start; if(isEntryPoint) s.WriteStartElement(\"{0}\", \"urn:hl7-org:v3\")", structureAttribute.Name)));
                methodBodyAtt.Add(new CodeSnippetExpression("if(isEntryPoint) s.WriteAttributeString(\"xmlns\", \"xsi\", null, MARC.Everest.Formatters.XML.ITS1.XmlIts1Formatter.NS_XSI)"));
            }

            // Validate
            methodBodyAtt.Add(new CodeSnippetExpression("if(this.Host.ValidateConformance) this.Host.ValidateHelper(s, instance, this, resultContext)"));

            #region Build inherited properties in correct order
            var buildProperties = GetBuildProperties(forType);
            #endregion

            bool lastWasAttribute = true;
            // Get property information
            foreach (PropertyInfo pi in buildProperties)
            {
                Type        piType             = pi.PropertyType;
                List <Type> piInterfaces       = new List <Type>(piType.GetInterfaces());;
                object[]    propertyAttributes = pi.GetCustomAttributes(typeof(PropertyAttribute), true);

                if (propertyAttributes.Length > 0) // Property attribute ... process it
                {
                    var propertyAttribute = propertyAttributes[0] as PropertyAttribute;
                    CodeStatementCollection methodBody = propertyAttribute.PropertyType == PropertyAttribute.AttributeAttributeType.Structural ? methodBodyAtt : methodBodyEle;

                    bool retValChanged = false;

                    #region Process Property
                    // Validation Rule Change: We'll require the user to perform this
                    // Is this a required attribute that is null? We'll set a null flavor
                    if ((propertyAttribute.Conformance == PropertyAttribute.AttributeConformanceType.Required || propertyAttribute.Conformance == PropertyAttribute.AttributeConformanceType.Populated) &&
                        propertyAttribute.PropertyType != PropertyAttribute.AttributeAttributeType.Structural &&
                        piType.GetProperty("NullFlavor") != null &&
                        !piType.IsAbstract &&
                        pi.CanWrite)
                    {
                        var nullFlavorProperty = piType.GetProperty("NullFlavor");
                        // Locate the default property
                        methodBody.Add(new CodeSnippetStatement(String.Format("if(instance.{0} == null && Host.CreateRequiredElements) {{ instance.{0} = new {1}(); instance.{0}.NullFlavor = {2}.NoInformation; }}", pi.Name, CreateTypeReference(new CodeTypeReference(pi.PropertyType)), CreateTypeReference(new CodeTypeReference(nullFlavorProperty.PropertyType.GetGenericArguments()[0])))));
                    }


                    // Is the instance's null flavor set?
                    // Remarks: We do this way because we still need to write the null flavor out even if the  null flavor
                    if (pi.Name != "NullFlavor")
                    {
                        if (propertyAttribute.PropertyType == PropertyAttribute.AttributeAttributeType.Structural)
                        {
                            methodBody.Add(new CodeSnippetStatement(String.Format("if(instance.{0} != null && (isInstanceNull && suppressNull || !isInstanceNull)) {{\r\n", pi.Name)));
                        }
                        else
                        {
                            methodBody.Add(new CodeSnippetStatement(String.Format("if(instance.{0} != null && (isInstanceNull && suppressNull && suppressXsiNil || !isInstanceNull)) {{\r\n", pi.Name)));
                        }
                    }
                    else if (pi.Name == "NullFlavor")
                    {
                        methodBody.Add(new CodeSnippetExpression("if(instance.NullFlavor != null) this.Host.WriteNullFlavorUtil(s, instance.NullFlavor)"));
                        continue;
                    }

                    // Represents a choice
                    if (propertyAttributes.Length > 1)
                    {
                        #region Property is a Choice
                        int      ic = 0;
                        string[] choiceTypeCheckConditions =
                        {
                            "instance.{0}.GetType() == typeof({1})",
                            "alwaysCheckForOverrides && typeof({1}).IsAssignableFrom(instance.{0}.GetType())"
                        };
                        for (int tryCount = 0; tryCount < 2; tryCount++)
                        {
                            foreach (PropertyAttribute pa in propertyAttributes)
                            {
                                // Only process if
                                //  Type on the pa is not null , and
                                //  Either
                                //      1. The pa type matches the real property type (represents an alt traversal)
                                //      2. The pi type is abstract (represents a choice)
                                //      3. The pi is an object (represents a choice)

                                if (pa.Type != null && (pa.Type == pi.PropertyType || (pa.Type.IsSubclassOf(pi.PropertyType) && pi.PropertyType.IsAssignableFrom(pa.Type)) || pi.PropertyType == typeof(object)))
                                {
                                    // write if statement
                                    String conditionString = String.Format(choiceTypeCheckConditions[tryCount], pi.Name, pa.Type.FullName);

                                    if (pa.InteractionOwner != null)
                                    {
                                        methodBody.Add(new CodeSnippetStatement(String.Format("{0} if({1} && context is {2}) {{\r\n", ic > 0 ? "else" : "", conditionString, CreateTypeReference(new CodeTypeReference(pa.InteractionOwner)))));
                                    }
                                    else
                                    {
                                        methodBody.Add(new CodeSnippetStatement(String.Format("{0} if({1}) {{ \r\n", ic > 0 ? "else" : "", conditionString)));
                                    }
                                    // Output
                                    if (pa.Type.GetInterface("MARC.Everest.Interfaces.IGraphable") != null) // Non Graphable
                                    {
                                        methodBody.Add(new CodeSnippetExpression(String.Format("Host.WriteElementUtil(s, \"{3}\", \"{0}\", (MARC.Everest.Interfaces.IGraphable)instance.{1}, typeof({2}), context, resultContext)", pa.Name, pi.Name, CreateTypeReference(new CodeTypeReference(pa.Type)), pa.NamespaceUri)));
                                    }
                                    else if (pa.Type.GetInterface("System.Collections.IEnumerable") != null) // List
                                    {
                                        methodBody.Add(new CodeSnippetStatement(String.Format("foreach(MARC.Everest.Interfaces.IGraphable ig in instance.{0}) {{ Host.WriteElementUtil(s, \"{3}\", \"{1}\", ig, typeof({2}), context, resultContext); }}", pi.Name, pa.Name, CreateTypeReference(new CodeTypeReference(pa.Type)), pa.NamespaceUri)));
                                    }
                                    else // Not recognized
                                    {
                                        methodBody.Add(new CodeSnippetExpression(String.Format("s.WriteElementString(\"{0}\", \"urn:hl7-org:v3\", instance.{1}.ToString())\r\n", pa.Name, pi.Name)));
                                    }

                                    methodBody.Add(new CodeSnippetStatement("}"));
                                    ic++;
                                }
                            }
                        }

                        // Was a choice found?
                        if (ic == 0) // nope
                        {
                            PropertyAttribute pa = Array.Find <Object>(propertyAttributes, o => (o as PropertyAttribute).Type == null) as PropertyAttribute;
                            // Output
                            if (pa != null && pi.PropertyType.GetInterface("MARC.Everest.Interfaces.IGraphable") != null) // Non Graphable
                            {
                                retValChanged = true;
                                methodBody.Add(new CodeSnippetExpression(String.Format("Host.WriteElementUtil(s, \"{3}\", \"{0}\", (MARC.Everest.Interfaces.IGraphable)instance.{1}, typeof({2}), context, resultContext)", pa.Name, pi.Name, CreateTypeReference(new CodeTypeReference(pi.PropertyType)), pa.NamespaceUri)));
                            }
                            else if (pa != null && pi.PropertyType.GetInterface("System.Collections.IEnumerable") != null) // List
                            {
                                methodBody.Add(new CodeSnippetStatement(String.Format("foreach(MARC.Everest.Interfaces.IGraphable ig in instance.{0}) {{ Host.WriteElementUtil(s, \"{3}\", \"{1}\", ig, typeof({2}), context, resultContext); }}", pi.Name, pa.Name, CreateTypeReference(new CodeTypeReference(pi.PropertyType)), pa.NamespaceUri)));
                                retValChanged = true;
                            }
                            else if (pa != null) // Not recognized
                            {
                                methodBody.Add(new CodeSnippetExpression(String.Format("s.WriteElementString(\"{0}\", \"urn:hl7-org:v3\", instance.{1}.ToString())", pa.Name, pi.Name)));
                            }
                        }
                        else
                        {
                            methodBody.Add(new CodeSnippetStatement(String.Format("else {{ resultContext.Code = MARC.Everest.Connectors.ResultCode.Error; resultContext.AddResultDetail(new MARC.Everest.Connectors.NotSupportedChoiceResultDetail(MARC.Everest.Connectors.ResultDetailType.Error, System.String.Format(\"Type {{0}} is not a valid choice according to available choice elements\", instance.{0}.GetType()), s.ToString(), null)); }}", pi.Name)));
                        }
                        #endregion
                    }
                    else
                    {
                        #region Property is a Structural, or NonStructural property
                        PropertyAttribute pa = propertyAttribute;
                        if (pa.DefaultUpdateMode != MARC.Everest.DataTypes.UpdateMode.Unknown && piType.GetProperty("UpdateMode") != null)
                        {
                            methodBody.Add(new CodeSnippetExpression(String.Format("if(instance.{0}.UpdateMode == null && (host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowUpdateModeImposing) == MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowUpdateModeImposing) instance.{0}.UpdateMode = MARC.Everest.DataTypes.UpdateMode.{1}", pi.Name, pa.DefaultUpdateMode)));
                        }
                        if (pa.ImposeFlavorId != null && piType.GetProperty("Flavor") != null)
                        {
                            methodBody.Add(new CodeSnippetExpression(String.Format("if((host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowFlavorImposing) == MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowFlavorImposing) instance.{0}.Flavor = \"{1}\"", pi.Name, pa.ImposeFlavorId)));
                        }
                        if (pa.SupplierDomain != null && piType.GetProperty("CodeSystem") != null)
                        {
                            methodBody.Add(new CodeSnippetExpression(String.Format("if((host.Settings & MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowSupplierDomainImposing) == MARC.Everest.Formatters.XML.ITS1.SettingsType.AllowSupplierDomainImposing && System.String.IsNullOrEmpty(instance.{0}.CodeSystem) && instance.{0}.NullFlavor == null) instance.{0}.CodeSystem = \"{1}\"", pi.Name, pa.SupplierDomain)));
                        }

                        // Write attribute/element
                        if (pa.PropertyType == PropertyAttribute.AttributeAttributeType.Structural) // Attribute
                        {
                            methodBody.Add(new CodeSnippetExpression(String.Format("s.WriteAttributeString(\"{0}\", MARC.Everest.Connectors.Util.ToWireFormat(instance.{1}))", pa.Name, pi.Name)));
                        }
                        else if (piInterfaces.Contains(typeof(IGraphable))) // Non Graphable
                        {
                            if (piInterfaces.Contains(typeof(IColl)))
                            {
                                methodBody.Add(new CodeSnippetStatement(String.Format("if(!instance.{0}.IsEmpty || instance.{0}.NullFlavor != null)", pi.Name)));
                            }
                            retValChanged = true;
                            methodBody.Add(new CodeSnippetExpression(String.Format("Host.WriteElementUtil(s, \"{3}\", \"{0}\", (MARC.Everest.Interfaces.IGraphable)instance.{1}, typeof({2}), context, resultContext)", pa.Name, pi.Name, CreateTypeReference(new CodeTypeReference(pi.PropertyType)), pa.NamespaceUri)));
                        }
                        else if (piInterfaces.Contains(typeof(ICollection))) // List
                        {
                            // Is this a collection
                            Type lType = pi.PropertyType;
                            if (lType.GetGenericArguments().Length > 0)
                            {
                                lType = lType.GetGenericArguments()[0];
                            }
                            methodBody.Add(new CodeSnippetStatement(String.Format("foreach(MARC.Everest.Interfaces.IGraphable ig in instance.{0}) {{ Host.WriteElementUtil(s, \"{3}\", \"{1}\", ig, typeof({2}), context, resultContext); }}", pi.Name, pa.Name, CreateTypeReference(new CodeTypeReference(lType)), pa.NamespaceUri)));
                            retValChanged = true;
                        }
                        else // Not recognized
                        {
                            methodBody.Add(new CodeSnippetExpression(String.Format("s.WriteElementString(\"{0}\", \"urn:hl7-org:v3\", instance.{1}.ToString())", pa.Name, pi.Name)));
                        }
                        #endregion

                        lastWasAttribute = pa.PropertyType == PropertyAttribute.AttributeAttributeType.Structural;
                    }

                    //if(pi.Name != "NullFlavor")
                    //    methodBody.Add(new CodeSnippetStatement("}")); // Finish the if that encapsulates this property code
                    methodBody.Add(new CodeSnippetStatement("}")); // Finish the if that encapsulates this property code

                    #endregion
                }
            }

            //if (forType.GetProperty("NullFlavor") != null && !forTypeNullFlavor)
            //    methodBody.Append("}");

            // End interaction
            if (structureAttribute.StructureType == StructureAttribute.StructureAttributeType.Interaction || structureAttribute.IsEntryPoint)
            {
                methodBodyEle.Add(new CodeSnippetExpression("if(isEntryPoint) s.WriteEndElement()")); // End Interaction
            }
            // Create stuff finally
            method.Statements.Add(new CodeSnippetExpression(string.Format("{0} instance = o as {0};", trefTypeReference)));
            method.Statements.AddRange(methodBodyAtt);
            method.Statements.AddRange(methodBodyEle);

            return(method);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Create a value from an Everest enum
        /// </summary>
        /// TODO: Optimize this
        private ValueSet CreateValueFromEverestEnum(Type enumType)
        {
            StructureAttribute structAtt = enumType.GetCustomAttribute <StructureAttribute>();
            var baseUri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString();

            ValueSet retVal = new ValueSet();

            retVal.Name       = structAtt.Name;
            retVal.Identifier = structAtt.CodeSystem;
            retVal.Id         = retVal.Identifier;
            // Use the company attribute
            var companyAtt = enumType.Assembly.GetCustomAttribute <AssemblyCompanyAttribute>();

            if (companyAtt != null)
            {
                retVal.Publisher = companyAtt.Company;
            }
            var versionAtt = enumType.Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>();

            if (versionAtt != null)
            {
                retVal.Version = versionAtt.InformationalVersion;
            }
            retVal.VersionId = retVal.Version;

            // Date of the assembly file
            if (!String.IsNullOrEmpty(enumType.Assembly.Location) && File.Exists(enumType.Assembly.Location))
            {
                retVal.Date = new SVC.Messaging.FHIR.DataTypes.DateOnly()
                {
                    DateValue = new FileInfo(enumType.Assembly.Location).LastWriteTime
                }
            }
            ;
            retVal.Timestamp = retVal.Date.DateValue.Value;
            retVal.Status    = new SVC.Messaging.FHIR.DataTypes.PrimitiveCode <string>("published");

            // Compose the codes if it has codes from a known code system
            var  enumFields         = enumType.GetFields();
            bool hasRegisteredCodes = Array.Exists(enumFields, (f) =>
            {
                var enumAtt = f.GetCustomAttribute <EnumerationAttribute>();
                if (enumAtt != null)
                {
                    return(ApplicationContext.ConfigurationService.OidRegistrar.FindData(enumAtt.SupplierDomain) != null);
                }
                else
                {
                    return(false);
                }
            }), hasDifferentSuppliers = Array.Exists(enumFields, (f) => {
                var enumAtt = f.GetCustomAttribute <EnumerationAttribute>();
                if (enumAtt != null)
                {
                    return(Array.Exists(enumFields, (fi) =>
                    {
                        var ienumAtt = fi.GetCustomAttribute <EnumerationAttribute>();
                        if (ienumAtt != null)
                        {
                            return ienumAtt.SupplierDomain != enumAtt.SupplierDomain;
                        }
                        return false;
                    }));
                }
                else
                {
                    return(false);
                }
            });

            // Compose or define
            var sysOid = ApplicationContext.ConfigurationService.OidRegistrar.FindData(retVal.Identifier);

            if (sysOid != null)
            {
                retVal.Compose = new ComposeDefinition();
                retVal.Compose.Import.Add(new SVC.Messaging.FHIR.DataTypes.FhirUri(sysOid.Ref));
            }
            else if (hasRegisteredCodes || hasDifferentSuppliers)
            {
                retVal.Compose = new ComposeDefinition();
                // Group like items
                Array.Sort(enumFields, (a, b) =>
                {
                    EnumerationAttribute aAtt = a.GetCustomAttribute <EnumerationAttribute>(),
                    bAtt = b.GetCustomAttribute <EnumerationAttribute>();
                    if ((aAtt == null) ^ (bAtt == null))
                    {
                        return(aAtt == null ? -1 : 1);
                    }
                    else if (aAtt == bAtt)
                    {
                        return(0);
                    }
                    return(aAtt.SupplierDomain.CompareTo(bAtt.SupplierDomain));
                });
                // Build the concept sets
                ConceptSet currentSet = null;
                foreach (var itm in enumFields)
                {
                    EnumerationAttribute enumValue = itm.GetCustomAttribute <EnumerationAttribute>();
                    if (enumValue == null)
                    {
                        continue;
                    }

                    // Extract code system
                    var oidData    = ApplicationContext.ConfigurationService.OidRegistrar.FindData(enumValue.SupplierDomain);
                    Uri codeSystem = oidData == null ? new Uri(String.Format("urn:oid:{0}", enumValue.SupplierDomain)) : oidData.Ref;

                    // add current set and construct
                    if (currentSet == null || !currentSet.System.Value.Equals(codeSystem))
                    {
                        currentSet = new ConceptSet()
                        {
                            System = codeSystem
                        };
                        retVal.Compose.Include.Add(currentSet);
                    }

                    // Now add mnemonic
                    currentSet.Code.Add(new SVC.Messaging.FHIR.DataTypes.PrimitiveCode <string>(enumValue.Value));
                }
            }
            else
            {
                // Create a definition for a valueset
                retVal.Define        = new ValueSetDefinition();
                retVal.Define.System = new Uri(String.Format("{0}/ValueSet/@v3-{1}", baseUri, structAtt.Name));
                foreach (var itm in enumFields)
                {
                    EnumerationAttribute enumValue = itm.GetCustomAttribute <EnumerationAttribute>();
                    if (enumValue == null)
                    {
                        continue;
                    }
                    DescriptionAttribute description = itm.GetCustomAttribute <DescriptionAttribute>();
                    retVal.Define.Concept.Add(new ConceptDefinition()
                    {
                        Code     = new SVC.Messaging.FHIR.DataTypes.PrimitiveCode <string>(enumValue.Value),
                        Abstract = false,
                        Display  = description == null ? itm.Name : description.Description
                    });
                }
            }

            return(retVal);
        }
    }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            Console.WriteLine("XML ITS1 Formatter Pregenerator Utility");
            Console.WriteLine("Copyright (C) 2012, Mohawk College of Applied Arts and Technology");

            ParameterParser <Parameters> parser = new ParameterParser <Parameters>();

            try
            {
                var arguments = parser.Parse(args);

                if (arguments.ShowHelp)
                {
                    ShowHelp();
                    return;
                }
                // Generate formatter utility
                MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator creator = new MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator();

                // Create code namespace
                CodeNamespace ns = new CodeNamespace(arguments.TargetNs);
                // Load assembly
                Assembly rmimAssembly = Assembly.LoadFile(arguments.AssemblyFile);

                List <Type> rmimTypes = new List <Type>();

                if (arguments.Interactions != null)
                {
                    foreach (var s in arguments.Interactions)
                    {
                        rmimTypes.Add(rmimAssembly.GetTypes().First(o => o.Name == s));
                    }
                }
                else
                {
                    rmimTypes.AddRange(rmimAssembly.GetTypes());
                }

                // Validate parameters
                if (rmimTypes.Count == 0)
                {
                    throw new ArgumentException("Type array must have at least one element", "t");
                }

                // Create a list of types (a todo list) that represent the types we want to format
                List <Type> types = new List <Type>(200);

                // Iterate through types and create formatter
                // Iterate throgh the types
                foreach (Type type in rmimTypes)
                {
                    if (type.Assembly != rmimAssembly)
                    {
                        throw new InvalidOperationException("All types must belong to the same revision assembly");
                    }
                    GetUniqueTypes(type, types, true);
                }


                // Waith thread pool
                WaitThreadPool wtp = new WaitThreadPool();
                try
                {
                    // Create type definitions
                    foreach (Type t in types)
                    {
                        // Check if we need to gen this type
                        if (t.GetCustomAttributes(typeof(StructureAttribute), false).Length == 0 ||
                            s_formatterGenerated.Contains(t))
                        {
                            continue;
                        }

                        s_formatterGenerated.Add(t);

                        // Structure Attribute
                        StructureAttribute sta = t.GetCustomAttributes(typeof(StructureAttribute), false)[0] as StructureAttribute;

                        // Type formatter creator
                        TypeFormatterCreator crtr = new TypeFormatterCreator();

                        // Reset event
                        crtr.CodeTypeDeclarationCompleted += new CreateTypeFormatterCompletedDelegate(delegate(CodeTypeDeclaration result)
                        {
                            // Add to the code currently created
                            if (result != null)
                            {
                                lock (ns)
                                    ns.Types.Add(result);
                            }
                        });

                        // Helper result
                        wtp.QueueUserWorkItem(crtr.CreateTypeFormatter, t);
                    }

                    // Wait for final pool to clear
                    wtp.WaitOne();
                }
                finally
                {
                    wtp.Dispose();
                }

                if (ns.Types.Count == 0)
                {
                    Console.WriteLine("Didn't create any formatter helpers...");
                    return;
                }



                // Setup compiler and referenced assemblies
                CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();


                using (TextWriter tw = File.CreateText(arguments.Output ?? "output.cs"))
                    csharpCodeProvider.GenerateCodeFromNamespace(ns, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()
                    {
                        IndentString = "\t"
                    });
            }
            catch (ArgumentNullException)
            {
                ShowHelp();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return;
            }
            finally
            {
            }

#if DEBUG
            Console.ReadKey();
#endif
        }