public void SetUp()
 {
     _converter = DataTypeConverter.Instance;
 }
Exemple #2
0
 /// <summary>
 /// Create patient link
 /// </summary>
 private Patient.LinkComponent CreateLink <TLink>(Guid targetEntityKey, Patient.LinkType type) where TLink : DomainResource, new() => new Patient.LinkComponent()
 {
     Type  = type,
     Other = DataTypeConverter.CreateNonVersionedReference <TLink>(targetEntityKey)
 };
Exemple #3
0
        /// <summary>
        /// Map a patient object to FHIR.
        /// </summary>
        /// <param name="model">The patient to map to FHIR</param>
        /// <returns>Returns the mapped FHIR resource.</returns>
        protected override Patient MapToFhir(Core.Model.Roles.Patient model)
        {
            // If the model is being constructed as part of a bundle, then the caller
            // should have included the bundle so we can add any related resources
            var partOfBundle = model.GetAnnotations <Bundle>().FirstOrDefault();

            var retVal = DataTypeConverter.CreateResource <Patient>(model);

            retVal.Active  = StatusKeys.ActiveStates.Contains(model.StatusConceptKey.Value);
            retVal.Address = model.GetAddresses().Select(DataTypeConverter.ToFhirAddress).ToList();

            if (model.DateOfBirth.HasValue)
            {
                switch (model.DateOfBirthPrecision.GetValueOrDefault())
                {
                case DatePrecision.Day:
                    retVal.BirthDate = model.DateOfBirth.Value.ToString("yyyy-MM-dd");
                    break;

                case DatePrecision.Month:
                    retVal.BirthDate = model.DateOfBirth.Value.ToString("yyyy-MM");
                    break;

                case DatePrecision.Year:
                    retVal.BirthDate = model.DateOfBirth.Value.ToString("yyyy");
                    break;
                }
            }

            // Deceased precision
            if (model.DeceasedDate.HasValue)
            {
                if (model.DeceasedDate == DateTime.MinValue)
                {
                    retVal.Deceased = new FhirBoolean(true);
                }
                else
                {
                    switch (model.DeceasedDatePrecision)
                    {
                    case DatePrecision.Day:
                        retVal.Deceased = new FhirDateTime(model.DeceasedDate.Value.Year, model.DeceasedDate.Value.Month, model.DeceasedDate.Value.Day);
                        break;

                    case DatePrecision.Month:
                        retVal.Deceased = new FhirDateTime(model.DeceasedDate.Value.Year, model.DeceasedDate.Value.Month);
                        break;

                    case DatePrecision.Year:
                        retVal.Deceased = new FhirDateTime(model.DeceasedDate.Value.Year);
                        break;

                    default:
                        retVal.Deceased = DataTypeConverter.ToFhirDateTime(model.DeceasedDate);
                        break;
                    }
                }
            }

            if (model.GenderConceptKey.HasValue)
            {
                retVal.Gender = DataTypeConverter.ToFhirEnumeration <AdministrativeGender>(model.GenderConceptKey, "http://hl7.org/fhir/administrative-gender", true);
            }

            retVal.Identifier    = model.Identifiers?.Select(DataTypeConverter.ToFhirIdentifier).ToList();
            retVal.MultipleBirth = model.MultipleBirthOrder == 0 ? (DataType) new FhirBoolean(true) : model.MultipleBirthOrder.HasValue ? new Integer(model.MultipleBirthOrder.Value) : null;
            retVal.Name          = model.GetNames().Select(DataTypeConverter.ToFhirHumanName).ToList();
            retVal.Telecom       = model.GetTelecoms().Select(DataTypeConverter.ToFhirTelecom).ToList();
            retVal.Communication = model.GetPersonLanguages().Select(DataTypeConverter.ToFhirCommunicationComponent).ToList();

            foreach (var rel in model.GetRelationships().Where(o => !o.InversionIndicator))
            {
                if (rel.RelationshipTypeKey == EntityRelationshipTypeKeys.Contact)
                {
                    var relEntity = rel.LoadProperty(o => o.TargetEntity);

                    if (relEntity is Core.Model.Entities.Person person)
                    {
                        var contact = new Patient.ContactComponent()
                        {
                            ElementId    = $"{person.Key}",
                            Address      = DataTypeConverter.ToFhirAddress(person.GetAddresses().FirstOrDefault()),
                            Relationship = new List <CodeableConcept>()
                            {
                                DataTypeConverter.ToFhirCodeableConcept(rel.RelationshipRoleKey, "http://terminology.hl7.org/CodeSystem/v2-0131"),
                                DataTypeConverter.ToFhirCodeableConcept(rel.RelationshipTypeKey, "http://terminology.hl7.org/CodeSystem/v2-0131")
                            }.OfType <CodeableConcept>().ToList(),
                            Name = DataTypeConverter.ToFhirHumanName(person.GetNames().FirstOrDefault()),
                            // TODO: Gender
                            Gender  = DataTypeConverter.ToFhirEnumeration <AdministrativeGender>(person.GenderConceptKey, "http://hl7.org/fhir/administrative-gender"),
                            Telecom = person.GetTelecoms().Select(t => DataTypeConverter.ToFhirTelecom(t)).ToList()
                        };

                        var scoper = person.LoadCollection(o => o.Relationships).FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.Scoper);
                        if (scoper != null)
                        {
                            contact.Organization = DataTypeConverter.CreateNonVersionedReference <Hl7.Fhir.Model.Organization>(scoper.LoadProperty(o => o.TargetEntity));
                        }
                        DataTypeConverter.AddExtensions(person, contact);
                        retVal.Contact.Add(contact);
                    }
                    else if (relEntity is Core.Model.Entities.Organization org) // it *IS* an organization
                    {
                        var contact = new Patient.ContactComponent()
                        {
                            ElementId    = $"{org.Key}",
                            Relationship = new List <CodeableConcept>()
                            {
                                DataTypeConverter.ToFhirCodeableConcept(rel.RelationshipRoleKey, "http://terminology.hl7.org/CodeSystem/v2-0131"),
                                DataTypeConverter.ToFhirCodeableConcept(rel.RelationshipTypeKey, "http://terminology.hl7.org/CodeSystem/v2-0131")
                            }.OfType <CodeableConcept>().ToList(),
                            Organization = DataTypeConverter.CreateNonVersionedReference <Hl7.Fhir.Model.Organization>(org)
                        };
                        retVal.Contact.Add(contact);
                    }
                }
                else if (rel.RelationshipTypeKey == EntityRelationshipTypeKeys.Scoper)
                {
                    var scoper = rel.LoadProperty(o => o.TargetEntity);

                    retVal.ManagingOrganization = DataTypeConverter.CreateNonVersionedReference <Hl7.Fhir.Model.Organization>(scoper);

                    // If this is part of a bundle, include it
                    partOfBundle?.Entry.Add(new Bundle.EntryComponent
                    {
                        FullUrl  = $"{MessageUtil.GetBaseUri()}/Organization/{scoper.Key}",
                        Resource = FhirResourceHandlerUtil.GetMapperForInstance(scoper).MapToFhir(scoper)
                    });
                }
                else if (rel.RelationshipTypeKey == EntityRelationshipTypeKeys.HealthcareProvider)
                {
                    var practitioner = rel.LoadProperty(o => o.TargetEntity);

                    retVal.GeneralPractitioner.Add(DataTypeConverter.CreateVersionedReference <Practitioner>(practitioner));

                    // If this is part of a bundle, include it
                    partOfBundle?.Entry.Add(new Bundle.EntryComponent
                    {
                        FullUrl  = $"{MessageUtil.GetBaseUri()}/Practitioner/{practitioner.Key}",
                        Resource = FhirResourceHandlerUtil.GetMapperForInstance(practitioner).MapToFhir(practitioner)
                    });
                }
                else if (rel.RelationshipTypeKey == EntityRelationshipTypeKeys.Replaces)
                {
                    retVal.Link.Add(this.CreateLink <Patient>(rel.TargetEntityKey.Value, Patient.LinkType.Replaces));
                }
                else if (rel.RelationshipTypeKey == EntityRelationshipTypeKeys.Duplicate)
                {
                    retVal.Link.Add(this.CreateLink <Patient>(rel.TargetEntityKey.Value, Patient.LinkType.Seealso));
                }
                else if (rel.RelationshipTypeKey == MDM_MASTER_LINK) // HACK: MDM Master Record
                {
                    if (rel.SourceEntityKey.HasValue && rel.SourceEntityKey != model.Key)
                    {
                        retVal.Link.Add(this.CreateLink <Patient>(rel.SourceEntityKey.Value, Patient.LinkType.Seealso));
                    }
                    else // Is a local
                    {
                        retVal.Link.Add(this.CreateLink <Patient>(rel.TargetEntityKey.Value, Patient.LinkType.Refer));
                    }
                }
                else if (rel.ClassificationKey == EntityRelationshipTypeKeys.EquivalentEntity)
                {
                    retVal.Link.Add(this.CreateLink <Patient>(rel.TargetEntityKey.Value, Patient.LinkType.Refer));
                }
                else if (partOfBundle != null) // This is part of a bundle and we need to include it
                {
                    // HACK: This piece of code is used to add any RelatedPersons to the container bundle if it is part of a bundle
                    if (this.GetRelatedPersonConceptUuids().Contains(rel.RelationshipTypeKey.Value))
                    {
                        var relative = FhirResourceHandlerUtil.GetMapperForInstance(rel).MapToFhir(rel);
                        partOfBundle.Entry.Add(new Bundle.EntryComponent()
                        {
                            FullUrl  = $"{MessageUtil.GetBaseUri()}/RelatedPerson/{rel.Key}",
                            Resource = relative
                        });
                    }
                }
            }

            // Reverse relationships of family member?
            var uuids = model.Relationships.Where(r => r.RelationshipTypeKey == MDM_MASTER_LINK).Select(r => r.SourceEntityKey).Union(new Guid?[] { model.Key }).ToArray();
            var familyMemberConcepts = this.GetFamilyMemberUuids();
            var reverseRelationships = this.m_erRepository.Find(o => uuids.Contains(o.TargetEntityKey) && familyMemberConcepts.Contains(o.RelationshipTypeKey.Value) && o.ObsoleteVersionSequenceId == null);

            foreach (var rrv in reverseRelationships)
            {
                retVal.Link.Add(new Patient.LinkComponent
                {
                    Type  = Patient.LinkType.Seealso,
                    Other = DataTypeConverter.CreateNonVersionedReference <RelatedPerson>(rrv)
                });

                // If this is part of a bundle, include it
                partOfBundle?.Entry.Add(new Bundle.EntryComponent
                {
                    FullUrl  = $"{MessageUtil.GetBaseUri()}/RelatedPerson/{rrv.Key}",
                    Resource = FhirResourceHandlerUtil.GetMappersFor(ResourceType.RelatedPerson).First().MapToFhir(rrv)
                });
            }

            // Was this record replaced?
            if (!retVal.Active.GetValueOrDefault())
            {
                var replacedRelationships = this.m_erRepository.Find(o => uuids.Contains(o.TargetEntityKey) && o.RelationshipTypeKey == EntityRelationshipTypeKeys.Replaces && o.ObsoleteVersionSequenceId == null);

                foreach (var repl in replacedRelationships)
                {
                    retVal.Link.Add(new Patient.LinkComponent()
                    {
                        Type  = Patient.LinkType.ReplacedBy,
                        Other = DataTypeConverter.CreateNonVersionedReference <Patient>(repl.LoadProperty(o => o.SourceEntity)),
                    });
                }
            }

            var photo = model.LoadCollection(o => o.Extensions).FirstOrDefault(o => o.ExtensionTypeKey == ExtensionTypeKeys.JpegPhotoExtension);

            if (photo != null)
            {
                retVal.Photo = new List <Attachment>
                {
                    new Attachment
                    {
                        ContentType = "image/jpg",
                        Data        = photo.ExtensionValueXml
                    }
                };
            }

            return(retVal);
        }
Exemple #4
0
        /// <summary>
        /// Gas estimation for transaction. Used to fill transaction.gas field. Check RawTransaction docs for more on gas.
        /// </summary>
        /// <param name="request">The transaction request whose cost will be estimated.</param>
        /// <param name="blockNumber">Block number or <see cref="BlockParameter.Latest" /> or <see cref="BlockParameter.Earliest" />.</param>
        /// <returns>Estimated gas in Wei.</returns>
        public async Task <long> EstimateGas(TransactionRequest request, BigInteger blockNumber)
        {
            string jsonResponse = await _in3.SendRpc(EthEstimateGas, new object[] { await MapTransactionToRpc(request), BlockParameter.AsString(blockNumber) });

            return((long)DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
Exemple #5
0
        /// <summary>
        /// Retrieve the of uncle of a block for the given <paramref name="blockNumber" /> and a position. Uncle blocks are valid blocks and are mined in a genuine manner, but get rejected from the main blockchain.
        /// </summary>
        /// <param name="blockNumber">Block number or <see cref="BlockParameter.Latest" /> or <see cref="BlockParameter.Earliest" />.</param>
        /// <param name="position">Position of the block.</param>
        /// <returns>The uncle block.</returns>
        public async Task <Block> GetUncleByBlockNumberAndIndex(BigInteger blockNumber, int position)
        {
            string jsonResponse = await _in3.SendRpc(EthGetUncleByBlockNumberAndIndex,
                                                     new object[] { BlockParameter.AsString(blockNumber), DataTypeConverter.BigIntToPrefixedHex(position) });

            return(RpcHandler.From <TransactionBlock>(jsonResponse));
        }
Exemple #6
0
        /// <summary>
        /// Get the <see cref="Chain" /> which the client is currently connected to.
        /// </summary>
        /// <returns>The <see cref="Chain" />.</returns>
        public async Task <Chain> GetChainId()
        {
            string jsonResponse = await _in3.SendRpc(EthChainId, new object[] { });

            return((Chain)(long)DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
Exemple #7
0
        /// <summary>
        /// Creates a filter in the node, to notify when a new block arrives. To check if the state has changed, call <see cref="Eth1.Api.GetFilterChangesFromLogs" />.
        /// Filters are event catchers running on the Ethereum Client. Incubed has a client-side implementation.
        /// An event will be stored in case it is within to and from blocks, or in the block of blockhash, contains a
        /// transaction to the designed address, and has a word listed on topics.
        /// </summary>
        /// <returns>The filter id.</returns>
        /// <remarks>
        /// <para>Use the returned filter id to perform other filter operations.</para>
        /// </remarks>
        public async Task <long> NewBlockFilter()
        {
            string jsonResponse = await _in3.SendRpc(EthNewBlockFilter, new object[] { });

            return((long)DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
        public override void Serialize(BinaryWriter writer, long startOffset, SerializationInfo additionalInfo)
        {
            writer.BaseStream.Position = startOffset;
            DataTypeConverter.WriteUShort(writer, Format);
            writer.BaseStream.Position += DataTypeLength.UShort;
            DataTypeConverter.WriteUShort(writer, Language);

            CharGlyphIdMap[0xFFFF] = 0;
            var charList  = CharGlyphIdMap.Keys.OrderBy(u => u).ToList();
            var segStarts = new List <uint>();
            var segEnds   = new List <uint>();

            for (var i = 0; i < charList.Count; i++)
            {
                if (i == 0 || charList[i] - 1 != charList[i - 1])
                {
                    segStarts.Add(charList[i]);
                }
                if (i == charList.Count - 1 || charList[i] + 1 != charList[i + 1])
                {
                    segEnds.Add(charList[i]);
                }
            }

            var segCount = segStarts.Count;

            DataTypeConverter.WriteUShort(writer, (ushort)(segCount * 2));
            {
                var pow         = Math.Floor(Math.Log(segCount, 2));
                var searchRange = Math.Pow(2, pow + 1);
                DataTypeConverter.WriteUShort(writer, (ushort)searchRange);
                DataTypeConverter.WriteUShort(writer, (ushort)pow);
                DataTypeConverter.WriteUShort(writer, (ushort)(segCount * 2 - searchRange));
            }

            foreach (var end in segEnds)
            {
                DataTypeConverter.WriteUShort(writer, (ushort)end);
            }
            DataTypeConverter.WriteUShort(writer, 0);
            foreach (var start in segStarts)
            {
                DataTypeConverter.WriteUShort(writer, (ushort)start);
            }
            var idDeltaOffset       = writer.BaseStream.Position;
            var idRangeOffsetOffset = idDeltaOffset + segCount * DataTypeLength.Short;
            var glyphIdArrayOffset  = idRangeOffsetOffset + segCount * DataTypeLength.UShort;

            for (var i = 0; i < segCount; i++)
            {
                if (IsSegmentGlyphIdContiguous(segStarts[i], segEnds[i]))
                {
                    writer.BaseStream.Position = idDeltaOffset;
                    DataTypeConverter.WriteShort(writer, (short)(CharGlyphIdMap[segStarts[i]] - segStarts[i]));

                    writer.BaseStream.Position = idRangeOffsetOffset;
                    DataTypeConverter.WriteUShort(writer, 0);
                }
                else
                {
                    writer.BaseStream.Position = idDeltaOffset;
                    DataTypeConverter.WriteShort(writer, 0);

                    writer.BaseStream.Position = idRangeOffsetOffset;
                    DataTypeConverter.WriteUShort(writer, (ushort)(glyphIdArrayOffset - idRangeOffsetOffset));

                    writer.BaseStream.Position = glyphIdArrayOffset;
                    for (var j = segStarts[i]; j <= segEnds[i]; j++)
                    {
                        DataTypeConverter.WriteUShort(writer, (ushort)CharGlyphIdMap[j]);
                    }
                    glyphIdArrayOffset = writer.BaseStream.Position;
                }
                idDeltaOffset       += DataTypeLength.Short;
                idRangeOffsetOffset += DataTypeLength.UShort;
            }

            // Set length
            var length = glyphIdArrayOffset - startOffset;

            writer.BaseStream.Position = startOffset + DataTypeLength.UShort;
            DataTypeConverter.WriteUShort(writer, (ushort)length);

            // Recover writer position
            writer.BaseStream.Position = startOffset + length;
        }
        /// <summary>
        /// Invoke the operation
        /// </summary>
        public Resource Invoke(Parameters parameters)
        {
            var resource = parameters.Parameter.FirstOrDefault(o => o.Name == "resource");
            var profile  = parameters.Parameter.FirstOrDefault(o => o.Name == "profile");
            var mode     = parameters.Parameter.FirstOrDefault(o => o.Name == "mode");

            var retVal = new OperationOutcome();

            // Get the profile handler for the specified profile, if no profile then just perform a profile mode
            if (!resource.Resource.TryDeriveResourceType(out ResourceType rt))
            {
                retVal.Issue.Add(new OperationOutcome.IssueComponent()
                {
                    Code        = OperationOutcome.IssueType.NotSupported,
                    Severity    = OperationOutcome.IssueSeverity.Fatal,
                    Diagnostics = $"Resource {resource.Resource.TypeName} not supported"
                });
            }
            else
            {
                var hdlr = FhirResourceHandlerUtil.GetResourceHandler(rt);
                if (hdlr == null)
                {
                    retVal.Issue.Add(new OperationOutcome.IssueComponent()
                    {
                        Code        = OperationOutcome.IssueType.NotSupported,
                        Severity    = OperationOutcome.IssueSeverity.Fatal,
                        Diagnostics = $"Resource {resource.Resource.TypeName} not supported"
                    });
                }
                else
                {
                    // Find all profiles and validate
                    if (profile?.Value != null)
                    {
                        retVal.Issue = ExtensionUtil.ProfileHandlers.Where(o => (profile.Value as FhirUri).Value == o.ProfileUri.ToString()).Select(o => o.Validate(resource.Resource))
                                       .SelectMany(i => i.Select(o => DataTypeConverter.ToIssue(o))).ToList();
                    }

                    try
                    {
                        // Instruct the handler to perform an update with
                        hdlr.Update(resource.Resource.Id, resource.Resource, Core.Services.TransactionMode.Rollback);
                        retVal.Issue.Add(new OperationOutcome.IssueComponent()
                        {
                            Diagnostics = "Resource Valid",
                            Severity    = OperationOutcome.IssueSeverity.Information,
                            Code        = OperationOutcome.IssueType.Unknown
                        });
                    }
                    catch (DetectedIssueException e)
                    {
                        retVal.Issue.AddRange(e.Issues.Select(o => DataTypeConverter.ToIssue(o)));
                    }
                    catch (Exception e)
                    {
                        retVal.Issue.Add(new OperationOutcome.IssueComponent()
                        {
                            Severity    = OperationOutcome.IssueSeverity.Error,
                            Code        = OperationOutcome.IssueType.NoStore,
                            Diagnostics = e.Message
                        });
                    }
                }
            }
            return(retVal);
        }
Exemple #10
0
        /// <summary>
        /// Map to Model
        /// </summary>
        protected override Core.Model.Entities.Organization MapToModel(Hl7.Fhir.Model.Organization resource)
        {
            Core.Model.Entities.Organization retVal = null;
            if (Guid.TryParse(resource.Id, out Guid key))
            {
                retVal = this.m_repository.Get(key);
            }
            else if (resource.Identifier?.Count > 0)
            {
                foreach (var ii in resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier))
                {
                    if (ii.LoadProperty(o => o.Authority).IsUnique)
                    {
                        retVal = this.m_repository.Find(o => o.Identifiers.Where(i => i.AuthorityKey == ii.AuthorityKey).Any(i => i.Value == ii.Value)).FirstOrDefault();
                    }
                    if (retVal != null)
                    {
                        break;
                    }
                }
            }
            if (retVal == null)
            {
                retVal = new Core.Model.Entities.Organization()
                {
                    Key = Guid.NewGuid()
                };
            }

            // Organization
            retVal.TypeConcept = resource.Type.Select(o => DataTypeConverter.ToConcept(o)).OfType <Concept>().FirstOrDefault();
            retVal.Addresses   = resource.Address.Select(DataTypeConverter.ToEntityAddress).ToList();

            // TODO: Extensions
            retVal.Identifiers = resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier).ToList();
            retVal.Names       = new List <EntityName>()
            {
                new EntityName(NameUseKeys.OfficialRecord, resource.Name)
            };
            retVal.Names.AddRange(resource.Alias.Select(o => new EntityName(NameUseKeys.Pseudonym, o)));
            retVal.StatusConceptKey = !resource.Active.HasValue || resource.Active == true ? StatusKeys.Active : StatusKeys.Inactive;
            retVal.Telecoms         = resource.Telecom.Select(DataTypeConverter.ToEntityTelecomAddress).OfType <EntityTelecomAddress>().ToList();

            if (resource.PartOf != null)
            {
                var reference = DataTypeConverter.ResolveEntity <Core.Model.Entities.Organization>(resource.PartOf, resource);
                if (reference == null)
                {
                    this.m_tracer.TraceError($"Could not resolve {resource.PartOf.Reference}");
                    throw new KeyNotFoundException(m_localizationService.FormatString("error.type.KeyNotFoundException.couldNotResolve", new
                    {
                        param = resource.PartOf.Reference
                    }));
                }

                // point the child organization entity at the target organization entity with a relationship of parent
                retVal.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Parent, reference));
            }
            retVal.Extensions = resource.Extension.Select(o => DataTypeConverter.ToEntityExtension(o, retVal)).OfType <EntityExtension>().ToList();
            return(retVal);
        }
        /// <summary>
        /// Write Address Space Element
        /// </summary>
        /// <param name="session"></param>
        /// <param name="itemId"></param>
        public void WriteAddresSpaceItem(DaSession session, string itemId, object selectedObject, bool isAddSpaceElem)
        {
            Helper.DataTypes dataTypeHelper = new DataTypes();
            this.panelBottom.Visible = true;

            isDaItem     = false;
            this.session = session;

            ValueQT[] itemValues;
            int[]     itemResults;
            int       result = session.Read(MAX_AGE_DEVICE, new string[] { itemId }, null, out itemValues, out itemResults, null);

            if (itemResults.Length == 0)
            {
                return;
            }
            if (itemValues.Length == 0)
            {
                return;
            }

            Type             itemDataType    = typeof(short);
            EnumAccessRights itemAccessRighs = EnumAccessRights.READWRITEABLE;
            bool             hasWriteAccess  = true;

            if (ResultCode.SUCCEEDED(result) && ResultCode.SUCCEEDED(itemResults[0]))
            {
                DaGetPropertiesOptions propertyGetOptions = new DaGetPropertiesOptions();
                propertyGetOptions.WhatPropertyData = EnumPropertyData.ALL;

                DaProperty[] properties = null;
                if (isAddSpaceElem)
                {
                    if (ResultCode.SUCCEEDED(session.GetDaProperties(itemId,
                                                                     null,
                                                                     propertyGetOptions,
                                                                     out properties,
                                                                     null)))
                    {
                        if (properties == null)
                        {
                            this.propertyGrid.SelectedObject = FillEmptyValueQT(itemId, null);
                            return;
                        }
                        if (properties.Length < 5)
                        {
                            this.propertyGrid.SelectedObject = FillEmptyValueQT(itemId, null);
                            return;
                        }
                        itemDataType    = DataTypeConverter.GetSysType((short)properties[0].ValueQT.Data);
                        itemAccessRighs = ObjToAccesssRights(properties[4].ValueQT.Data);
                    }
                }
                else
                {
                    itemDataType = (selectedObject as DaProperty).DataType;
                }

                //the item value is null
                if (itemValues[0] == null)
                {
                    this.propertyGrid.SelectedObject = FillEmptyValueQT(itemId, itemDataType);
                    return;
                }

                if (itemAccessRighs == EnumAccessRights.READABLE)
                {
                    hasWriteAccess = false;
                }
            }
            this.propertyGrid.SelectedObject = FillWriteService(itemId, itemDataType, hasWriteAccess, itemValues[0]);
        }
        /// <summary>
        /// Map to FHIR
        /// </summary>
        protected override Condition MapToFhir(CodedObservation model, WebOperationContext webOperationContext)
        {
            var retVal = DataTypeConverter.CreateResource <Condition>(model);

            retVal.Identifier = model.LoadCollection <ActIdentifier>("Identifiers").Select(o => DataTypeConverter.ToFhirIdentifier <Act>(o)).ToList();

            // Clinical status of the condition
            if (model.StatusConceptKey == StatusKeys.Active)
            {
                retVal.ClinicalStatus = ConditionClinicalStatus.Active;
            }
            else if (model.StatusConceptKey == StatusKeys.Completed)
            {
                retVal.ClinicalStatus = ConditionClinicalStatus.Resolved;
            }
            else if (model.StatusConceptKey == StatusKeys.Nullified)
            {
                retVal.VerificationStatus = ConditionVerificationStatus.EnteredInError;
            }
            else if (model.StatusConceptKey == StatusKeys.Obsolete)
            {
                retVal.ClinicalStatus = ConditionClinicalStatus.Inactive;
            }

            // Category
            retVal.Category.Add(new MARC.HI.EHRS.SVC.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/condition-category"), "encounter-diagnosis"));

            // Severity?
            var actRelationshipService = ApplicationContext.Current.GetService <IDataPersistenceService <ActRelationship> >();

            var severity = actRelationshipService.Query(o => o.SourceEntityKey == model.Key && o.RelationshipTypeKey == ActRelationshipTypeKeys.HasComponent && o.TargetAct.TypeConceptKey == ObservationTypeKeys.Severity, AuthenticationContext.Current.Principal);

            if (severity == null)             // Perhaps we should get from neighbor if this is in an encounter
            {
                var contextAct = actRelationshipService.Query(o => o.TargetActKey == model.Key, AuthenticationContext.Current.Principal).FirstOrDefault();
                if (contextAct != null)
                {
                    severity = actRelationshipService.Query(o => o.SourceEntityKey == contextAct.SourceEntityKey && o.RelationshipTypeKey == ActRelationshipTypeKeys.HasComponent && o.TargetAct.TypeConceptKey == ObservationTypeKeys.Severity, AuthenticationContext.Current.Principal);
                }
            }

            // Severity
            if (severity != null)
            {
                retVal.Severity = DataTypeConverter.ToFhirCodeableConcept((severity as CodedObservation).LoadProperty <Concept>("Value"));
            }

            retVal.Code = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("Value"));

            // body sites?
            var sites = actRelationshipService.Query(o => o.SourceEntityKey == model.Key && o.RelationshipTypeKey == ActRelationshipTypeKeys.HasComponent && o.TargetAct.TypeConceptKey == ObservationTypeKeys.FindingSite, AuthenticationContext.Current.Principal);

            retVal.BodySite = sites.Select(o => DataTypeConverter.ToFhirCodeableConcept(o.LoadProperty <CodedObservation>("TargetAct").LoadProperty <Concept>("Value"))).ToList();

            // Subject
            var recordTarget = model.LoadCollection <ActParticipation>("Participations").FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.RecordTarget);

            if (recordTarget != null)
            {
                this.traceSource.TraceInformation("RCT: {0}", recordTarget.PlayerEntityKey);
                retVal.Subject = DataTypeConverter.CreateReference <Patient>(recordTarget.LoadProperty <Entity>("PlayerEntity"), webOperationContext);
            }
            // Onset
            if (model.StartTime.HasValue || model.StopTime.HasValue)
            {
                retVal.Onset = new FhirPeriod()
                {
                    Start = model.StartTime?.DateTime,
                    Stop  = model.StopTime?.DateTime
                }
            }
            ;
            else
            {
                retVal.Onset = new FhirDateTime(model.ActTime.DateTime);
            }

            retVal.AssertionDate = model.CreationTime.LocalDateTime;
            var author = model.LoadCollection <ActParticipation>("Participations").FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.Authororiginator);

            if (author != null)
            {
                retVal.Asserter = DataTypeConverter.CreatePlainReference <Practitioner>(author.LoadProperty <Entity>("PlayerEntity"), webOperationContext);
            }

            return(retVal);
        }
Exemple #13
0
        /// <summary>
        /// Map the specified patient encounter to a FHIR based encounter
        /// </summary>
        protected override Encounter MapToFhir(PatientEncounter model)
        {
            var retVal = DataTypeConverter.CreateResource <Encounter>(model);

            // Map the identifier
            retVal.Identifier = model.LoadCollection <ActIdentifier>("Identifiers").Select(o => DataTypeConverter.ToFhirIdentifier(o)).ToList();

            // Map status keys
            switch (model.StatusConceptKey.ToString().ToUpper())
            {
            case StatusKeyStrings.Active:
            case StatusKeyStrings.New:
                switch (model.MoodConceptKey.ToString().ToUpper())
                {
                case MoodConceptKeyStrings.Eventoccurrence:
                case MoodConceptKeyStrings.Request:
                    retVal.Status = Encounter.EncounterStatus.InProgress;
                    break;

                case MoodConceptKeyStrings.Intent:
                case MoodConceptKeyStrings.Promise:
                    retVal.Status = Encounter.EncounterStatus.Planned;
                    break;
                }

                break;

            case StatusKeyStrings.Cancelled:
                retVal.Status = Encounter.EncounterStatus.Cancelled;
                break;

            case StatusKeyStrings.Nullified:
                retVal.Status = Encounter.EncounterStatus.EnteredInError;
                break;

            case StatusKeyStrings.Obsolete:
                retVal.Status = Encounter.EncounterStatus.Unknown;
                break;

            case StatusKeyStrings.Completed:
                retVal.Status = Encounter.EncounterStatus.Finished;
                break;
            }

            if (model.StartTime.HasValue || model.StopTime.HasValue)
            {
                retVal.Period = DataTypeConverter.ToPeriod(model.StartTime, model.StopTime);
            }
            else
            {
                retVal.Period = DataTypeConverter.ToPeriod(model.ActTime, model.ActTime);
            }

            retVal.ReasonCode = new List <CodeableConcept>
            {
                DataTypeConverter.ToFhirCodeableConcept(model.ReasonConceptKey)
            };

            retVal.Class = DataTypeConverter.ToFhirCodeableConcept(model.TypeConceptKey).GetCoding();

            // Map associated
            var associated = model.LoadCollection <ActParticipation>("Participations").ToArray();

            // Subject of encounter
            retVal.Subject = DataTypeConverter.CreateNonVersionedReference <Patient>(associated.FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.RecordTarget)?.LoadProperty <Entity>("PlayerEntity"));

            // Locations
            retVal.Location = associated.Where(o => o.LoadProperty <Entity>("PlayerEntity") is Place).Select(o => new Encounter.LocationComponent
            {
                Period   = DataTypeConverter.ToPeriod(model.CreationTime, null),
                Location = DataTypeConverter.CreateVersionedReference <Location>(o.PlayerEntity)
            }).ToList();

            // Service provider
            var cst = associated.FirstOrDefault(o => o.LoadProperty <Entity>("PlayerEntity") is Organization && o.ParticipationRoleKey == ActParticipationKey.Custodian);

            if (cst != null)
            {
                retVal.ServiceProvider = DataTypeConverter.CreateVersionedReference <Hl7.Fhir.Model.Organization>(cst.PlayerEntity);
            }

            // Participants
            retVal.Participant = associated.Where(o => o.LoadProperty <Entity>("PlayerEntity") is Provider || o.LoadProperty <Entity>("PlayerEntity") is UserEntity).Select(o => new Encounter.ParticipantComponent
            {
                Type = new List <CodeableConcept>
                {
                    DataTypeConverter.ToFhirCodeableConcept(o.ParticipationRoleKey)
                },
                Individual = DataTypeConverter.CreateVersionedReference <Practitioner>(o.PlayerEntity)
            }).ToList();

            return(retVal);
        }
Exemple #14
0
        /// <summary>
        /// Map to model the encounter
        /// </summary>
        protected override PatientEncounter MapToModel(Encounter resource)
        {
            var status = resource.Status;

            var retVal = new PatientEncounter
            {
                TypeConcept = DataTypeConverter.ToConcept(resource.Class, "http://santedb.org/conceptset/v3-ActEncounterCode"),
                // TODO: Extensions
                Extensions       = resource.Extension.Select(DataTypeConverter.ToActExtension).OfType <ActExtension>().ToList(),
                Identifiers      = resource.Identifier.Select(DataTypeConverter.ToActIdentifier).ToList(),
                Key              = Guid.NewGuid(),
                StatusConceptKey = status == Encounter.EncounterStatus.Finished ? StatusKeys.Completed :
                                   status == Encounter.EncounterStatus.Cancelled ? StatusKeys.Cancelled :
                                   status == Encounter.EncounterStatus.InProgress || status == Encounter.EncounterStatus.Arrived ? StatusKeys.Active :
                                   status == Encounter.EncounterStatus.Planned ? StatusKeys.New :
                                   status == Encounter.EncounterStatus.EnteredInError ? StatusKeys.Nullified : StatusKeys.Inactive,
                MoodConceptKey = status == Encounter.EncounterStatus.Planned ? ActMoodKeys.Intent : ActMoodKeys.Eventoccurrence,
                ReasonConcept  = DataTypeConverter.ToConcept(resource.ReasonCode.FirstOrDefault()),
                StartTime      = DataTypeConverter.ToDateTimeOffset(resource.Period.Start),
                StopTime       = DataTypeConverter.ToDateTimeOffset(resource.Period.End)
            };

            if (!Guid.TryParse(resource.Id, out var key))
            {
                key = Guid.NewGuid();
            }

            retVal.Key = key;

            // Attempt to resolve relationships
            if (resource.Subject != null)
            {
                // if the subject is a UUID then add the record target key
                // otherwise attempt to resolve the reference
                retVal.Participations.Add(resource.Subject.Reference.StartsWith("urn:uuid:") ? new ActParticipation(ActParticipationKey.RecordTarget, Guid.Parse(resource.Subject.Reference.Substring(9))) : new ActParticipation(ActParticipationKey.RecordTarget, DataTypeConverter.ResolveEntity <Core.Model.Roles.Patient>(resource.Subject, resource)));
            }

            // Attempt to resolve organization
            if (resource.ServiceProvider != null)
            {
                // Is the subject a uuid
                if (resource.ServiceProvider.Reference.StartsWith("urn:uuid:"))
                {
                    retVal.Participations.Add(new ActParticipation(ActParticipationKey.Custodian, Guid.Parse(resource.ServiceProvider.Reference.Substring(9))));
                }
                else
                {
                    this.m_tracer.TraceError("Only UUID references are supported");
                    throw new NotSupportedException(this.m_localizationService.FormatString("error.type.NotSupportedException.paramOnlySupported", new
                    {
                        param = "UUID"
                    }));
                }
            }

            // TODO : Other Participations
            return(retVal);
        }
Exemple #15
0
        /// <summary>
        /// Map the inbound place to a FHIR model
        /// </summary>
        protected override Location MapToFhir(Place model)
        {
            Location retVal = DataTypeConverter.CreateResource <Location>(model);

            retVal.Identifier = model.LoadCollection <EntityIdentifier>("Identifiers").Select(o => DataTypeConverter.ToFhirIdentifier <Entity>(o)).ToList();

            // Map status
            switch (model.StatusConceptKey.ToString().ToUpper())
            {
            case StatusKeyStrings.Active:
            case StatusKeyStrings.New:
                retVal.Status = Location.LocationStatus.Active;
                break;

            case StatusKeyStrings.Cancelled:
                retVal.Status = Location.LocationStatus.Suspended;
                break;

            case StatusKeyStrings.Nullified:
            case StatusKeyStrings.Obsolete:
            case StatusKeyStrings.Inactive:
                retVal.Status = Location.LocationStatus.Inactive;
                break;
            }

            retVal.Name  = model.LoadCollection <EntityName>("Names").FirstOrDefault(o => o.NameUseKey == NameUseKeys.OfficialRecord)?.LoadCollection <EntityNameComponent>("Component")?.FirstOrDefault()?.Value;
            retVal.Alias = model.LoadCollection <EntityName>("Names").Where(o => o.NameUseKey != NameUseKeys.OfficialRecord)?.Select(n => n.LoadCollection <EntityNameComponent>("Component")?.FirstOrDefault()?.Value).ToList();

            // Convert the determiner code
            if (model.DeterminerConceptKey == DeterminerKeys.Described)
            {
                retVal.Mode = Location.LocationMode.Kind;
            }
            else
            {
                retVal.Mode = Location.LocationMode.Instance;
            }

            retVal.Type = new List <CodeableConcept>()
            {
                DataTypeConverter.ToFhirCodeableConcept(model.TypeConceptKey, "http://hl7.org/fhir/ValueSet/v3-ServiceDeliveryLocationRoleType")
            };
            retVal.Telecom = model.LoadCollection <EntityTelecomAddress>("Telecoms").Select(o => DataTypeConverter.ToFhirTelecom(o)).ToList();
            retVal.Address = DataTypeConverter.ToFhirAddress(model.LoadCollection <EntityAddress>("Addresses").FirstOrDefault());

            if (model.GeoTag != null)
            {
                retVal.Position = new Location.PositionComponent()
                {
                    Latitude  = (decimal)model.GeoTag.Lat,
                    Longitude = (decimal)model.GeoTag.Lng
                }
            }
            ;

            // Part of?
            var parent = model.LoadCollection <EntityRelationship>(nameof(Entity.Relationships)).FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.Parent);

            if (parent != null)
            {
                retVal.PartOf = DataTypeConverter.CreateVersionedReference <Location>(parent.LoadProperty <Entity>(nameof(EntityRelationship.TargetEntity)));
            }

            return(retVal);
        }
        /// <summary>
        /// Gets the MySql datatype definition as string
        /// </summary>
        /// <param name="column">The column.</param>
        /// <returns></returns>
        public string WriteDataType(DatabaseColumn column)
        {
            if (column == null)
            {
                return(string.Empty);
            }
            if (string.IsNullOrEmpty(column.DbDataType))
            {
                return(string.Empty);
            }
            //we don't do column.DbDataTypeStandard() as native types will have length/precision-scale
            //and also ints will have the UNSIGNED marker
            //These types will fall through unchanged.
            var dataType = column.DbDataType.ToUpperInvariant();
            //int providerType = -1;
            //if (column.DataType != null)
            //    providerType = column.DataType.ProviderDbType;

            var precision = column.Precision;
            var scale     = column.Scale;
            var length    = column.Length;

            //oracle to MySql translation
            if (dataType == "NUMBER")
            {
                dataType = DataTypeConverter.OracleNumberConversion(precision, scale);
            }
            if (dataType.StartsWith("TIMESTAMP", StringComparison.OrdinalIgnoreCase) &&
                DataTypeConverter.IsSqlServerTimestamp(dataType, column))
            {
                dataType = "TINYBLOB"; //there's no equivalent really
            }

            if (dataType == "VARCHAR2" || dataType == "NVARCHAR" || dataType == "NVARCHAR2")
            {
                dataType = ConvertString(length);
            }
            else if (dataType == "CLOB" || dataType == "NTEXT")
            {
                dataType = "LONGTEXT";
            }
            else if (dataType == "NCHAR")
            {
                dataType = "CHAR";
            }
            else if (dataType == "DATETIME2" || dataType == "TIME")
            {
                dataType = "DATETIME";
            }
            else if (dataType == "MONEY")
            {
                dataType  = "DECIMAL";
                precision = 19;
                scale     = 4;
            }
            else if (dataType == "BIT")
            {
                dataType = "TINYINT";
            }

            else if (dataType == "IMAGE" || dataType == "VARBINARY")
            {
                dataType = ConvertBlob(length);
            }
            else if (dataType == "UNIQUEIDENTIFIER")
            {
                dataType = "VARCHAR";
                length   = 64;
            }
            else if (dataType == "XML" || dataType == "XMLTYPE")
            {
                dataType = "TEXT";
            }
            //write out MySql datatype definition
            if (dataType == "VARCHAR" ||
                dataType == "CHAR" ||
                dataType == "BINARY" ||
                dataType == "VARBINARY")
            {
                dataType = dataType + " (" + length + ")";
            }

            if (dataType == "NUMERIC" ||
                dataType == "DECIMAL")
            {
                var writeScale = ((scale != null) && (scale > 0) ? "," + scale : "");
                dataType = dataType + " (" + precision + writeScale + ")";
            }

            return(dataType);
        }
Exemple #17
0
        /// <summary>
        /// The current gas price in Wei (1 ETH equals 1000000000000000000 Wei ).
        /// </summary>
        /// <returns>The gas price.</returns>
        public async Task <long> GetGasPrice()
        {
            string jsonResponse = await _in3.SendRpc(EthGasPrice, new object[] { });

            return((long)DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
Exemple #18
0
 public override string ToString()
 {
     return(DataTypeConverter.Convert(this.DataType, this.BarType, new long?()));
 }
Exemple #19
0
        /// <summary>
        /// Returns the balance of the account of given <paramref name="address" />.
        /// </summary>
        /// <param name="address">Address to check for balance.</param>
        /// <param name="blockNumber">Block number or <see cref="BlockParameter.Latest" /> or <see cref="BlockParameter.Earliest" />.</param>
        /// <returns>The current balance in wei.</returns>
        public async Task <BigInteger> GetBalance(string address, BigInteger blockNumber)
        {
            string jsonResponse = await _in3.SendRpc(EthGetBalance, new object[] { address, BlockParameter.AsString(blockNumber) });

            return(DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
Exemple #20
0
        private static string OtherDatabaseTypesToPostgreSql(string dataType, DatabaseColumn column)
        {
            //string types
            //character(n) (aka char(n)) character varying(n) aka varchar(n) and text
            if (DataTypeConverter.IsFixedLengthString(dataType))
            {
                return("CHAR");
            }
            if (DataTypeConverter.IsLongString(dataType))
            {
                return("TEXT");
            }
            if (DataTypeConverter.IsVariableString(dataType))
            {
                if (column.Length == -1)
                {
                    return("TEXT");
                }
                return("VARCHAR");
            }

            //numeric types
            if (dataType == "INT")
            {
                return("INTEGER");
            }
            if (dataType == "INT4")
            {
                return("INTEGER");                    //this is a PostgreSql alias, we'll use standard SQL
            }
            //else if (dataType == "SERIAL") return "INTEGER"; //this is a PostgreSql alias, we'll use standard SQL
            //else if (dataType == "BIGSERIAL") return "BIGINT"; //this is a PostgreSql alias, we'll use standard SQL
            if (dataType == "INT8")
            {
                return("BIGINT");                    //this is a PostgreSql alias, we'll use standard SQL
            }
            if (dataType == "INT2")
            {
                return("SMALLINT");                    //this is a PostgreSql alias, we'll use standard SQL
            }
            if (dataType == "TINYINT")
            {
                return("SMALLINT");                       //this is a MsSql alias, we'll use standard SQL
            }
            if (dataType == "NUMBER")
            {
                return(DataTypeConverter.OracleNumberConversion(column.Precision, column.Scale));
            }

            //float and real
            if (dataType == "FLOAT4")
            {
                return("REAL");                      //this is a PostgreSql alias, we'll use standard SQL
            }
            if (dataType == "FLOAT")
            {
                return("DOUBLE PRECISION");
            }

            //date times
            //SqlServer Timestamp is a binary
            if (DataTypeConverter.IsSqlServerTimestamp(dataType, column))
            {
                return("BYTEA"); //this is just a byte array- functionally you should redesign the table and perhaps use the system extension columns
            }
            if (DataTypeConverter.IsDateTime(dataType))
            {
                return("TIMESTAMP");
            }

            //bytes
            if (DataTypeConverter.IsBlob(dataType, column))
            {
                return("OID");//blobs become object ids
            }
            if (DataTypeConverter.IsBinary(dataType))
            {
                return("BYTEA");
            }

            //there is a native BIT(n) type in Postgresql, but in conversion we probably mean boolean.
            if (dataType == "BIT" && !column.Length.HasValue)
            {
                return("BOOLEAN");
            }

            //other types
            if (dataType == "XMLTYPE")
            {
                return("XML");
            }
            if (dataType == "UNIQUEIDENTIFIER")
            {
                return("UUID");
            }
            return(dataType);
        }
Exemple #21
0
        /// <summary>
        /// Uninstalls a previously created filter.
        /// </summary>
        /// <param name="filterId">The filter id returned by <see cref="Eth1.Api.NewBlockFilter" />.</param>
        /// <returns>The result of the operation, <see langword="true" /> on success or <see langword="false" /> on failure.</returns>
        public async Task <bool> UninstallFilter(long filterId)
        {
            string jsonResponse = await _in3.SendRpc(EthUninstallFilter, new object[] { DataTypeConverter.BigIntToPrefixedHex(filterId) });

            return(RpcHandler.From <bool>(jsonResponse));
        }
        /// <summary>
        /// Map to model the encounter
        /// </summary>
        protected override PatientEncounter MapToModel(Encounter resource, RestOperationContext webOperationContext)
        {
            // Organization
            var status = resource.Status?.Value;
            var retVal = new PatientEncounter()
            {
                TypeConcept = DataTypeConverter.ToConcept(resource.Class, new Uri("http://openiz.org/conceptset/v3-ActEncounterCode")),
                StartTime   = resource.Period?.Start?.DateValue,
                StopTime    = resource.Period?.Stop?.DateValue,
                // TODO: Extensions
                Extensions       = resource.Extension.Select(DataTypeConverter.ToActExtension).OfType <ActExtension>().ToList(),
                Identifiers      = resource.Identifier.Select(DataTypeConverter.ToActIdentifier).ToList(),
                Key              = Guid.NewGuid(),
                StatusConceptKey = status == EncounterStatus.Finished ? StatusKeys.Completed :
                                   status == EncounterStatus.Cancelled ? StatusKeys.Cancelled :
                                   status == EncounterStatus.InProgress || status == EncounterStatus.Arrived ? StatusKeys.Active :
                                   status == EncounterStatus.Planned ? StatusKeys.Active : StatusKeys.Obsolete,
                MoodConceptKey = status == EncounterStatus.Planned ? ActMoodKeys.Intent : ActMoodKeys.Eventoccurrence,
                ReasonConcept  = DataTypeConverter.ToConcept(resource.Reason)
            };

            // Parse key
            Guid key;

            if (!Guid.TryParse(resource.Id, out key))
            {
                key = Guid.NewGuid();
            }
            retVal.Key = key;

            // Attempt to resolve relationships
            if (resource.Subject != null)
            {
                // Is the subject a uuid
                if (resource.Subject.ReferenceUrl.Value.StartsWith("urn:uuid:"))
                {
                    retVal.Participations.Add(new ActParticipation(ActParticipationKey.RecordTarget, Guid.Parse(resource.Subject.ReferenceUrl.Value.Substring(9))));
                }
                else
                {
                    throw new NotSupportedException("Only UUID references are supported");
                }
            }

            // Attempt to resolve organiztaion
            if (resource.ServiceProvider != null)
            {
                // Is the subject a uuid
                if (resource.ServiceProvider.ReferenceUrl.Value.StartsWith("urn:uuid:"))
                {
                    retVal.Participations.Add(new ActParticipation(ActParticipationKey.Custodian, Guid.Parse(resource.ServiceProvider.ReferenceUrl.Value.Substring(9))));
                }
                else
                {
                    throw new NotSupportedException("Only UUID references are supported");
                }
            }

            // TODO : Other Participations
            return(retVal);
        }
Exemple #23
0
        /// <summary>
        /// Retrieve the logs for a certain filter. Logs marks changes of state on the blockchain for events. Equivalent to <see cref="Eth1.Api.GetFilterChangesFromLogs" />.
        /// </summary>
        /// <param name="filterId">Id returned during the filter creation.</param>
        /// <returns>Array of logs which occurred since last poll.</returns>
        /// <remarks>
        /// <para>Since the return is the <see langword="Log[]" /> since last poll, executing this multiple times changes the state making this a "non-idempotent" getter.</para>
        /// </remarks>
        public async Task <Log[]> GetFilterLogs(long filterId)
        {
            string jsonResponse = await _in3.SendRpc(EthGetFilterLogs, new object[] { DataTypeConverter.BigIntToPrefixedHex((BigInteger)filterId) });

            return(RpcHandler.From <Log[]>(jsonResponse));
        }
        /// <summary>
        /// Map the specified patient encounter to a FHIR based encounter
        /// </summary>
        protected override Encounter MapToFhir(PatientEncounter model, RestOperationContext restOperationContext)
        {
            var retVal = DataTypeConverter.CreateResource <Encounter>(model);

            // Map the identifier
            retVal.Identifier = model.LoadCollection <ActIdentifier>("Identifiers").Select(o => DataTypeConverter.ToFhirIdentifier <Act>(o)).ToList();

            // Map status keys
            switch (model.StatusConceptKey.ToString().ToUpper())
            {
            case StatusKeyStrings.Active:
                retVal.Status = EncounterStatus.InProgress;
                break;

            case StatusKeyStrings.Cancelled:
            case StatusKeyStrings.Nullified:
                retVal.Status = EncounterStatus.Cancelled;
                break;

            case StatusKeyStrings.Completed:
                retVal.Status = EncounterStatus.Finished;
                break;
            }

            if (model.StartTime.HasValue || model.StopTime.HasValue)
            {
                retVal.Period = new FhirPeriod()
                {
                    Start = model.StartTime?.DateTime,
                    Stop  = model.StopTime?.DateTime
                }
            }
            ;
            else
            {
                retVal.Period = new FhirPeriod()
                {
                    Start = model.ActTime.DateTime,
                    Stop  = model.ActTime.DateTime
                }
            };

            retVal.Reason = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("ReasonConcept"));
            retVal.Type   = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("TypeConcept"));

            // Map associated
            var associated = model.LoadCollection <ActParticipation>("Participations");

            // Subject of encounter
            retVal.Subject = DataTypeConverter.CreateReference <SanteDB.Messaging.FHIR.Resources.Patient>(associated.FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.RecordTarget)?.LoadProperty <Entity>("PlayerEntity"), restOperationContext);

            // Locations
            retVal.Location = associated.Where(o => o.LoadProperty <Entity>("PlayerEntity") is Place).Select(o => new EncounterLocation()
            {
                Period = new FhirPeriod()
                {
                    Start = model.CreationTime.DateTime
                },
                Location = DataTypeConverter.CreateReference <Location>(o.PlayerEntity, restOperationContext)
            }).ToList();

            // Service provider
            var cst = associated.FirstOrDefault(o => o.LoadProperty <Entity>("PlayerEntity") is Core.Model.Entities.Organization && o.ParticipationRoleKey == ActParticipationKey.Custodian);

            if (cst != null)
            {
                retVal.ServiceProvider = DataTypeConverter.CreateReference <SanteDB.Messaging.FHIR.Resources.Organization>(cst.PlayerEntity, restOperationContext);
            }

            // Participants
            retVal.Participant = associated.Where(o => o.LoadProperty <Entity>("PlayerEntity") is Provider || o.LoadProperty <Entity>("PlayerEntity") is UserEntity).Select(o => new EncounterParticipant()
            {
                Period = new FhirPeriod()
                {
                    Start = model.CreationTime.DateTime
                },
                Type = new List <FhirCodeableConcept>()
                {
                    DataTypeConverter.ToFhirCodeableConcept(o.LoadProperty <Concept>("ParticipationRole"))
                },
                Individual = DataTypeConverter.CreateReference <Practitioner>(o.PlayerEntity, restOperationContext)
            }).ToList();


            return(retVal);
        }
Exemple #25
0
        /// <summary>
        /// Returns the number of the most recent block the in3 network can collect signatures to verify.
        /// Can be changed by <see cref="Configuration.ClientConfiguration.ReplaceLatestBlock" />.
        /// If you need the very latest block, change <see cref="Configuration.ClientConfiguration.SignatureCount" /> to <see langword="0"/>.
        /// </summary>
        /// <returns>The number of the block.</returns>
        public async Task <BigInteger> BlockNumber()
        {
            string jsonResponse = await _in3.SendRpc(EthBlockNumber, new object[] { });

            return(DataTypeConverter.HexStringToBigint(RpcHandler.From <string>(jsonResponse)));
        }
 /// <summary>
 /// Map to FHIR
 /// </summary>
 protected override SanteDB.Messaging.FHIR.Resources.Organization MapToFhir(Core.Model.Entities.Organization model, RestOperationContext webOperationContext)
 {
     return(DataTypeConverter.CreateResource <SanteDB.Messaging.FHIR.Resources.Organization>(model));
 }
Exemple #27
0
        /// <summary>
        /// Maps a FHIR patient resource to an HDSI patient.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <returns>Returns the mapped model.</returns>
        protected override Core.Model.Roles.Patient MapToModel(Patient resource)
        {
            Core.Model.Roles.Patient patient = null;

            // Attempt to XRef
            if (Guid.TryParse(resource.Id, out Guid key))
            {
                patient = this.m_repository.Get(key);

                // Patient doesn't exist?
                if (patient == null)
                {
                    patient = new Core.Model.Roles.Patient
                    {
                        Key = key
                    };
                }
            }
            else if (resource.Identifier.Any())
            {
                foreach (var ii in resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier))
                {
                    if (ii.LoadProperty(o => o.Authority).IsUnique)
                    {
                        patient = this.m_repository.Find(o => o.Identifiers.Where(i => i.AuthorityKey == ii.AuthorityKey).Any(i => i.Value == ii.Value)).FirstOrDefault();
                    }
                    if (patient != null)
                    {
                        break;
                    }
                }

                if (patient == null)
                {
                    patient = new Core.Model.Roles.Patient
                    {
                        Key = Guid.NewGuid()
                    };
                }
            }
            else
            {
                patient = new Core.Model.Roles.Patient
                {
                    Key = Guid.NewGuid()
                };
            }

            patient.Addresses             = resource.Address.Select(DataTypeConverter.ToEntityAddress).ToList();
            patient.CreationTime          = DateTimeOffset.Now;
            patient.GenderConceptKey      = resource.Gender == null ? null : DataTypeConverter.ToConcept(new Coding("http://hl7.org/fhir/administrative-gender", Hl7.Fhir.Utility.EnumUtility.GetLiteral(resource.Gender)))?.Key;
            patient.Identifiers           = resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier).ToList();
            patient.LanguageCommunication = resource.Communication.Select(DataTypeConverter.ToLanguageCommunication).ToList();
            patient.Names            = resource.Name.Select(DataTypeConverter.ToEntityName).ToList();
            patient.StatusConceptKey = resource.Active == null || resource.Active == true ? StatusKeys.Active : StatusKeys.Inactive;
            patient.Telecoms         = resource.Telecom.Select(DataTypeConverter.ToEntityTelecomAddress).OfType <EntityTelecomAddress>().ToList();
            patient.Relationships    = resource.Contact.Select(r => DataTypeConverter.ToEntityRelationship(r, resource)).ToList();
            patient.Extensions       = resource.Extension.Select(o => DataTypeConverter.ToEntityExtension(o, patient)).ToList();

            patient.DateOfBirth = DataTypeConverter.ToDateTimeOffset(resource.BirthDate, out var dateOfBirthPrecision)?.DateTime;
            // TODO: fix
            // HACK: the date of birth precision CK only allows "Y", "M", or "D" for the precision value
            patient.DateOfBirthPrecision = dateOfBirthPrecision == DatePrecision.Full ? DatePrecision.Day : dateOfBirthPrecision;

            switch (resource.Deceased)
            {
            case FhirDateTime dtValue when !String.IsNullOrEmpty(dtValue.Value):
                patient.DeceasedDate = DataTypeConverter.ToDateTimeOffset(dtValue.Value, out var datePrecision)?.DateTime;
                // TODO: fix
                // HACK: the deceased date precision CK only allows "Y", "M", or "D" for the precision value
                patient.DeceasedDatePrecision = datePrecision == DatePrecision.Full ? DatePrecision.Day : datePrecision;
                break;

            case FhirBoolean boolValue when boolValue.Value.GetValueOrDefault():
                // we don't have a field for "deceased indicator" to say that the patient is dead, but we don't know that actual date/time of death
                // should find a better way to do this
                patient.DeceasedDate = DateTime.MinValue;

                patient.DeceasedDatePrecision = DatePrecision.Year;
                break;
            }

            switch (resource.MultipleBirth)
            {
            case FhirBoolean boolBirth when boolBirth.Value.GetValueOrDefault():
                patient.MultipleBirthOrder = 0;

                break;

            case Integer intBirth:
                patient.MultipleBirthOrder = intBirth.Value;
                break;
            }

            if (resource.GeneralPractitioner != null)
            {
                patient.Relationships.AddRange(resource.GeneralPractitioner.Select(r =>
                {
                    var referenceKey = DataTypeConverter.ResolveEntity <Core.Model.Roles.Provider>(r, resource) as Entity ?? DataTypeConverter.ResolveEntity <Core.Model.Entities.Organization>(r, resource);

                    if (referenceKey == null)
                    {
                        this.m_tracer.TraceError("Can't locate a registered general practitioner");
                        throw new KeyNotFoundException(m_localizationService.FormatString("error.type.KeyNotFoundException.cannotLocateRegistered", new
                        {
                            param = "general practitioner"
                        }));
                    }

                    return(new EntityRelationship(EntityRelationshipTypeKeys.HealthcareProvider, referenceKey));
                }));
            }
            if (resource.ManagingOrganization != null)
            {
                var referenceKey = DataTypeConverter.ResolveEntity <Core.Model.Entities.Organization>(resource.ManagingOrganization, resource);

                if (referenceKey == null)
                {
                    this.m_tracer.TraceError("Can't locate a registered managing organization");

                    throw new KeyNotFoundException(m_localizationService.FormatString("error.type.KeyNotFoundException.cannotLocateRegistered", new
                    {
                        param = "managing organization"
                    }));
                }

                patient.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Scoper, referenceKey));
            }

            // Process contained related persons
            foreach (var itm in resource.Contained.OfType <RelatedPerson>())
            {
                var er = FhirResourceHandlerUtil.GetMappersFor(ResourceType.RelatedPerson).First().MapToModel(itm) as Core.Model.Entities.EntityRelationship;

                // Relationship bindings
                er.ClassificationKey = RelationshipClassKeys.ContainedObjectLink;
                er.SourceEntityKey   = patient.Key;

                // Now add rels to me
                patient.Relationships.Add(er);
            }

            // Links
            foreach (var lnk in resource.Link)
            {
                switch (lnk.Type.Value)
                {
                case Patient.LinkType.Replaces:
                {
                    // Find the victim
                    var replacee = DataTypeConverter.ResolveEntity <Core.Model.Roles.Patient>(lnk.Other, resource);

                    if (replacee == null)
                    {
                        this.m_tracer.TraceError($"Cannot locate patient referenced by {lnk.Type} relationship");
                        throw new KeyNotFoundException(m_localizationService.FormatString("error.messaging.fhir.patientResource.cannotLocatePatient", new
                            {
                                param = lnk.Type
                            }));
                    }

                    replacee.StatusConceptKey = StatusKeys.Obsolete;
                    patient.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Replaces, replacee));
                    break;
                }

                case Patient.LinkType.ReplacedBy:
                {
                    // Find the new
                    var replacer = DataTypeConverter.ResolveEntity <Core.Model.Roles.Patient>(lnk.Other, resource);

                    if (replacer == null)
                    {
                        this.m_tracer.TraceError($"Cannot locate patient referenced by {lnk.Type} relationship");
                        throw new KeyNotFoundException(m_localizationService.FormatString("error.messaging.fhir.patientResource.cannotLocatePatient", new
                            {
                                param = lnk.Type
                            }));
                    }

                    patient.StatusConceptKey = StatusKeys.Obsolete;
                    patient.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Replaces, patient)
                        {
                            HolderKey = replacer.Key
                        });
                    break;
                }

                case Patient.LinkType.Seealso:
                {
                    var referee = DataTypeConverter.ResolveEntity <Entity>(lnk.Other, resource);        // We use Entity here in lieu Patient since the code below can handle the MDM layer

                    // Is this a current MDM link?
                    if (referee.GetTag(FhirConstants.PlaceholderTag) == "true")         // The referee wants us to become the data
                    {
                        patient.Key = referee.Key;
                    }
                    else if (referee.LoadCollection(o => o.Relationships).Any(r => r.RelationshipTypeKey == MDM_MASTER_LINK) &&
                             referee.GetTag("$mdm.type") == "M")       // HACK: This is a master and someone is attempting to point another record at it
                    {
                        patient.Relationships.Add(new EntityRelationship()
                            {
                                RelationshipTypeKey = MDM_MASTER_LINK,
                                SourceEntityKey     = referee.Key,
                                TargetEntityKey     = patient.Key
                            });
                    }
                    else
                    {
                        patient.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.EquivalentEntity, referee));
                    }
                    break;
                }

                case Patient.LinkType.Refer:     // This points to a more detailed view of the patient
                {
                    var referee = DataTypeConverter.ResolveEntity <Entity>(lnk.Other, resource);
                    if (referee.GetTag("$mdm.type") == "M")         // HACK: MDM User is attempting to point this at another Master (note: THE MDM LAYER WON'T LIKE THIS)
                    {
                        patient.Relationships.Add(new EntityRelationship(MDM_MASTER_LINK, referee));
                    }
                    else
                    {
                        this.m_tracer.TraceError($"Setting refer relationships to source of truth is not supported");
                        throw new NotSupportedException(m_localizationService.GetString("error.type.NotSupportedException.userMessage"));
                    }

                    break;         // TODO: These are special cases of references
                }
                }
            }

            if (resource.Photo != null && resource.Photo.Any())
            {
                patient.Extensions.RemoveAll(o => o.ExtensionTypeKey == ExtensionTypeKeys.JpegPhotoExtension);
                patient.Extensions.Add(new EntityExtension(ExtensionTypeKeys.JpegPhotoExtension, resource.Photo.First().Data));
            }

            return(patient);
        }
Exemple #28
0
        private static string OtherDatabaseTypesToDb2(string dataType, DatabaseColumn column)
        {
            //string types
            if (DataTypeConverter.IsFixedLengthString(dataType))
            {
                return("CHAR");
            }
            if (DataTypeConverter.IsLongString(dataType))
            {
                return(dataType == "CLOB" ? "CLOB" : "DBCLOB");
            }
            if (DataTypeConverter.IsVariableString(dataType))
            {
                if (column.Length == -1)
                {
                    return("DBCLOB");
                }
                return("VARCHAR");
            }

            //numeric types
            if (dataType == "SMALLINT")
            {
                return(dataType);
            }
            if (dataType == "BIGINT")
            {
                return(dataType);
            }
            if (dataType == "INTEGER")
            {
                return(dataType);
            }

            if (dataType == "INT")
            {
                return("INTEGER");
            }
            if (dataType == "NUM")
            {
                return("NUMERIC");                   //DB2 alias
            }
            if (dataType == "DEC")
            {
                return("DECIMAL");                   //DB2 alias
            }
            if (dataType == "MONEY")
            {
                return("DECIMAL(19,4)");
            }
            if (dataType == "BIT")
            {
                return("SMALLINT");                   //could be CHAR(1) but nicer with an integer
            }
            if (dataType == "NUMBER")
            {
                return(DataTypeConverter.OracleNumberConversion(column.Precision, column.Scale));
            }

            //date times
            //SqlServer Timestamp is a binary
            if (DataTypeConverter.IsSqlServerTimestamp(dataType, column))
            {
                return("GRAPHIC");
            }

            if (DataTypeConverter.IsDateTime(dataType))
            {
                return("TIMESTAMP");
            }

            //bytes
            if (DataTypeConverter.IsBlob(dataType, column.Length))
            {
                return("BLOB");
            }
            if (DataTypeConverter.IsBinary(dataType))
            {
                if (dataType == "LONG VARGRAPHIC")
                {
                    return(dataType);
                }
                if (dataType == "GRAPHIC")
                {
                    return(dataType);
                }
                return("VARGRAPHIC");
            }

            //other types
            if (dataType == "XMLTYPE")
            {
                return("XML");
            }
            if (dataType == "UNIQUEIDENTIFIER")
            {
                return("CHAR(16) FOR BIT DATA");
            }
            return(dataType);
        }
        /// <summary>
        /// Maps a FHIR <see cref="Medication"/> to a <see cref="ManufacturedMaterial"/> instance.
        /// </summary>
        /// <param name="resource">The model resource to be mapped</param>
        /// <returns>Returns the mapped <see cref="ManufacturedMaterial"/> instance.</returns>
        protected override ManufacturedMaterial MapToModel(Medication resource)
        {
            ManufacturedMaterial manufacturedMaterial;

            if (Guid.TryParse(resource.Id, out var key))
            {
                manufacturedMaterial = this.m_repository.Get(key) ?? new ManufacturedMaterial
                {
                    Key = key
                };
            }
            else
            {
                manufacturedMaterial = new ManufacturedMaterial
                {
                    Key = Guid.NewGuid()
                };
            }

            manufacturedMaterial.Identifiers = resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier).ToList();
            manufacturedMaterial.TypeConcept = DataTypeConverter.ToConcept(resource.Code?.Coding?.FirstOrDefault(), "http://snomed.info/sct");

            switch (resource.Status)
            {
            case Medication.MedicationStatusCodes.Active:
                manufacturedMaterial.StatusConceptKey = StatusKeys.Active;
                break;

            case Medication.MedicationStatusCodes.Inactive:
                manufacturedMaterial.StatusConceptKey = StatusKeys.Obsolete;
                break;

            case Medication.MedicationStatusCodes.EnteredInError:
                manufacturedMaterial.StatusConceptKey = StatusKeys.Nullified;
                break;
            }

            manufacturedMaterial.LotNumber  = resource.Batch?.LotNumber;
            manufacturedMaterial.ExpiryDate = DataTypeConverter.ToDateTimeOffset(resource.Batch?.ExpirationDateElement)?.DateTime;

            if (resource.Manufacturer != null)
            {
                manufacturedMaterial.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.ManufacturedProduct, DataTypeConverter.ResolveEntity <Core.Model.Entities.Organization>(resource.Manufacturer, resource)));
            }

            return(manufacturedMaterial);
        }
Exemple #30
0
        /// <summary>
        /// Maps the specified act to an adverse event
        /// </summary>
        protected override AdverseEvent MapToFhir(Act model, RestOperationContext restOperationContext)
        {
            var retVal = DataTypeConverter.CreateResource <AdverseEvent>(model);

            retVal.Identifier = DataTypeConverter.ToFhirIdentifier <Act>(model.Identifiers.FirstOrDefault());
            retVal.Category   = AdverseEventCategory.AdverseEvent;
            retVal.Type       = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("TypeConcept"));

            var recordTarget = model.LoadCollection <ActParticipation>("Participations").FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.RecordTarget);

            if (recordTarget != null)
            {
                retVal.Subject = DataTypeConverter.CreateReference <Patient>(recordTarget.LoadProperty <Entity>("PlayerEntity"), restOperationContext);
            }

            // Main topic of the concern
            var subject = model.LoadCollection <ActRelationship>("Relationships").FirstOrDefault(o => o.RelationshipTypeKey == ActRelationshipTypeKeys.HasSubject)?.LoadProperty <Act>("TargetAct");

            if (subject == null)
            {
                throw new InvalidOperationException("This act does not appear to be an adverse event");
            }
            retVal.Date = subject.ActTime.DateTime;

            // Reactions = HasManifestation
            var reactions = subject.LoadCollection <ActRelationship>("Relationships").Where(o => o.RelationshipTypeKey == ActRelationshipTypeKeys.HasManifestation);

            retVal.Reaction = reactions.Select(o => DataTypeConverter.CreateReference <Condition>(o.LoadProperty <Act>("TargetAct"), restOperationContext)).ToList();

            var location = model.LoadCollection <ActParticipation>("Participations").FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.Location);

            if (location != null)
            {
                retVal.Location = DataTypeConverter.CreateReference <Location>(location.LoadProperty <Entity>("PlayerEntity"), restOperationContext);
            }

            // Severity
            var severity = subject.LoadCollection <ActRelationship>("Relationships").First(o => o.RelationshipTypeKey == ActRelationshipTypeKeys.HasComponent && o.LoadProperty <Act>("TargetAct").TypeConceptKey == ObservationTypeKeys.Severity);

            if (severity != null)
            {
                retVal.Seriousness = DataTypeConverter.ToFhirCodeableConcept(severity.LoadProperty <CodedObservation>("TargetAct").Value, "http://hl7.org/fhir/adverse-event-seriousness");
            }

            // Did the patient die?
            var causeOfDeath = model.LoadCollection <ActRelationship>("Relationships").FirstOrDefault(o => o.RelationshipTypeKey == ActRelationshipTypeKeys.IsCauseOf && o.LoadProperty <Act>("TargetAct").TypeConceptKey == ObservationTypeKeys.ClinicalState && (o.TargetAct as CodedObservation)?.ValueKey == Guid.Parse("6df3720b-857f-4ba2-826f-b7f1d3c3adbb"));

            if (causeOfDeath != null)
            {
                retVal.Outcome = new SanteDB.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/adverse-event-outcome"), "fatal");
            }
            else if (model.StatusConceptKey == StatusKeys.Active)
            {
                retVal.Outcome = new SanteDB.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/adverse-event-outcome"), "ongoing");
            }
            else if (model.StatusConceptKey == StatusKeys.Completed)
            {
                retVal.Outcome = new SanteDB.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/adverse-event-outcome"), "resolved");
            }

            var author = model.LoadCollection <ActParticipation>("Participations").FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.Authororiginator);

            if (author != null)
            {
                retVal.Recorder = DataTypeConverter.CreatePlainReference <Practitioner>(author.LoadProperty <Entity>("PlayerEntity"), restOperationContext);
            }

            // Suspect entities
            var refersTo = model.LoadCollection <ActRelationship>("Relationships").Where(o => o.RelationshipTypeKey == ActRelationshipTypeKeys.RefersTo);

            if (refersTo.Count() > 0)
            {
                retVal.SuspectEntity = refersTo.Select(o => o.LoadProperty <Act>("TargetAct")).OfType <SubstanceAdministration>().Select(o =>
                {
                    var consumable = o.LoadCollection <ActParticipation>("Participations").FirstOrDefault(x => x.ParticipationRoleKey == ActParticipationKey.Consumable)?.LoadProperty <ManufacturedMaterial>("PlayerEntity");
                    if (consumable == null)
                    {
                        var product = o.LoadCollection <ActParticipation>("Participations").FirstOrDefault(x => x.ParticipationRoleKey == ActParticipationKey.Product)?.LoadProperty <Material>("PlayerEntity");
                        return(new AdverseEventSuspectEntity()
                        {
                            Instance = DataTypeConverter.CreatePlainReference <Substance>(product, restOperationContext)
                        });
                    }
                    else
                    {
                        return new AdverseEventSuspectEntity()
                        {
                            Instance = DataTypeConverter.CreatePlainReference <Medication>(consumable, restOperationContext)
                        }
                    };
                }).ToList();
            }

            return(retVal);
        }
 public AutoStructureSchemaBuilder()
 {
     DataTypeConverter = new DataTypeConverter();
 }
Exemple #32
0
        /// <summary>
        /// Map the incoming FHIR resource to a MODEL resource
        /// </summary>
        /// <param name="resource">The resource to be mapped</param>
        /// <returns></returns>
        protected override Place MapToModel(Location resource)
        {
            Place place = null;

            if (Guid.TryParse(resource.Id, out Guid key))
            {
                place = this.m_repository.Get(key);

                if (place == null)
                {
                    place = new Place
                    {
                        Key = key
                    };
                }
            }
            else if (resource.Identifier.Any())
            {
                foreach (var ii in resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier))
                {
                    if (ii.LoadProperty(o => o.Authority).IsUnique)
                    {
                        place = this.m_repository.Find(o => o.Identifiers.Where(i => i.AuthorityKey == ii.AuthorityKey).Any(i => i.Value == ii.Value)).FirstOrDefault();
                    }
                    if (place != null)
                    {
                        break;
                    }
                }

                if (place == null)
                {
                    place = new Place
                    {
                        Key = Guid.NewGuid()
                    };
                }
            }
            else
            {
                place = new Place
                {
                    Key = Guid.NewGuid()
                };
            }

            switch (resource.Status)
            {
            case Location.LocationStatus.Active:
                place.StatusConceptKey = StatusKeys.Active;
                break;

            case Location.LocationStatus.Suspended:
                throw new NotSupportedException(this.m_localizationService.GetString("error.type.NotSupportedException"));

            case Location.LocationStatus.Inactive:
                place.StatusConceptKey = StatusKeys.Inactive;
                break;
            }

            // add the textual representation of the name of the place as the address text property for search purposes
            // see the BirthPlaceExtension class
            if (!string.IsNullOrEmpty(resource.Address?.Text))
            {
                place.Names.Add(new EntityName(NameUseKeys.Search, resource.Address.Text));
            }

            place.Names.Add(new EntityName(NameUseKeys.OfficialRecord, resource.Name));
            place.Names.AddRange(resource.Alias.Select(o => new EntityName(NameUseKeys.Pseudonym, o)));

            if (resource.Mode == Location.LocationMode.Kind)
            {
                place.DeterminerConceptKey = DeterminerKeys.Described;
            }
            else
            {
                place.DeterminerConceptKey = DeterminerKeys.Specific;
            }

            place.TypeConcept = DataTypeConverter.ToConcept(resource.Type.FirstOrDefault());
            place.Telecoms    = resource.Telecom.Select(DataTypeConverter.ToEntityTelecomAddress).OfType <EntityTelecomAddress>().ToList();
            place.Identifiers = resource.Identifier.Select(DataTypeConverter.ToEntityIdentifier).ToList();

            if (resource.Address != null)
            {
                place.Addresses = new List <EntityAddress>()
                {
                    DataTypeConverter.ToEntityAddress(resource.Address)
                }
            }
            ;


            if (resource.Position != null)
            {
                place.GeoTag = new GeoTag
                {
                    Lat = (double)resource.Position.Latitude,
                    Lng = (double)resource.Position.Longitude
                };
            }

            if (resource.PartOf != null)
            {
                var reference = DataTypeConverter.ResolveEntity <Place>(resource.PartOf, resource);
                if (reference == null)
                {
                    this.m_tracer.TraceError($"Could not resolve {resource.PartOf.Reference}");
                    throw new KeyNotFoundException(m_localizationService.FormatString("error.type.KeyNotFoundException.couldNotResolve", new
                    {
                        param = resource.PartOf.Reference
                    }));
                }

                // point the child place entity at the target place entity with a relationship of parent
                place.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Parent, reference));
            }

            return(place);
        }