Ejemplo n.º 1
0
        private void UpdateExtensionStructureDefinitionForUsage(StructureDefinition sd, string typeName, string context)
        {
            bool updated = false;

            // Check the context (and add it)
            if (!sd.Context.Any(uc => uc.Type == StructureDefinition.ExtensionContextType.Fhirpath && uc.Expression == context))
            {
                // Need to include this context too
                sd.Context.Add(new StructureDefinition.ContextComponent()
                {
                    Type       = StructureDefinition.ExtensionContextType.Fhirpath,
                    Expression = context
                });
                updated = true;
            }

            // Check the datatype
            if (!sd.Differential.Element.Any(e => e.Path == "Extension.value[x]" && e.Type.Any(t => t.Code == typeName)))
            {
                sd.Differential.Element.FirstOrDefault(e => e.Path == "Extension.value[x]").Type.Add(new ElementDefinition.TypeRefComponent()
                {
                    Code = typeName
                });
                updated = true;
            }
            // Store the StructureDefinition
            if (updated)
            {
                SaveStructureDefinition(sd);
            }
        }
Ejemplo n.º 2
0
        void LoadFhirElement(StructureDefinition sDef)
        {
            const String fcn = "LoadFhirElement";

            /*
             * Eliminate all but the top level resources to simplify things.
             * Add them in later????
             */
            if (sDef.Type != sDef.Name)
            {
                this.ConversionWarn(this.GetType().Name, fcn, $"Skipping resource {sDef.Name}");
                return;
            }

            SDefInfo sDefInfo = new SDefInfo
            {
                SDef = sDef
            };

            switch (sDef.Url)
            {
            case "http://hl7.org/fhir/StructureDefinition/Element":
                sDefInfo.TFlag = SDefInfo.TypeFlag.Element;
                break;

            case "http://hl7.org/fhir/StructureDefinition/Resource":
                sDefInfo.TFlag = SDefInfo.TypeFlag.Resource;
                break;

            default:
                sDefInfo.TFlag = SDefInfo.TypeFlag.Unknown;
                break;
            }
            this.items.Add(sDef.Url, sDefInfo);
        }
Ejemplo n.º 3
0
        void LoadFhirElement(StructureDefinition sDef)
        {
            const String fcn = "LoadFhirElement";

            // This is to eliminate the derived types. For now,
            // we only want to do that base resource types.
            if (sDef.Type != sDef.Name)
            {
                this.ConversionWarn(this.GetType().Name, fcn, $"Skipping derived class {sDef.Name}");
                return;
            }
            SDefInfo sDefInfo = new SDefInfo(sDef);

            switch (sDef.Url)
            {
            case "http://hl7.org/fhir/StructureDefinition/Element":
                sDefInfo.TFlag = SDefInfo.TypeFlag.Group;
                break;

            case "http://hl7.org/fhir/StructureDefinition/Resource":
                sDefInfo.TFlag = SDefInfo.TypeFlag.Entry;
                break;

            default:
                sDefInfo.TFlag = SDefInfo.TypeFlag.Unknown;
                break;
            }

            this.items.Add(sDef.Url, sDefInfo);
        }
        /// <summary>
        /// Rewrites the Path's of the elements in a structure so they are based on the given path: the root
        /// of the given structure will become the given path, it's children will be relocated below that path
        /// </summary>
        /// <param name="root">The structure that will be rebased on the path</param>
        /// <param name="path">The path to rebase the structure on</param>
        public static void Rebase(this StructureDefinition root, string path)
        {
            var nav = new ElementNavigator(root);

            if (nav.MoveToFirstChild())
            {
                var newPaths = new List <string>()
                {
                    path
                };

                rebaseChildren(nav, path, newPaths);

                var snapshot = root.Snapshot.Element;

                // Can only change the paths after navigating the tree, otherwise the
                // navigation functions (which are based on the paths) won't function correctly
                for (var i = 0; i < root.Snapshot.Element.Count; i++)
                {
                    root.Snapshot.Element[i].Path = newPaths[i];
                }

                root.Differential = null;       // this is now invalid, because the snapshot has changed
            }
        }
Ejemplo n.º 5
0
        public void SaveStructureDefinition(StructureDefinition sd)
        {
            // Ensure the folder exists
            Uri    t = new Uri(sd.Url);
            string profileOutputDirectory = Path.Combine(_outputProfilePath, t.Host);

            if (!Directory.Exists(profileOutputDirectory))
            {
                Directory.CreateDirectory(profileOutputDirectory);
            }

            // Non extensions will just go in the root of the output
            if (sd.BaseDefinition != "http://hl7.org/fhir/StructureDefinition/Extension")
            {
                profileOutputDirectory = _outputProfilePath;
            }

            // Now output the file
            System.IO.File.WriteAllText($"{profileOutputDirectory}/StructureDefinition-{sd.Id}.xml", new FhirXmlSerializer(new SerializerSettings()
            {
                AppendNewLine = true, Pretty = true
            }).SerializeToString(sd));

            // And add it to our resolver
            sourceSD.InvalidateByCanonicalUri(sd.Url);
            ds.Refresh();

            // And check that it comes back...
            var instSD = sourceSD.ResolveByUri(sd.Url) as StructureDefinition;

            if (instSD == null)
            {
                Console.WriteLine($"Was not able to resolve the newly created extension");
            }
        }
Ejemplo n.º 6
0
        void FixDifferential(ProcessItem processedItem)
        {
            const String        fcn  = "FixDifferentials";
            StructureDefinition sDef = (StructureDefinition)processedItem.Resource;

            this.ConversionInfo(this.GetType().Name,
                                fcn,
                                $"Computing differential for {processedItem.Resource.GetName()}");

            ElementTreeNode differentialNode = processedItem.SnapNode.Clone();
            {
                ElementTreeDiffer differ = new ElementTreeDiffer(this);
                if (differ.Process(processedItem.SnapNodeOriginal, differentialNode) == false)
                {
                    return;
                }
            }
            {
                ElementTreeSetBase setBase = new ElementTreeSetBase(this);
                if (setBase.Process(processedItem.SnapNodeOriginal, differentialNode) == false)
                {
                    return;
                }
            }

            {
                processedItem.DiffNode = differentialNode;
                List <ElementDefinition> elementDefinitions = new List <ElementDefinition>();
                differentialNode.CopyTo(elementDefinitions);
                sDef.Differential.Element = elementDefinitions;
            }
        }
Ejemplo n.º 7
0
        internal static StructureDefinition AddComponentLink(this StructureDefinition sd,
                                                             String url,
                                                             SDefEditor.Cardinality cardinalityLeft,
                                                             SDefEditor.Cardinality cardinalityRight,
                                                             String componentRef,
                                                             String types,
                                                             params String[] targets)
        {
            dynamic packet = new JObject();

            packet.LinkType     = SVGGlobal.ComponentType;
            packet.ShowChildren = false;
            if (cardinalityLeft != null)
            {
                packet.CardinalityLeft = cardinalityLeft.ToString();
            }
            packet.LinkTarget    = url;
            packet.ComponentHRef = componentRef;
            packet.Types         = types;
            packet.References    = new JArray(targets);
            if (cardinalityRight != null)
            {
                packet.CardinalityRight = cardinalityRight.ToString();
            }
            sd.AddExtension(Global.ResourceMapLinkUrl, new FhirString(packet.ToString()));
            return(sd);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Fix errors in differentia.
        /// The tools will celan out the min and max values if they are unchanged from the base, so here
        /// we put them back in because they are required.
        /// </summary>
        /// <param name="processedItem"></param>
        /// <param name="sDef"></param>
        void CleanupDifferential(ProcessItem item,
                                 StructureDefinition sDef)
        {
            foreach (ElementDefinition ed in sDef.Differential.Element.Skip(1))
            {
                if ((ed.Min.HasValue == false) ||
                    (String.IsNullOrEmpty(ed.Max)))
                {
                    if (item.SnapNode == null)
                    {
                        ElementTreeLoader l = new ElementTreeLoader(this);
                        item.SnapNode = l.Create(item.SDef.Snapshot.Element);
                    }

                    ElementTreeNode snapNode;
                    if (item.SnapNode.TryGetElementNode(ed.ElementId, out snapNode) == false)
                    {
                        item.SnapNode.TryGetElementNode(ed.Path, out snapNode);
                    }
                    if (snapNode != null)
                    {
                        ed.Min = snapNode.ElementDefinition.Min;
                        ed.Max = snapNode.ElementDefinition.Max;
                    }
                }
            }
        }
        public static ElementNavigator JumpToNameReference(this StructureDefinition elements, string nameReference)
        {
            var nav = new ElementNavigator(elements);

            //TODO: In the current DSTU1 base profiles, nameReference is actually a path, not a name (to Element.Name)
            //this is a problem, since when doing slicing, the path may no longer point to a single set of constraints
            //so, we need to (temporarily) watch out for this
            if (nameReference.Contains("."))
            {
                // An incorrectly used nameReference, containing a Path, not a name
                if (nav.JumpToFirst(nameReference))
                {
                    return(nav);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                if (nav.JumpToNameReference(nameReference))
                {
                    return(nav);
                }
                else
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 10
0
        public SDefEditor AddFragRef(StructureDefinition sd)
        {
            if (sd.IsFragment() == false)
            {
                throw new Exception("Expected a fragment");
            }

            String fragRef = sd.Url;

            if (String.IsNullOrWhiteSpace(fragRef))
            {
                throw new Exception($"Fragment Url must not be empty");
            }
            this.SDef.Extension.Add(new Extension
            {
                Url   = PreFhirGenerator.FragmentUrl,
                Value = new FhirUrl(fragRef)
            });

            dynamic packet = new JObject();

            packet.LinkType     = "fragment";
            packet.ShowChildren = false;
            packet.LinkTarget   = sd.Url;
            this.SDef.AddExtension(Global.ResourceMapLinkUrl, new FhirString(packet.ToString()));
            return(this);
        }
Ejemplo n.º 11
0
        void AddReferences(HashSet <String> referencedFrags,
                           String fragmentDir,
                           StructureDefinition sd)
        {
            const String fcn = "ProcessOne";

            FhirJsonParser parser = new FhirJsonParser();

            foreach (String fragmentUrl in sd.ReferencedFragments())
            {
                String fragmentPath = FragPath(fragmentDir, fragmentUrl.LastUriPart());
                if (File.Exists(fragmentPath) == false)
                {
                    this.ConversionError(this.GetType().Name,
                                         fcn,
                                         $"Missing fragment file {fragmentPath}");
                }
                if (referencedFrags.Contains(fragmentPath) == false)
                {
                    referencedFrags.Add(fragmentPath);
                    StructureDefinition frag = parser.Parse <StructureDefinition>(File.ReadAllText(fragmentPath));
                    this.AddFragment(frag);
                    AddReferences(referencedFrags, fragmentDir, frag);
                }
            }
        }
Ejemplo n.º 12
0
        StructureDefinition CreateFragment(String name, String url)
        {
            StructureDefinition frag = new StructureDefinition
            {
                Abstract       = true,
                Kind           = StructureDefinition.StructureDefinitionKind.Resource,
                FhirVersion    = FhirVersion,
                Name           = name,
                Description    = new Markdown("Fragment"),
                Url            = url,
                Version        = ProfileVersion,
                Date           = this.date.ToString(),
                Status         = ProfileStatus,
                Publisher      = "Hl7-Clinical Interoperability Council",
                Contact        = this.Contact(),
                Differential   = new StructureDefinition.DifferentialComponent(),
                BaseDefinition = "http://hl7.org/fhir/StructureDefinition/Resource",
                Type           = "Resource"
            };

            frag.Extension.Add(new Extension
            {
                Url   = PreFhirGenerator.IsFragmentUrl,
                Value = new FhirBoolean(true)
            });
            frag.AddDiffElement(new ElementDefinition
            {
                Path      = name,
                ElementId = name,
                Min       = 0,
                Max       = "*"
            });
            return(frag);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Create structure definition editor
        /// </summary>
        public SDefEditor(IConversionInfo info,
                          String name,
                          String url,
                          String baseDefinition,
                          String mapName,
                          String fragmentDir,
                          String pageDir)
        {
            this.info        = info;
            this.fragmentDir = fragmentDir;
            this.pageDir     = pageDir;
            this.baseSDef    = FhirStructureDefinitions.Self.GetResource(baseDefinition);
            if (this.baseSDef == null)
            {
                throw new Exception($"'Base definition resource {baseDefinition}' not found");
            }

            this.basePath = baseDefinition.LastUriPart();

            {
                ElementTreeLoader l = new ElementTreeLoader();
                this.snapNode         = l.Create(this.baseSDef.Snapshot.Element);
                this.snapNodeOriginal = this.snapNode.Clone();
            }

            this.sDef = new StructureDefinition
            {
                Name           = name,
                Url            = url,
                BaseDefinition = baseDefinition,
                Differential   = new StructureDefinition.DifferentialComponent()
            };

            this.SDef.AddExtension(Global.ResourceMapNameUrl, new FhirString(mapName));
        }
Ejemplo n.º 14
0
        public IEnumerable <Struct> ReadStructs(object obj, ProfileConverterOptions opts)
        {
            var xd         = (XDocument)obj;
            var rawStructs = xd.Element("registry")?.Element("types")?.Elements("type")
                             .Where(typex => typex.HasCategoryAttribute("struct"))
                             .Select(typex => StructureDefinition.CreateFromXml(typex))
                             .ToArray();
            var structs = ConvertStructs(rawStructs, opts);

            foreach (var feature in xd.Element("registry").Elements("feature").Attributes("api").Select(x => x.Value).RemoveDuplicates())
            {
                foreach (var(_, s) in structs)
                {
                    yield return(new Struct
                    {
                        Attributes = s.Attributes,
                        ExtensionName = "Core",
                        Fields = s.Fields,
                        Functions = s.Functions,
                        Name = s.Name,
                        NativeName = s.NativeName,
                        ProfileName = feature,
                        ProfileVersion = null
                    });
                }
            }

            opts.TypeMaps.Add(structs.ToDictionary(x => x.Key, x => x.Value.Name));
        }
Ejemplo n.º 15
0
        public async void GetValue_WithObjectInsideStructureAndRightJson_ShouldReturnItemsValues()
        {
            var structure = new StructureDefinition
            {
                Id     = "test",
                Fields = new List <Field>
                {
                    new Field
                    {
                        Id        = "test_address",
                        Name      = "address",
                        DataType  = DataTypeEnum.Object,
                        Nullable  = false,
                        Structure = new StructureDefinition
                        {
                            Id     = "address",
                            Name   = "address",
                            Fields = new List <Field>
                            {
                                Field.NotNullString("test_city", "city"),
                                Field.NotNullString("test_country", "country")
                            }
                        }
                    }
                }
            };

            var city = await structure.GetValue("address.city", JsonSerializer.Serialize(new { address = new { city = "Tabriz", country = "Iran" } }));

            Assert.Equal("Tabriz", city);
        }
Ejemplo n.º 16
0
        public async void ValidateJsonStructure_WithNotNullElementAndNotGivenValueInsideJson_ShouldReturnFalse()
        {
            var structure = new StructureDefinition
            {
                Id     = "test",
                Fields = new List <Field>
                {
                    new Field
                    {
                        Id       = "test_city",
                        Name     = "city",
                        DataType = DataTypeEnum.String,
                        Nullable = false
                    },
                    new Field
                    {
                        Id       = "test_country",
                        Name     = "country",
                        DataType = DataTypeEnum.String,
                        Nullable = false
                    }
                }
            };

            Assert.False(await structure.ValidateJsonStructure(new { city = "Tabriz" }));
        }
Ejemplo n.º 17
0
 public ConvertFhirClass(DirectFhirGenerator gen,
                         DirectFhirGenerator.SDefInfo sDefInfo)
 {
     this.sDefInfo = sDefInfo;
     this.gen      = gen;
     this.sDef     = this.sDefInfo.SDef;
 }
        public void TestSuccessfulCreate()
        {
            MockObjectRepository mockRepo = new MockObjectRepository();

            mockRepo.InitializeFHIR2Repository();
            mockRepo.InitializeLCG();

            var dafPatientJson           = Helper.GetSampleContents("Trifolia.Test.DocSamples.daf-patient_struc_def.json");
            StructureDefinition strucDef = (StructureDefinition)FhirParser.ParseResourceFromJson(dafPatientJson);

            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://localhost:8080/api/FHIR2/StructureDefinition");

            HttpRequest  contextRequest  = new HttpRequest(null, "http://localhost:8080/api/FHIR2/StructureDefinition", null);
            HttpResponse contextResponse = new HttpResponse(new StringWriter());

            HttpContext.Current = new HttpContext(contextRequest, contextResponse);

            FHIR2StructureDefinitionController controller = new FHIR2StructureDefinitionController(mockRepo, request);
            var response = controller.CreateStructureDefinition(strucDef);
            var result   = AssertHelper.IsType <TrifoliaApiController.CustomHeadersWithContentResult <StructureDefinition> >(response);

            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
            Assert.IsNotNull(result.CustomHeaders["Location"]);
            Assert.AreEqual(result.CustomHeaders["Location"], "http://localhost:8080/api/FHIR2/StructureDefinition/1");

            Assert.IsNotNull(result.Content);
            Assert.AreEqual(strucDef.Name, result.Content.Name);
        }
        public void TestFailedCreate_Id()
        {
            MockObjectRepository mockRepo = new MockObjectRepository();

            mockRepo.InitializeFHIR2Repository();
            mockRepo.InitializeLCG();

            var dafPatientJson           = Helper.GetSampleContents("Trifolia.Test.DocSamples.daf-patient_struc_def.json");
            StructureDefinition strucDef = (StructureDefinition)FhirParser.ParseResourceFromJson(dafPatientJson);

            strucDef.Id = "daf-patient";

            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://localhost:8080/api/FHIR2/StructureDefinition");

            HttpRequest  contextRequest  = new HttpRequest(null, "http://localhost:8080/api/FHIR2/StructureDefinition", null);
            HttpResponse contextResponse = new HttpResponse(new StringWriter());

            HttpContext.Current = new HttpContext(contextRequest, contextResponse);

            FHIR2StructureDefinitionController controller = new FHIR2StructureDefinitionController(mockRepo, request);
            var response = controller.CreateStructureDefinition(strucDef);
            var result   = AssertHelper.IsType <NegotiatedContentResult <OperationOutcome> >(response);

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);

            Assert.IsNotNull(result.Content);
            Assert.AreEqual(1, result.Content.Issue.Count);
        }
Ejemplo n.º 20
0
        protected void WriteStructure(StringBuilder sb, StructureDefinition sd)
        {
            sb.AppendLine($"struct {CSharpToShaderType(sd.Name)}");
            sb.AppendLine("{");
            StringBuilder fb = new StringBuilder();

            foreach (FieldDefinition field in sd.Fields)
            {
                string fieldTypeStr = GetStructureFieldType(field);
                fb.Append(fieldTypeStr);
                fb.Append(' ');
                fb.Append(CorrectIdentifier(field.Name.Trim()));
                int arrayCount = field.ArrayElementCount;
                if (arrayCount > 0)
                {
                    fb.Append('['); fb.Append(arrayCount); fb.Append(']');
                }
                fb.Append(';');
                sb.Append("    ");
                sb.AppendLine(fb.ToString());
                fb.Clear();
            }
            sb.AppendLine("};");
            sb.AppendLine();
        }
Ejemplo n.º 21
0
        void Create_NoModObservation(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("NoModObservation");

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
        }
Ejemplo n.º 22
0
        public void TestVertexShader_VertexSemantics()
        {
            string          functionName = "TestShaders.TestVertexShader.VS";
            Compilation     compilation  = TestUtil.GetTestProjectCompilation();
            HlslBackend     backend      = new HlslBackend(compilation);
            ShaderGenerator sg           = new ShaderGenerator(
                compilation,
                functionName,
                null,
                backend);
            ShaderGenerationResult             genResult = sg.GenerateShaders();
            IReadOnlyList <GeneratedShaderSet> sets      = genResult.GetOutput(backend);

            Assert.Equal(1, sets.Count);
            ShaderModel shaderModel = sets[0].Model;

            StructureDefinition vsInput = shaderModel.GetStructureDefinition(nameof(TestShaders) + "." + nameof(PositionTexture));

            Assert.Equal(SemanticType.Position, vsInput.Fields[0].SemanticType);
            Assert.Equal(SemanticType.TextureCoordinate, vsInput.Fields[1].SemanticType);

            StructureDefinition fsInput = shaderModel.GetStructureDefinition(
                nameof(TestShaders) + "." + nameof(TestVertexShader) + "+" + nameof(TestVertexShader.VertexOutput));

            Assert.Equal(SemanticType.Position, fsInput.Fields[0].SemanticType);
            Assert.Equal(SemanticType.TextureCoordinate, fsInput.Fields[1].SemanticType);
        }
        public void DumpReferences(StructureDefinition sd)
        {
            Debug.WriteLine("References for StructureDefinition '{0}' ('{1}')".FormatWith(sd.Name, sd.Url));
            Debug.WriteLine("Base = '{0}'".FormatWith(sd.Base));

            var profiles = sd.Snapshot.Element.SelectMany(e => e.Type).SelectMany(t => t.Profile);

            profiles = profiles.OrderBy(p => p).Distinct();

            // FhirClient client = new FhirClient("http://fhir2.healthintersections.com.au/open/");
            // var folderPath = Path.Combine(Directory.GetCurrentDirectory(), @"TestData\snapshot-test\download");
            // if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); }

            foreach (var profile in profiles)
            {
                Debug.WriteLine(profile);

                // How to determine the original filename?
                //try
                //{
                //    var xml = client.Get(profile);
                //    var filePath = Path.Combine()
                //    File.WriteAllText(folderPath, )
                //}
                //catch (Exception ex)
                //{
                //    Debug.WriteLine(ex.Message);
                //}
            }
        }
Ejemplo n.º 24
0
        void Create_Fixed(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("Fixed");

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.identifier");
                e.Min   = 0;
                e.Max   = "1";
                e.Fixed = new Identifier("fixedIdentifierSystem", "fixedIdentifierValue");
            }
            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.status");
                e.Fixed = new Code("cancelled");
                e.Min   = 1;
                e.Max   = "1";
            }
            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.code");
                e.Min   = 0;
                e.Max   = "1";
                e.Fixed = new CodeableConcept("codeSystem", "codeCode", "codeDisplay", "codeText");
            }

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
            profile.SaveJson($@"c:\Temp\{profile.Name}.json");
        }
Ejemplo n.º 25
0
        StructureDefinition CreateObservation(String name)
        {
            StructureDefinition profile = new StructureDefinition
            {
                Url            = $"http://xxyyz.com/{name}",
                Name           = name,
                Title          = name,
                Description    = new Markdown("Profile on Observation with fixed values"),
                BaseDefinition = "http://hl7.org/fhir/StructureDefinition/Observation",
                Derivation     = StructureDefinition.TypeDerivationRule.Constraint,
                DateElement    = new FhirDateTime(2019, 1, 1, 0, 0, 0, new TimeSpan(0)),
                Publisher      = "Me",
                FhirVersion    = FVersion,
                Type           = "Observation",
                Kind           = StructureDefinition.StructureDefinitionKind.Resource,
                Abstract       = false,
                Differential   = new StructureDefinition.DifferentialComponent()
            };

            profile.Differential.Element.Add(
                new ElementDefinition
            {
                Path      = "Observation",
                ElementId = "Observation"
            });

            return(profile);
        }
        /// <summary>
        /// Build the StructureDefinition attribute for a complex type.
        /// </summary>
        public static void StructureDefinitionAttribute(
            this TypeBuilder typeBuilder,
            StructureDefinition structureDefinition)
        {
            var                    attributeType = typeof(StructureDefinitionAttribute);
            var                    baseDataType  = ComplexTypes.StructureDefinitionAttribute.FromBaseType(structureDefinition.BaseDataType);
            ConstructorInfo        ctorInfo      = attributeType.GetConstructor(Type.EmptyTypes);
            CustomAttributeBuilder builder       = new CustomAttributeBuilder(
                ctorInfo,
                new object[0],  // constructor arguments
                new[]           // properties to assign
            {
                attributeType.GetProperty("DefaultEncodingId"),
                attributeType.GetProperty("BaseDataType"),
                attributeType.GetProperty("StructureType")
            },
                new object[]    // values to assign
            {
                structureDefinition.DefaultEncodingId?.ToString(),
                baseDataType,
                structureDefinition.StructureType
            });

            typeBuilder.SetCustomAttribute(builder);
        }
Ejemplo n.º 27
0
        public void FindTemplate_Remote_Test()
        {
            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://test:100/");
            MockObjectRepository repo = new MockObjectRepository();

            repo.InitializeFHIR2Repository();
            repo.InitializeLCG();

            ResourceReference reference = new ResourceReference();

            reference.Reference = "http://test.com/FHIR/StructureDefinition/test";

            MockWebClient       webClient      = new MockWebClient();
            var                 dafPatientJson = Trifolia.Test.Helper.GetSampleContents("Trifolia.Test.DocSamples.daf-patient_struc_def.json");
            StructureDefinition strucDef       = (StructureDefinition)FhirParser.ParseResourceFromJson(dafPatientJson);

            webClient.ExpectContent("http://test.com/FHIR/StructureDefinition/test", dafPatientJson);
            var foundTemplate = Shared.FindTemplate(request, webClient, repo, reference);

            Assert.IsNotNull(foundTemplate);
            Assert.AreEqual(1, foundTemplate.Id);
            Assert.AreEqual(strucDef.Name, foundTemplate.Name);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create a complex type from a StructureDefinition.
        /// Available since OPC UA V1.04 in the DataTypeDefinition attribute.
        /// </summary>
        public IComplexTypeFieldBuilder AddStructuredType(
            QualifiedName name,
            StructureDefinition structureDefinition)
        {
            if (structureDefinition == null)
            {
                throw new ArgumentNullException(nameof(structureDefinition));
            }
            Type baseType;

            switch (structureDefinition.StructureType)
            {
            case StructureType.StructureWithOptionalFields: baseType = typeof(OptionalFieldsComplexType); break;

            case StructureType.Union: baseType = typeof(UnionComplexType); break;

            case StructureType.Structure:
            default: baseType = typeof(BaseComplexType); break;
            }
            var structureBuilder = m_moduleBuilder.DefineType(
                GetFullQualifiedTypeName(name),
                TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable,
                baseType);

            structureBuilder.DataContractAttribute(m_targetNamespace);
            structureBuilder.StructureDefinitionAttribute(structureDefinition);
            return(new ComplexTypeFieldBuilder(structureBuilder, structureDefinition.StructureType));
        }
Ejemplo n.º 29
0
        public async void ValidateJsonStructure_WithNullableIntegerAndNotNullableStringWithWrongValue_ShouldReturnFalse()
        {
            var structure = new StructureDefinition
            {
                Id     = "test",
                Fields = new List <Field>
                {
                    new Field
                    {
                        Id       = "test_age",
                        Name     = "age",
                        DataType = DataTypeEnum.Integer,
                        Nullable = true
                    },
                    new Field
                    {
                        Id       = "test_name",
                        Name     = "name",
                        DataType = DataTypeEnum.String,
                        Nullable = false
                    }
                }
            };

            Assert.False(await structure.ValidateJsonStructure(new { name = "Yashar", age = "gfh" }));
        }
Ejemplo n.º 30
0
        protected void WriteStructure(ShaderFunction function, StringBuilder sb, StructureDefinition sd, ResourceDefinition resource)
        {
            if (resource != null)
            {
                if (resource.ResourceKind == ShaderResourceKind.Emit)
                {
                    sb.Append("out ");
                }
                else
                {
                    sb.Append("in ");
                }
                if (resource.ResourceKind == ShaderResourceKind.BuiltIn)
                {
                    sb.AppendLine(SemanticIdentifier(new ShaderBuiltin(function.Type.Stage(), resource.Semantic)));
                }
                else
                {
                    sb.AppendLine(CSharpToShaderType(sd.Name));
                }
            }
            else
            {
                sb.AppendLine($"struct {CSharpToShaderType(sd.Name)}");
            }
            sb.AppendLine("{");
            StringBuilder fb = new StringBuilder();

            foreach (FieldDefinition field in sd.Fields)
            {
                string fieldTypeStr = GetStructureFieldType(field);
                fb.Append(fieldTypeStr);
                fb.Append(' ');
                fb.Append(CorrectIdentifier(field.Name.Trim()));
                int arrayCount = field.ArrayElementCount;
                if (arrayCount > 0)
                {
                    fb.Append('['); fb.Append(arrayCount); fb.Append(']');
                }
                fb.Append(';');
                sb.Append("    ");
                sb.AppendLine(fb.ToString());
                fb.Clear();
            }
            sb.Append("}");
            if (resource != null)
            {
                sb.Append(" ");
                sb.Append(CorrectIdentifierName(resource.Name.Trim()));
                if (resource.ValueType.FixedSize > 0)
                {
                    sb.Append('[');
                    sb.Append(resource.ValueType.FixedSize);
                    sb.Append(']');
                }
            }
            sb.AppendLine(";");
            sb.AppendLine();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StructureValue"/> class.
        /// Values are populated with defaults
        /// </summary>
        /// <param name="theStructureDefinition">The structure definition.</param>
        /// <param name="parent">The parent.</param>
        public StructureValue(StructureDefinition theStructureDefinition, Value parent)
            : base(theStructureDefinition, parent)
        {
            m_StructureDefinition = theStructureDefinition;
            m_AttributeValues = new AttributeValueCollection(m_StructureDefinition.Name);

            foreach (var item in m_StructureDefinition.AttributeDefinitions)
            {
                AddAttributeValue(item, item.Type.Instantiate(this));
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StructureValue"/> class.
        /// </summary>
        /// <param name="theBytes">The bytes.</param>
        /// <param name="theStructureDefinition">The structure definition.</param>
        /// <param name="parent">The parent.</param>
        public StructureValue(ByteStore theBytes, StructureDefinition theStructureDefinition, Value parent)
            : base(theStructureDefinition, parent)
        {
            m_StructureDefinition = theStructureDefinition;
            m_AttributeValues = new AttributeValueCollection(m_StructureDefinition.Name); 

            int startPosition = theBytes.ReadPosition;
            foreach (var attribute in m_StructureDefinition.AttributeDefinitions)
            {
                int localOffset = theBytes.ReadPosition - startPosition;

                // Adjust alignment within current structure 
                if (attribute.ByteOffset.HasValue)
                {
                    while (attribute.ByteOffset.Value > localOffset)
                    {
                        theBytes.GetByte();
                        localOffset++;
                    }
                }

                // Error handling - trap decode errors for structure attributes and replace the attribute
                // value with an error value
                try
                {
                    // Decode the value from the binary data
                    Value theValue = attribute.Type.Decode(theBytes, this);

                    // Values decoded from switch cases need to have their name tweaked
                    if (attribute.Type.TypeId == TypeId.SwitchType)
                    {
                        SwitchDefinition switchDefinition = attribute.Type as SwitchDefinition;
                        SwitchCaseDefinition theCase = switchDefinition.GetSwitchCaseDefinition(this);
                        AddAttributeValue(attribute, theCase.Name, theValue);
                    }
                    else
                    {
                        AddAttributeValue(attribute, theValue);
                    }
                }
                catch (DataDictionaryException ex)
                {
                    AddAttributeValue(attribute, new ErrorValue (string.Format ("{0} Error: {1}", InitialType.Name, ex.Message), this));
                    throw new PartialDecodeException(GetTopParent(), ex.Message);
                }
            }
        }
 public DefaultObjectStructure(StructureDefinition typeDef)
     : base(typeDef)
 {
 }
Ejemplo n.º 34
0
 protected BaseObjectStructure(StructureDefinition typeDef)
 {
     StructureDef = typeDef;
 }