Пример #1
0
        public void SimpleAggregateSnapshottingViaSnapshotCreatorAndConcreteAggregateFactory()
        {
            IStoreEvents          memoryStore      = Wireup.Init().UsingInMemoryPersistence().Build();
            IConstructAggregates  aggregateFactory = new AggregateFactory();
            IEventStoreRepository repository       = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector());
            Guid            aggregateID            = Guid.NewGuid();
            SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now);

            repository.Save(aggregate, Guid.NewGuid());
            aggregate.Version.Should().Be(1);

            SnapshotCreator <SimpleAggregate> snapshotCreator = new SnapshotCreator <SimpleAggregate>(repository, 1);
            ISnapshot snapshot = snapshotCreator.SaveSnapShot(aggregate.Id);

            ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue);

            retrievedSnapshot.Should().NotBeNull();
            retrievedSnapshot.StreamRevision.Should().Be(1);
            retrievedSnapshot.ShouldBeEquivalentTo(snapshot);

            SimpleAggregate retrievedAggregate = repository.GetById <SimpleAggregate>(aggregate.Id);

            retrievedAggregate.Should().NotBeNull();
            aggregate.Version.Should().Be(1);
            retrievedAggregate.ShouldBeEquivalentTo(aggregate);
        }
Пример #2
0
        public void SimpleMod()
        {
            StructureDefinition original = this.CreateBaseObservation();
            StructureDefinition modified = this.CreateBaseObservation();

            SnapshotCreator.Create(original);
            SnapshotCreator.Create(modified);
            ElementTreeLoader loader = new ElementTreeLoader(info);

            ElementTreeNode originalNode = loader.Create(original.Snapshot.Element);
            ElementTreeNode modifiedNode = loader.Create(modified.Snapshot.Element);

            Assert.True(modifiedNode.TryGetElementNode("Observation.value[x]", out ElementTreeNode n));
            n.ElementDefinition.Max = "0";

            ElementTreeDiffer differ = new ElementTreeDiffer(info);

            differ.Process(originalNode, modifiedNode);

            List <ElementDefinition> elementDefinitions = new List <ElementDefinition>();

            modifiedNode.CopyTo(elementDefinitions);
            Assert.True(elementDefinitions.Count == 2);
            Assert.True(elementDefinitions[1].Path == "Observation.value[x]");
            Assert.True(elementDefinitions[1].Max == "0");
        }
Пример #3
0
        void Create_NoModObservation(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("NoModObservation");

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
        }
Пример #4
0
        public void CardinalityTest()
        {
            StructureDefinition s = this.CreateBaseObservation();

            SnapshotCreator.Create(s);
            ElementNode head = ElementNode.Create(s.Snapshot.Element);

            Assert.True(head.Slices.Any() == false);
            Assert.True(head.Children.Count() == 1);

            {
                Assert.True(head.TryGetElementNode("Observation.id", out ElementNode idNode) == true);
                Assert.True(idNode.Element.Min == 0);
                Assert.True(idNode.Element.Max == "1");
                Assert.True(idNode.Element.Base.Min == 0);
                Assert.True(idNode.Element.Base.Max == "1");
            }

            {
                Assert.True(head.TryGetElementNode("Observation.meta", out ElementNode metaNode) == true);
                Assert.True(metaNode.Element.Min == 0);
                Assert.True(metaNode.Element.Max == "1");
                Assert.True(metaNode.Element.Base.Min == 0);
                Assert.True(metaNode.Element.Base.Max == "1");
            }
            {
                Assert.True(head.TryGetElementNode("Observation.status", out ElementNode statusNode) == true);
                Assert.True(statusNode.Element.Min == 1);
                Assert.True(statusNode.Element.Max == "1");
                Assert.True(statusNode.Element.Base.Min == 1);
                Assert.True(statusNode.Element.Base.Max == "1");
            }
        }
Пример #5
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");
        }
Пример #6
0
        ElementTreeNode GetSnapNodeOriginal(StructureDefinition sDef,
                                            ElementTreeLoader l)
        {
            const String fcn = "LoadBase";

            lock (originalNodes)
            {
                if (originalNodes.TryGetValue(sDef.BaseDefinition, out ElementTreeNode retVal) == true)
                {
                    return(retVal);
                }

                StructureDefinition SBaseDef = FhirStructureDefinitions.Self.GetResource(sDef.BaseDefinition);
                if (SBaseDef == null)
                {
                    info.ConversionError(this.GetType().Name,
                                         fcn,
                                         $"Error loading StructureDef '{sDef.Name}'. BaseDefinition {sDef.BaseDefinition} not found ");
                    return(null);
                }

                if (SBaseDef.Snapshot == null)
                {
                    SnapshotCreator.Create(SBaseDef);
                }
                retVal = l.Create(SBaseDef.Snapshot.Element);;
                originalNodes.Add(sDef.BaseDefinition, retVal);
                return(retVal);
            }
        }
Пример #7
0
        void ProcessProfile(StructureDefinition profile)
        {
            //String fcn = "ProcessProfile";

            if (profile.Snapshot == null)
            {
                SnapshotCreator.Create(profile);
            }
            ElementNode profileItems = ElementNode.Create(profile.Snapshot.Element);

            Type fhirType = this.GetFhirApiType(profile.BaseDefinition);

            GenerateItem gi = new GenerateItem(this,
                                               this.NameSpace,
                                               profile.Name,
                                               profile.Type,
                                               fhirType,
                                               this.OutputLanguage,
                                               profileItems);

            gi.Process();

            String outputFile = Path.Combine(this.OutputDir, $"{profile.Name}.cs");

            File.WriteAllText(outputFile, gi.GetCode());
        }
Пример #8
0
        public void AddFragments(String inputDir)
        {
            //const String fcn = "AddFragments";

            void Save(DomainResource r, String outputName)
            {
                RemoveFragmentExtensions(r);

                String outputPath = Path.Combine(this.resourceDir, outputName);

                r.SaveJson(outputPath);
                this.fcGuide?.Mark(outputPath);
            }

            List <StructureDefinition> structureDefinitions = new List <StructureDefinition>();

            foreach (String file in Directory.GetFiles(inputDir))
            {
                String         fhirText = File.ReadAllText(file);
                FhirJsonParser parser   = new FhirJsonParser();
                var            resource = parser.Parse(fhirText, typeof(Resource));
                switch (resource)
                {
                case StructureDefinition structureDefinition:
                    Extension isFragmentExtension = structureDefinition.GetExtension(Global.IsFragmentExtensionUrl);
                    // Onlu add fragments to IG.
                    if (isFragmentExtension != null)
                    {
                        Int32 index = structureDefinition.Url.LastIndexOf('/');
                        structureDefinitions.Add(structureDefinition);
                    }

                    break;
                }
            }

            structureDefinitions.Sort((a, b) => String.Compare(a.Url, b.Url, new System.StringComparison()));

            foreach (StructureDefinition structureDefinition in structureDefinitions)
            {
                String fixedName = $"StructureDefinition-{structureDefinition.Name}";

                if (structureDefinition.Snapshot == null)
                {
                    SnapshotCreator.Create(structureDefinition);
                }
                Extension isFragmentExtension = structureDefinition.GetExtension(Global.IsFragmentExtensionUrl);
                {
                    String groupId = "Fragments";
                    Save(structureDefinition, $"{fixedName}.json");
                    String shortDescription = $"Fragment '{structureDefinition.Snapshot.Element[0].Short}'";

                    this.implementationGuide.AddIGResource($"StructureDefinition/{structureDefinition.Name}",
                                                           structureDefinition.Title,
                                                           shortDescription,
                                                           groupId,
                                                           false);
                }
            }
        }
Пример #9
0
        public void SimpleAggregateSnapshottingViaSnapshotCreator()
        {
            IStoreEvents          memoryStore      = Wireup.Init().UsingInMemoryPersistence().Build();
            IConstructAggregates  aggregateFactory = A.Fake <IConstructAggregates>();
            IEventStoreRepository repository       = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector());
            Guid            aggregateID            = Guid.NewGuid();
            SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now);

            repository.Save(aggregate, Guid.NewGuid());

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, null)).ReturnsLazily(() => new SimpleAggregate());

            SnapshotCreator <SimpleAggregate> snapshotCreator = new SnapshotCreator <SimpleAggregate>(repository, 1);
            Snapshot snapshot = snapshotCreator.SaveSnapShot(aggregate.Id);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            retrievedSnapshot.Should().NotBeNull();
            retrievedSnapshot.StreamRevision.Should().Be(1);
            retrievedSnapshot.ShouldBeEquivalentTo(snapshot);

            SimpleAggregate retrievedAggregate = repository.GetById <SimpleAggregate>(aggregate.Id);

            retrievedAggregate.Should().NotBeNull();
            aggregate.Version.Should().Be(1);
            retrievedAggregate.ShouldBeEquivalentTo(aggregate);
            A.CallTo(aggregateFactory).Where(o => o.Method.Name != "Build").MustNotHaveHappened();
            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.Not.IsNull())).MustHaveHappened();
        }
Пример #10
0
        public bool Write(out String fragmentName)
        {
            fragmentName = null;

            this.sDef.Snapshot = null;

            // Create differential by comparing current snapshot with original.
            ElementTreeNode differentialNode = this.snapNode.Clone();

            {
                ElementTreeDiffer differ = new ElementTreeDiffer(this.info);
                if (differ.Process(this.snapNodeOriginal, differentialNode) == false)
                {
                    return(false);
                }
            }
            {
                ElementTreeSetBase setBase = new ElementTreeSetBase(this.info);
                if (setBase.Process(this.snapNodeOriginal, differentialNode) == false)
                {
                    return(false);
                }
            }

            // Patch Path and Id's with correct basePath.
            differentialNode.ReplaceBasePath(this.basePath);

            {
                List <ElementDefinition> elementDefinitions = new List <ElementDefinition>();
                differentialNode.CopyTo(elementDefinitions);
                this.sDef.Differential.Element = elementDefinitions;
            }

            fragmentName = Path.Combine(this.fragmentDir, $"StructureDefinition-{this.sDef.Name}.json");

            // Make sure that all Observation resources that are not fragments, have Observation.code
            // fixed properly.
            if (
                (this.sDef.IsFragment() == false) &&
                (this.sDef.BaseDefinition == Global.ObservationUrl)
                )
            {
                if (this.snapNode.TryGetElementNode("Observation.code", out ElementTreeNode codeNode) == false)
                {
                    throw new Exception("Observation.code not found");
                }
                if (codeNode.ElementDefinition.Pattern == null)
                {
                    this.info.ConversionError(nameof(SDefEditor),
                                              "Write",
                                              $"Observation {this.SDef.Name} lacks fixed Observation.code.");
                }
            }

            SnapshotCreator.Create(this.sDef);

            this.sDef.SaveJson(fragmentName);
            return(true);
        }
        public void FindLint()
        {
            if (this.sDef.Snapshot == null)
            {
                SnapshotCreator.Create(this.sDef);
            }
            ElementLoader loader = new ElementLoader(this.processor);
            ElementNode   e      = loader.Create(sDef);

            SliceCardinalities(this.sDef, e);
        }
Пример #12
0
        void Create_CardinalityModObservation(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("CardinalityModObservation");

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.identifier");
                e.Min = 0;
                e.Max = "1";
            };

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
        }
Пример #13
0
        void Create_Fixed2(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("Fixed2");

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.effective[x]");
                e.Fixed = new Period(new FhirDateTime(1002, 1, 2), new FhirDateTime(1003, 4, 5));
            }

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.value[x]");
                e.Fixed = new FhirBoolean(true);
            }

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
        }
Пример #14
0
        void Create_Fixed1(ProfileGenerator p)
        {
            StructureDefinition profile = CreateObservation("Fixed1");

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.effective[x]");
                e.Fixed = new FhirDateTime(1002, 1, 2, 3, 4, 5, new TimeSpan(0));
            }

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.value[x]");
                e.Fixed = new Quantity(10, "things", "www.things.com");
            }

            SnapshotCreator.Create(profile);
            p.AddProfile(profile);
        }
Пример #15
0
        public void Create()
        {
            try
            {
                StructureDefinition pBase = this.CreateBaseProfile();
                Assert.True(pBase.BaseDefinition == "http://hl7.org/fhir/StructureDefinition/Observation");
                Assert.True(pBase.Type == "Observation");
                Assert.True(pBase.Kind == StructureDefinition.StructureDefinitionKind.Resource);
                Assert.True(pBase.Abstract == false);
                SnapshotCreator.Create(pBase);

                StructureDefinition frag = this.CreateFragment("Fragment", "http://www.test.com/frag1");
                Assert.True(frag.FhirVersion == FhirVersion);
                Assert.True(frag.Kind == StructureDefinition.StructureDefinitionKind.Logical);
                Assert.True(frag.Abstract == true);

                PreFhirGenerator p = this.CreatePreFhir();
                frag.FhirVersion = FHIRVersion.N0_01;
                frag.Version     = ProfileVersion;
                frag.Date        = this.date.ToString();
                frag.Status      = ProfileStatus;
                frag.Publisher   = "Hl7-Clinical Interoperability Council";
                frag.Contact     = this.Contact();

                pBase.AddFragRef(frag);
                p.AddFragment(pBase);
                p.AddFragment(frag);
                Assert.True(p.Process() == true);
                StringBuilder sb = new StringBuilder();
                p.FormatMessages(sb);
                Trace.WriteLine(sb.ToString());
                Assert.True(p.HasErrors == false);

                Assert.True(pBase.FhirVersion == FHIRVersion.N0_01);
                Assert.True(pBase.Version == ProfileVersion);
                Assert.True(pBase.Date == this.date.ToString());
                Assert.True(pBase.Status == ProfileStatus);
                Assert.True(pBase.Publisher == "Hl7-Clinical Interoperability Council");
                Assert.True(pBase.Contact.Matches(this.Contact()));
            }
            catch
            {
                Assert.False(true);
            }
        }
Пример #16
0
        void ProcessProfile(StructureDefinition profile)
        {
            String fcn = "ProcessProfile";

            if (profile.Snapshot == null)
            {
                SnapshotCreator.Create(profile);
            }
            this.ProfileSDef = new StructDefHelper(profile);

            //IEnumerable<string> y = Source.ListArtifactNames();
            //Resource x = Source.ResolveByUri("http://hl7.org/fhir/DataElement/Identifier");
            //x = Source.FindStructureDefinitionForCoreType("identifier");

            switch (this.OutputLanguage)
            {
            case OutputLanguages.CSharp:
                this.Code = new CSCodeFormatter(this);
                break;

            default:
                throw new Exception($"Output language {OutputLanguage} not found");
            }

            if (this.ProfileSDef.SDef.Derivation.Value != StructureDefinition.TypeDerivationRule.Constraint)
            {
                this.ConversionError(this.GetType().Name, fcn, $"{this.ProfileSDef.SDef.Name} is not a profile (constraint == {this.ProfileSDef.SDef.Derivation.Value.ToString()}");
                return;
            }

            ElementManager elements = new ElementManager();

            elements.Load(profile.Snapshot.Element);

            switch (this.ProfileSDef.SDef.Type)
            {
            case "Extension":
                this.ProcessExtension(this.ProfileSDef.SDef);
                break;

            default:
                this.ProcessResourceConstraint(this.ProfileSDef.SDef);
                break;
            }
        }
Пример #17
0
        public void MergeTypes1()
        {
            try
            {
                // should work.
                PreFhirGenerator    p     = this.CreatePreFhir();
                StructureDefinition pBase = this.CreateBaseProfile();
                SnapshotCreator.Create(pBase);

                StructureDefinition frag = this.CreateFragment("Fragment", "http://www.test.com/frag1");
                String fragRoot          = frag.Differential.Element[0].Path;
                {
                    ElementDefinition e = new ElementDefinition
                    {
                        Path      = $"{fragRoot}.value[x]",
                        ElementId = $"{fragRoot}.value[x]",
                        Min       = 1,
                        Max       = "1"
                    };
                    e.Type.Add(new ElementDefinition.TypeRefComponent {
                        Code = "string"
                    });
                    frag.AddDiffElement(e);
                }
                pBase.AddFragRef(frag);
                p.AddFragment(pBase);
                p.AddFragment(frag);
                Assert.True(p.Process() == true);
                StringBuilder sb = new StringBuilder();
                p.FormatMessages(sb);
                Trace.WriteLine(sb.ToString());
                Assert.True(p.HasErrors == false);
                Assert.True(pBase.Differential.Element.Count == 2);
                Assert.True(pBase.Differential.Element[1].Min == 1);
                Assert.True(pBase.Differential.Element[1].Max == "1");
                Assert.True(pBase.Differential.Element[1].Type.Count == 1);
                Assert.True(pBase.Differential.Element[1].Type[0].Code == "string");
            }
            catch
            {
                Assert.False(true);
            }
        }
Пример #18
0
        void ProcessProfile(StructureDefinition profile)
        {
            String fcn = nameof(ProcessProfile);

            try
            {
                if (profile.Snapshot == null)
                {
                    SnapshotCreator.Create(profile);
                }
                ElementDefinitionNode profileItems = ElementDefinitionNode.Create(profile);

                String baseFhirResourceName = profile.Type;
                Type   fhirType             = ModelInfo.GetTypeForFhirType(baseFhirResourceName);
                if (fhirType == null)
                {
                    throw new Exception($"Can not find Fhir Resource Class for '{baseFhirResourceName}'");
                }

                String name = $"{profile.Name}Extensions";

                GenerateItem gi = new GenerateItem(this,
                                                   this.NameSpace,
                                                   name,
                                                   profile.Type,
                                                   fhirType,
                                                   this.OutputLanguage,
                                                   profileItems);

                gi.Process();

                if (this.SaveFlag == true)
                {
                    String outputFile = Path.Combine(this.OutputDir, $"{name}.cs");
                    File.WriteAllText(outputFile, gi.GetCode());
                }
            }
            catch (Exception err)
            {
                this.ConversionError(this.GetType().Name, fcn, $"Profile {profile.Name} failed with exception {err.Message}");
            }
        }
Пример #19
0
        public void NoMod()
        {
            StructureDefinition original = this.CreateBaseObservation();
            StructureDefinition modified = this.CreateBaseObservation();

            SnapshotCreator.Create(original);
            SnapshotCreator.Create(modified);
            ElementTreeLoader loader       = new ElementTreeLoader(info);
            ElementTreeNode   originalNode = loader.Create(original.Snapshot.Element);
            ElementTreeNode   modifiedNode = loader.Create(modified.Snapshot.Element);

            ElementTreeDiffer differ = new ElementTreeDiffer(info);

            differ.Process(originalNode, modifiedNode);

            List <ElementDefinition> elementDefinitions = new List <ElementDefinition>();

            modifiedNode.CopyTo(elementDefinitions);
            Assert.True(elementDefinitions.Count == 0);
        }
Пример #20
0
        public SDInfo(IConversionInfo ci, StructureDefinition sd)
        {
            this.StructDef = sd;
            ElementTreeLoader l = new ElementTreeLoader(ci);

            if (sd.Snapshot == null)
            {
                SnapshotCreator.Create(sd);
            }

            this.DiffNodes = l.Create(sd.Differential.Element);
            this.SnapNodes = l.Create(sd.Snapshot.Element);

            this.InterfaceEditor = new CodeEditor();
            this.InterfaceEditor.TryAddUserMacro("ClassName", CS.CSMisc.ClassName(this));
            this.InterfaceEditor.TryAddUserMacro("InterfaceName", CS.CSMisc.InterfaceName(this));
            this.InterfaceEditor.Load(Path.Combine("Templates", "Interface.txt"));
            this.AddMacros(this.InterfaceEditor, this);

            this.SubClassEditor = new CodeEditor();
            this.AddMacros(this.SubClassEditor, this);
            this.SubClassEditor.TryAddUserMacro("FhirBase", this.StructDef.BaseDefinition.LastUriPart());
            this.SubClassEditor.TryAddUserMacro("BaseClass", CS.CSMisc.ClassName(this));
            this.SubClassEditor.Load(Path.Combine("Templates", "SubClass.txt"));

            this.ClassEditor = new CodeEditor();
            this.AddMacros(this.ClassEditor, this);
            this.ClassEditor.TryAddUserMacro("ClassName", CS.CSMisc.ClassName(this));
            if (this.IsFragment())
            {
                this.ClassEditor.Load(Path.Combine("Templates", "Fragment.txt"));
            }
            else
            {
                this.ClassEditor.Load(Path.Combine("Templates", "Class.txt"));
            }

            this.CodeBlocks = ClassCodeBlocks.Create(this.InterfaceEditor,
                                                     this.ClassEditor,
                                                     this.SubClassEditor);
        }
Пример #21
0
        public void Handle(CreateSnapshotMessage message)
        {
            IUserDal         dal     = new UserDal();
            ISnapshotCreator creator = new SnapshotCreator();
            var aggregate            = dal.GetUserInfoFromSpan(message.AccountNumber, DateTime.Now - message.To);
            var snapshot             = creator.SnapCreateSnapshot(aggregate, message.To);

            using (var store = new DocumentStore {
                Url = "http://localhost:8080", DefaultDatabase = "ES"
            })
            {
                store.Initialize();
                using (var session = store.OpenSession())
                {
                    var user     = session.Query <User>().FirstOrDefault(x => x.AccountNumber == message.AccountNumber);
                    var snapShot = session.Load <Snapshot>($"{user.Id}/Snapshots");
                    snapShot.Snapshots.Insert(0, snapshot);
                    session.SaveChanges();
                }
            }
        }
Пример #22
0
        public void Handle(CreateNewUserMessage message)
        {
            var serviceBus = new ServiceBus();
            ISnapshotCreator snapshotCreator = new SnapshotCreator();

            using (IDocumentStore store = new DocumentStore {
                Url = "http://localhost:8080", DefaultDatabase = "ES"
            })
            {
                store.Initialize();
                var userObject = MapToUserObject(message);
                using (var session = store.OpenSession())
                {
                    session.Store(userObject);
                    session.Store(snapshotCreator.CreateRootSnapshot(userObject.Id));
                    session.SaveChanges();
                    var @event = InitialAmmountEvent(userObject, message);
                    serviceBus.PublishEvent(@event);
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Save resource to the indicated dir.
        /// </summary>
        /// <param name="outputDir"></param>
        void SaveResource(String outputDir,
                          ProcessItem processedItem,
                          bool finalFlag)
        {
            String outputName;

            switch (processedItem.Resource)
            {
            case StructureDefinition sDef:
                // Dont save fragments....
                if (sDef.IsFragment())
                {
                    return;
                }
                // recreate snapshot if missing
                if (finalFlag)
                {
                    if (sDef.Snapshot == null)
                    {
                        SnapshotCreator.Create(sDef);
                    }
                    this.CleanupDifferential(processedItem, sDef);
                }
                outputName = Path.Combine(outputDir, $"StructureDefinition-{sDef.Name}.json");
                break;

            case CodeSystem codeSys:
                outputName = Path.Combine(outputDir, $"CodeSystem-{codeSys.Name}.json");
                break;

            case ValueSet valueSet:
                outputName = Path.Combine(outputDir, $"ValueSet-{valueSet.Name}.json");
                break;

            default:
                throw new NotImplementedException($"Unimplemented type {processedItem.GetType().Name}");
            }
            processedItem.Resource.SaveJson(outputName);
            this.fc?.Mark(outputName);
        }
Пример #24
0
        public void SliceDiscriminatorTest()
        {
            StructureDefinition s = this.CreateBaseObservation();
            ElementDefinition   e = new ElementDefinition
            {
                ElementId = "Observation.component",
                Path      = "Observation.component",
                Slicing   = new ElementDefinition.SlicingComponent
                {
                    ElementId = "5",
                    Ordered   = false,
                    Rules     = ElementDefinition.SlicingRules.Open
                }
            };

            e.Slicing.Discriminator.Add(new ElementDefinition.DiscriminatorComponent
            {
                Type = ElementDefinition.DiscriminatorType.Value,
                Path = "code.coding.code"
            });
            s.Differential.Element.Add(e);

            SnapshotCreator.Create(s);
            ElementNode head = ElementNode.Create(s.Snapshot.Element);

            Assert.True(head.Slices.Any() == false);
            Assert.True(head.Children.Count() == 1);

            Assert.True(head.TryGetElementNode("Observation.component", out ElementNode observationComponent) == true);
            Assert.True(observationComponent.Path == "Observation.component");
            Assert.True(observationComponent.Slices.Any() == false);
            Assert.True(observationComponent.Element.Slicing.ElementId == "5");
            Assert.True(observationComponent.Element.Slicing.Ordered == false);
            Assert.True(observationComponent.Element.Slicing.Rules == ElementDefinition.SlicingRules.Open);
            Assert.True(observationComponent.Element.Slicing.Discriminator.Count == 1);
            Assert.True(observationComponent.Element.Slicing.Discriminator[0].Type == ElementDefinition.DiscriminatorType.Value);
            Assert.True(observationComponent.Element.Slicing.Discriminator[0].Path == "code.coding.code");
        }
Пример #25
0
        public bool LoadBase()
        {
            const String fcn = "LoadBase";

            if (this.SnapNode != null)
            {
                return(true);
            }

            this.FragmentFlag = this.SDef.IsFragment();
            StructureDefinition sDef = this.SDef;

            if (sDef == null)
            {
                throw new Exception("Internal error. ProcessItem is not a structured definition.");
            }
            if (sDef.Snapshot == null)
            {
                SnapshotCreator.Create(sDef);
            }
            List <ElementDefinition> elements = sDef.Snapshot.Element;

            this.BasePath = elements[0].Path;
            ElementTreeLoader l = new ElementTreeLoader(this.info);

            this.SnapNode = l.Create(elements);
            if (String.IsNullOrEmpty(sDef.BaseDefinition) == true)
            {
                info.ConversionError(this.GetType().Name,
                                     fcn,
                                     $"Error loading StructureDef '{sDef.Name}'. Empty BaseDefinition ");
                return(false);
            }

            this.SnapNodeOriginal = GetSnapNodeOriginal(sDef, l);
            return(true);
        }
Пример #26
0
 public Volume(SnapshotCreator <Volume> snapshotCreator)
 {
     _snapshotCreator = snapshotCreator;
 }
Пример #27
0
        public void SlicedNested()
        {
            SliceGenerator sliceGen = new SliceGenerator(SliceGenerator.OutputLanguageType.CSharp,
                                                         OutputNameSpace,
                                                         GenDir);
            StructureDefinition profile = CreateObservation("SlicedNested");

            {
                ElementDefinition e = profile.Differential.Element.GetOrCreateElement("Observation.component");
                e.Slicing = new ElementDefinition.SlicingComponent
                {
                    ElementId = "ObservationComponentSlice",
                    Ordered   = false,
                    Rules     = ElementDefinition.SlicingRules.Open
                };
                e.Slicing.Discriminator.Add(new ElementDefinition.DiscriminatorComponent
                {
                    Type = ElementDefinition.DiscriminatorType.Value,
                    Path = "code"
                });
            }
            {
                ElementDefinition e = new ElementDefinition
                {
                    ElementId = "Observation.component:Slice1",
                    Path      = "Observation.component",
                    SliceName = "Slice1"
                };
                profile.Differential.Element.Add(e);
            }

            {
                ElementDefinition e = new ElementDefinition
                {
                    Path      = "Observation.component.code",
                    ElementId = "Observation.component:Slice1.code",
                    Fixed     = new CodeableConcept("system", "Slice3aCode")
                };
                profile.Differential.Element.Add(e);
            }

            {
                ElementDefinition e = new ElementDefinition
                {
                    Path      = "Observation.component.code.coding",
                    ElementId = "Observation.component:Slice1.code.coding",
                };
                profile.Differential.Element.Add(e);

                e.Slicing = new ElementDefinition.SlicingComponent
                {
                    ElementId = "ObservationComponentSlice1",
                    Ordered   = false,
                    Rules     = ElementDefinition.SlicingRules.Open
                };
                e.Slicing.Discriminator.Add(new ElementDefinition.DiscriminatorComponent
                {
                    Type = ElementDefinition.DiscriminatorType.Value,
                    Path = "code"
                });
            }

            {
                ElementDefinition e = new ElementDefinition
                {
                    Path      = "Observation.component.code.coding.code",
                    ElementId = "Observation.component:Slice1.code.coding.code",
                    Fixed     = new Code("Slice3aCode")
                };
                profile.Differential.Element.Add(e);
            }

            SnapshotCreator.Create(profile);
            String outputPath = $@"\Temp\SlicedNested.json";

            profile.SaveJson(outputPath);
            //FhirValidator f = new FhirValidator();
            //{
            //    bool success = f.Validate("4.0.0", outputPath);
            //    StringBuilder sb = new StringBuilder();
            //    f.FormatMessages(sb);
            //    Trace.WriteLine(sb.ToString());
            //    Assert.True(success == true);
            //}
            sliceGen.AddProfile(profile);
            {
                bool success = sliceGen.Process();

                StringBuilder sb = new StringBuilder();
                sliceGen.FormatMessages(sb);
                Trace.WriteLine(sb.ToString());
                Assert.True(success == true);
            }
        }
Пример #28
0
        public void AddResources(params String[] inputDirs)
        {
            const String fcn = "AddResources";

            String Group(DomainResource resource)
            {
                Extension groupExtension = resource.GetExtension(Global.GroupExtensionUrl);

                if (groupExtension == null)
                {
                    throw new Exception($"StructureDefinition {resource.Id} lacks group extension");
                }
                FhirString value = groupExtension.Value as FhirString;

                if (value == null)
                {
                    throw new Exception($"StructureDefinition {resource.Id} lacks group extension value");
                }
                return(value.Value);
            }

            String GetGroupPath(DomainResource resource)
            {
                String groupPath = Group(resource);

                String groupId = groupPath.BaseUriPart();

                if (this.groupIds.Contains(groupId) == false)
                {
                    this.ConversionError(this.GetType().Name,
                                         fcn,
                                         $"Group {groupId} not defined");
                    return(null);
                }

                return(groupId);
            }

            void Save(DomainResource r, String outputName)
            {
                RemoveFragmentExtensions(r);
                String outputPath = Path.Combine(this.resourceDir, outputName);

                r.SaveJson(outputPath);
                this.fcGuide?.Mark(outputPath);
            }

            List <StructureDefinition> structureDefinitions = new List <StructureDefinition>();
            List <ValueSet>            valueSets            = new List <ValueSet>();
            List <CodeSystem>          codeSystems          = new List <CodeSystem>();

            foreach (String inputDir in inputDirs)
            {
                foreach (String file in Directory.GetFiles(inputDir))
                {
                    String         fhirText = File.ReadAllText(file);
                    FhirJsonParser parser   = new FhirJsonParser();
                    var            resource = parser.Parse(fhirText, typeof(Resource));
                    switch (resource)
                    {
                    case StructureDefinition structureDefinition:
                        structureDefinitions.Add(structureDefinition);
                        break;

                    case CodeSystem codeSystem:
                        codeSystems.Add(codeSystem);
                        break;

                    case ValueSet valueSet:
                        valueSets.Add(valueSet);
                        break;

                    default:
                        throw new NotImplementedException($"Unknown resource type '{file}'");
                    }
                }
            }

            structureDefinitions.Sort((a, b) => String.Compare(Group(a), Group(b), new System.StringComparison()));
            valueSets.Sort((a, b) => String.Compare(a.Name, b.Name, new System.StringComparison()));
            codeSystems.Sort((a, b) => String.Compare(a.Name, b.Name, new System.StringComparison()));

            foreach (CodeSystem codeSystem in codeSystems)
            {
                String groupId = GetGroupPath(codeSystem);
                Save(codeSystem, $"CodeSystem-{codeSystem.Name}.json");
                this.implementationGuide.AddIGResource($"CodeSystem/{codeSystem.Name}", codeSystem.Title,
                                                       codeSystem.Description.ToString(), groupId, false);
            }

            foreach (ValueSet valueSet in valueSets)
            {
                String groupId = GetGroupPath(valueSet);
                Save(valueSet, $"ValueSet-{valueSet.Name}.json");
                this.implementationGuide.AddIGResource($"ValueSet/{valueSet.Name}", valueSet.Title,
                                                       valueSet.Description.ToString(), groupId, false);
            }

            foreach (StructureDefinition structureDefinition in structureDefinitions)
            {
                String fixedName = $"StructureDefinition-{structureDefinition.Name}";

                if (structureDefinition.Snapshot == null)
                {
                    SnapshotCreator.Create(structureDefinition);
                }

                Extension isFragmentExtension = structureDefinition.GetExtension(Global.IsFragmentExtensionUrl);
                // Dont add fragments to IG.
                if (isFragmentExtension == null)
                {
                    String groupId = GetGroupPath(structureDefinition);
                    Save(structureDefinition, $"{fixedName}.json");
                    String shortDescription = structureDefinition.Snapshot.Element[0].Short;

                    this.implementationGuide.AddIGResource($"StructureDefinition/{structureDefinition.Name}",
                                                           structureDefinition.Title,
                                                           shortDescription,
                                                           groupId,
                                                           false);
                }
                else
                {
                }
            }
        }
 public VirtualMachine(SnapshotCreator <VirtualMachine> snapshotCreator)
 {
     _snapshotCreator = snapshotCreator;
 }
Пример #30
0
        public void SliceTest()
        {
            StructureDefinition s = this.CreateBaseObservation();

            {
                ElementDefinition e = new ElementDefinition
                {
                    ElementId = "Observation.code.coding",
                    Path      = "Observation.code.coding",
                    Min       = 0,
                    Max       = "*",
                    Slicing   = new ElementDefinition.SlicingComponent
                    {
                        ElementId = "4",
                        Ordered   = false,
                        Rules     = ElementDefinition.SlicingRules.Open
                    }
                };
                e.Slicing.Discriminator.Add(new ElementDefinition.DiscriminatorComponent
                {
                    Type = ElementDefinition.DiscriminatorType.Value,
                    Path = "code"
                });
                s.Differential.Element.Add(e);
            }

            {
                ElementDefinition e = new ElementDefinition
                {
                    ElementId = "Observation.code.coding:Slice",
                    SliceName = "Slice",
                    Path      = "Observation.code.coding",
                    Min       = 1,
                    Max       = "1"
                };
                e.Type.Add(new ElementDefinition.TypeRefComponent {
                    Code = "Coding"
                });
                s.Differential.Element.Add(e);
            }


            {
                ElementDefinition e = new ElementDefinition
                {
                    ElementId = "Observation.code.coding:Slice.system",
                    Path      = "Observation.code.coding.system",
                    Min       = 0,
                    Max       = "1",
                    Fixed     = new FhirUri("http://hl7.org/fhir/us/breast-radiology/CodeSystem/breastrad-BreastAbnormalityCodesCS")
                };
                e.Type.Add(new ElementDefinition.TypeRefComponent {
                    Code = "code"
                });
                s.Differential.Element.Add(e);
            }

            {
                ElementDefinition e = new ElementDefinition
                {
                    ElementId = "Observation.code.coding:Slice.code",
                    Path      = "Observation.code.coding.code",
                    Min       = 0,
                    Max       = "1",
                    Fixed     = new Code("BreastAbnormalityObservationCode")
                };
                e.Type.Add(new ElementDefinition.TypeRefComponent {
                    Code = "code"
                });
                s.Differential.Element.Add(e);
            }

            SnapshotCreator.Create(s);
            ElementNode head = ElementNode.Create(s.Snapshot.Element);

            Assert.True(head.Slices.Any() == false);
            Assert.True(head.Children.Count() == 1);

            Assert.True(head.TryGetElementNode("Observation.code.coding", out ElementNode coding) == true);
            Assert.True(coding.Slices.Count() == 1);

            Assert.True(head.TryGetElementNode("Observation.code.coding:Slice.code", out coding) == true);
        }