Beispiel #1
0
        /// <summary>
        /// Send specified audit
        /// </summary>
        public static void SendAudit(AuditData audit)
        {
            traceSource.TraceVerbose("Sending Audit - {0}", audit.CorrelationToken);

            ApplicationContext.Current.GetService <IThreadPoolService>().QueueUserWorkItem(o =>
            {
                AuthenticationContext.Current = new AuthenticationContext(AuthenticationContext.SystemPrincipal);
                // Translate codes to DICOM
                if (audit.EventTypeCode != null)
                {
                    IConceptRepositoryService icpcr = ApplicationContext.Current.GetService <IConceptRepositoryService>();
                    var concept = icpcr.GetConcept(audit.EventTypeCode.Code);
                    if (concept != null)
                    {
                        var refTerm = icpcr.GetConceptReferenceTerm(concept.Key.Value, "DCM");
                        if (refTerm != null)
                        {
                            audit.EventTypeCode = new AuditCode(refTerm.Mnemonic, "DCM")
                            {
                                DisplayName = refTerm.LoadCollection <ReferenceTermName>("DisplayNames")?.FirstOrDefault()?.Name
                            }
                        }
                        ;
                        else
                        {
                            audit.EventTypeCode.DisplayName = concept.LoadCollection <ConceptName>("ConceptNames").FirstOrDefault()?.Name;
                        }
                    }
                    traceSource.TraceVerbose("Mapped Audit Type Code - {0}-{1}-{2}", audit.EventTypeCode.CodeSystem, audit.EventTypeCode.Code, audit.EventTypeCode.DisplayName);
                }

                ApplicationContext.Current.GetService <IAuditorService>()?.SendAudit(audit);
            });
        }
Beispiel #2
0
        /// <summary>
        /// Create a care plan
        /// </summary>
        public Object Create(Object data, bool updateIfExists)
        {
            (data as Bundle)?.Reconstitute();
            data = (data as CarePlan)?.Target ?? data as Patient;
            if (data == null)
            {
                this.m_tracer.TraceError("Careplan requires a patient or bundle containing a patient entry");
                throw new InvalidOperationException(this.m_localizationService.GetString("error.rest.hdsi.careplanRequiresPatient"));
            }

            // Get care plan service
            var carePlanner = ApplicationServiceContext.Current.GetService <ICarePlanService>();
            var plan        = carePlanner.CreateCarePlan(data as Patient,
                                                         RestOperationContext.Current.IncomingRequest.QueryString["_asEncounters"] == "true",
                                                         RestOperationContext.Current.IncomingRequest.QueryString.ToQuery().ToDictionary(o => o.Key, o => (Object)o.Value));

            // Expand the participation roles form the care planner
            IConceptRepositoryService conceptService = ApplicationServiceContext.Current.GetService <IConceptRepositoryService>();

            foreach (var p in plan.Action)
            {
                p.Participations.ForEach(o => o.ParticipationRoleKey = o.ParticipationRoleKey ?? conceptService.GetConcept(o.ParticipationRole?.Mnemonic).Key);
            }
            return(Bundle.CreateBundle(plan));
        }
#pragma warning restore CS0067

        /// <summary>
        /// Create new audit repository service
        /// </summary>
        public AdoAuditRepositoryService(IConfigurationManager configurationManager,
                                         IDataCachingService dataCachingService,
                                         IBiMetadataRepository biMetadataRepository,
                                         IConceptRepositoryService conceptRepository,
                                         IAdhocCacheService adhocCacheService = null)
        {
            this.m_configuration      = configurationManager.GetSection <AdoAuditConfigurationSection>();
            this.m_adhocCache         = adhocCacheService;
            this.m_dataCachingService = dataCachingService;
            this.m_conceptRepository  = conceptRepository;

            try
            {
                this.m_configuration.Provider.UpgradeSchema("SanteDB.Persistence.Audit.ADO");

                ApplicationServiceContext.Current.Started += (o, e) =>
                {
                    using (AuthenticationContext.EnterSystemContext())
                    {
                        // Add audits as a BI data source
                        biMetadataRepository
                        .Insert(new BiDataSourceDefinition()
                        {
                            IsSystemObject   = true,
                            ConnectionString = this.m_configuration.ReadonlyConnectionString,
                            MetaData         = new BiMetadata()
                            {
                                Version = typeof(AdoAuditRepositoryService).Assembly.GetName().Version.ToString(),
                                Status  = BiDefinitionStatus.Active,
                                Demands = new List <string>()
                                {
                                    PermissionPolicyIdentifiers.AccessAuditLog
                                }
                            },
                            Id           = "org.santedb.bi.dataSource.audit",
                            Name         = "audit",
                            ProviderType = typeof(OrmBiDataProvider)
                        });
                    }
                };

                this.m_mapper  = new ModelMapper(typeof(AdoAuditRepositoryService).Assembly.GetManifestResourceStream("SanteDB.Persistence.Auditing.ADO.Data.Map.ModelMap.xml"));
                this.m_builder = new QueryBuilder(this.m_mapper, this.m_configuration.Provider);
            }
            catch (ModelMapValidationException e)
            {
                this.m_traceSource.TraceError("Error validing map: {0}", e.Message);
                foreach (var i in e.ValidationDetails)
                {
                    this.m_traceSource.TraceError("{0}:{1} @ {2}", i.Level, i.Message, i.Location);
                }
                throw;
            }
        }
        /// <summary>
        /// Gets a careplan by identifier
        /// </summary>
        public IdentifiedData Get(Guid id, Guid versionId)
        {
            Patient target      = ApplicationContext.Current.GetService <IRepositoryService <Patient> >().Get(id);
            var     carePlanner = ApplicationContext.Current.GetService <ICarePlanService>();
            var     plan        = carePlanner.CreateCarePlan(target,
                                                             WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["_asEncounters"] == "true",
                                                             WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters.ToQuery().ToDictionary(o => o.Key, o => (Object)o.Value));
            IConceptRepositoryService conceptService = ApplicationContext.Current.GetService <IConceptRepositoryService>();

            foreach (var p in plan.Action)
            {
                p.Participations.ForEach(o => o.ParticipationRoleKey = o.ParticipationRoleKey ?? conceptService.GetConcept(o.ParticipationRole?.Mnemonic).Key);
            }
            return(plan);
        }
        /// <summary>
        /// Validate the claim being made
        /// </summary>
        public bool Validate(IPrincipal principal, String value)
        {
            IConceptRepositoryService conceptService = ApplicationServiceContext.Current.GetService <IConceptRepositoryService>();

            try
            {
                // TODO: Validate that the "value" comes from the configured POU domain

                return(true);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                throw;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Query for care plan objects... Constructs a care plan for all patients matching the specified query parameters
        /// </summary>
        /// TODO: Change this to actually query care plans
        public IEnumerable <Object> Query(NameValueCollection queryParameters, int offset, int count, out int totalCount)
        {
            var repositoryService = ApplicationServiceContext.Current.GetService <IRepositoryService <Patient> >();

            if (repositoryService == null)
            {
                this.m_tracer.TraceError("Could not find patient repository service");
                throw new InvalidOperationException(this.m_localizationService.GetString("error.type.InvalidOperation.missingPatientRepo"));
            }


            // Query
            var carePlanner = ApplicationServiceContext.Current.GetService <ICarePlanService>();

            Expression <Func <Patient, bool> > queryExpr = QueryExpressionParser.BuildLinqExpression <Patient>(queryParameters);
            List <String>         queryId  = null;
            IEnumerable <Patient> patients = null;

            if (queryParameters.TryGetValue("_queryId", out queryId) && repositoryService is IPersistableQueryRepositoryService <Patient> )
            {
                patients = (repositoryService as IPersistableQueryRepositoryService <Patient>).Find(queryExpr, offset, count, out totalCount, new Guid(queryId[0]));
            }
            else
            {
                patients = repositoryService.Find(queryExpr, offset, count, out totalCount);
            }

            // Create care plan for the patients
            IConceptRepositoryService conceptService = ApplicationServiceContext.Current.GetService <IConceptRepositoryService>();

            return(patients.Select(o =>
            {
                var plan = carePlanner.CreateCarePlan(o);
                foreach (var p in plan.Action)
                {
                    p.Participations.ForEach(x => x.ParticipationRoleKey = x.ParticipationRoleKey ?? conceptService.GetConcept(x.ParticipationRole?.Mnemonic).Key);
                }
                return plan;
            }));
        }
        /// <summary>
        /// Create a care plan
        /// </summary>
        public IdentifiedData Create(IdentifiedData data, bool updateIfExists)
        {
            (data as Bundle)?.Reconstitute();
            data = (data as CarePlan)?.Target ?? data as Patient;
            if (data == null)
            {
                throw new InvalidOperationException("Careplan requires a patient or bundle containing a patient entry");
            }

            // Get care plan service
            var carePlanner = ApplicationContext.Current.GetService <ICarePlanService>();
            var plan        = carePlanner.CreateCarePlan(data as Patient,
                                                         WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["_asEncounters"] == "true",
                                                         WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters.ToQuery().ToDictionary(o => o.Key, o => (Object)o.Value));

            // Expand the participation roles form the care planner
            IConceptRepositoryService conceptService = ApplicationContext.Current.GetService <IConceptRepositoryService>();

            foreach (var p in plan.Action)
            {
                p.Participations.ForEach(o => o.ParticipationRoleKey = o.ParticipationRoleKey ?? conceptService.GetConcept(o.ParticipationRole?.Mnemonic).Key);
            }
            return(Bundle.CreateBundle(plan));
        }
Beispiel #8
0
        /// <summary>
        /// Queue the sending of an audit
        /// </summary>
        /// <param name="state"></param>
        private void SendAuditAsync(object state)
        {
            using (AuthenticationContext.EnterSystemContext())
            {
                try
                {
                    var ad = state as SdbAudit.AuditData;

                    // Translate codes to DICOM
                    if (ad.EventTypeCode != null)
                    {
                        IConceptRepositoryService icpcr = ApplicationServiceContext.Current.GetService <IConceptRepositoryService>();
                        var concept = icpcr?.GetConcept(ad.EventTypeCode.Code);
                        if (concept != null)
                        {
                            var refTerm = icpcr.GetConceptReferenceTerm(concept.Key.Value, "DCM");
                            if (refTerm != null)
                            {
                                ad.EventTypeCode = new AuditCode(refTerm.Mnemonic, "DCM")
                                {
                                    DisplayName = refTerm.LoadCollection <ReferenceTermName>("DisplayNames")?.FirstOrDefault()?.Name
                                }
                            }
                            ;
                            else
                            {
                                ad.EventTypeCode.DisplayName = concept.LoadCollection <ConceptName>("ConceptNames").FirstOrDefault()?.Name;
                            }
                        }
                        this.m_tracer.TraceVerbose("Mapped Audit Type Code - {0}-{1}-{2}", ad.EventTypeCode.CodeSystem, ad.EventTypeCode.Code, ad.EventTypeCode.DisplayName);
                    }

                    // Create the audit basic
                    AuditMessage am = new AuditMessage(
                        ad.Timestamp.DateTime, (AtnaApi.Model.ActionType)Enum.Parse(typeof(AtnaApi.Model.ActionType), ad.ActionCode.ToString()),
                        (AtnaApi.Model.OutcomeIndicator)Enum.Parse(typeof(AtnaApi.Model.OutcomeIndicator), ad.Outcome.ToString()),
                        (AtnaApi.Model.EventIdentifierType)Enum.Parse(typeof(AtnaApi.Model.EventIdentifierType), ad.EventIdentifier.ToString()),
                        null
                        );
                    if (ad.EventTypeCode != null)
                    {
                        am.EventIdentification.EventType.Add(new CodeValue <String>(ad.EventTypeCode.Code, ad.EventTypeCode.CodeSystem)
                        {
                            DisplayName = ad.EventTypeCode.DisplayName
                        });
                    }

                    am.SourceIdentification.Add(new AuditSourceIdentificationType()
                    {
                        AuditEnterpriseSiteID = ad.Metadata.FirstOrDefault(o => o.Key == SdbAudit.AuditMetadataKey.EnterpriseSiteID)?.Value ?? this.m_configuration.EnterpriseSiteId,
                        AuditSourceID         = ad.Metadata.FirstOrDefault(o => o.Key == SdbAudit.AuditMetadataKey.AuditSourceID)?.Value ?? Dns.GetHostName(),
                        AuditSourceTypeCode   = new List <CodeValue <AtnaApi.Model.AuditSourceType> >()
                        {
                            new CodeValue <AtnaApi.Model.AuditSourceType>(
                                (AtnaApi.Model.AuditSourceType)Enum.Parse(typeof(AtnaApi.Model.AuditSourceType), ad.Metadata.FirstOrDefault(o => o.Key == SdbAudit.AuditMetadataKey.AuditSourceType)?.Value ?? "ApplicationServerProcess"))
                        }
                    });

                    // Add additional data like the participant
                    bool   thisFound = false;
                    string dnsName   = Dns.GetHostName();
                    foreach (var adActor in ad.Actors)
                    {
                        thisFound |= (adActor.NetworkAccessPointId == Environment.MachineName || adActor.NetworkAccessPointId == dnsName) &&
                                     adActor.NetworkAccessPointType == SdbAudit.NetworkAccessPointType.MachineName;
                        var act = new AtnaApi.Model.AuditActorData()
                        {
                            NetworkAccessPointId            = adActor.NetworkAccessPointId,
                            NetworkAccessPointType          = (AtnaApi.Model.NetworkAccessPointType)Enum.Parse(typeof(AtnaApi.Model.NetworkAccessPointType), adActor.NetworkAccessPointType.ToString()),
                            NetworkAccessPointTypeSpecified = adActor.NetworkAccessPointType != 0,
                            UserIdentifier    = adActor.UserIdentifier,
                            UserIsRequestor   = adActor.UserIsRequestor,
                            UserName          = adActor.UserName,
                            AlternativeUserId = adActor.AlternativeUserId
                        };

                        if (adActor.ActorRoleCode != null)
                        {
                            foreach (var rol in adActor.ActorRoleCode)
                            {
                                act.ActorRoleCode.Add(new CodeValue <string>(rol.Code, rol.CodeSystem)
                                {
                                    DisplayName = rol.DisplayName
                                });
                            }
                        }
                        am.Actors.Add(act);
                    }

                    foreach (var aoPtctpt in ad.AuditableObjects)
                    {
                        var atnaAo = new AtnaApi.Model.AuditableObject()
                        {
                            IDTypeCode = aoPtctpt.IDTypeCode.HasValue && aoPtctpt.IDTypeCode != SdbAudit.AuditableObjectIdType.NotSpecified ?
                                         aoPtctpt.IDTypeCode.Value != SdbAudit.AuditableObjectIdType.Custom ?
                                         new CodeValue <AtnaApi.Model.AuditableObjectIdType>((AtnaApi.Model.AuditableObjectIdType)Enum.Parse(typeof(AtnaApi.Model.AuditableObjectIdType), aoPtctpt?.IDTypeCode?.ToString())) :
                                         (aoPtctpt.CustomIdTypeCode != null ?
                                          new CodeValue <AtnaApi.Model.AuditableObjectIdType>()
                            {
                                Code = aoPtctpt.CustomIdTypeCode?.Code,
                                CodeSystem = aoPtctpt.CustomIdTypeCode?.CodeSystem,
                                DisplayName = aoPtctpt.CustomIdTypeCode?.DisplayName
                            } : null) :
                                         null,
                            LifecycleType          = aoPtctpt.LifecycleType != SdbAudit.AuditableObjectLifecycle.NotSet && aoPtctpt.LifecycleType.HasValue ? (AtnaApi.Model.AuditableObjectLifecycle)Enum.Parse(typeof(AtnaApi.Model.AuditableObjectLifecycle), aoPtctpt.LifecycleType.ToString()) : 0,
                            LifecycleTypeSpecified = aoPtctpt.LifecycleType != SdbAudit.AuditableObjectLifecycle.NotSet && aoPtctpt.LifecycleType.HasValue,
                            ObjectId         = aoPtctpt.ObjectId,
                            Role             = aoPtctpt.Role.HasValue ? (AtnaApi.Model.AuditableObjectRole)Enum.Parse(typeof(AtnaApi.Model.AuditableObjectRole), aoPtctpt.Role.ToString()) : 0,
                            RoleSpecified    = aoPtctpt.Role != 0,
                            Type             = aoPtctpt.Type == SdbAudit.AuditableObjectType.NotSpecified ? AtnaApi.Model.AuditableObjectType.Other : (AtnaApi.Model.AuditableObjectType)Enum.Parse(typeof(AtnaApi.Model.AuditableObjectType), aoPtctpt.Type.ToString()),
                            TypeSpecified    = aoPtctpt.Type != SdbAudit.AuditableObjectType.NotSpecified,
                            ObjectSpec       = aoPtctpt.QueryData ?? aoPtctpt.NameData,
                            ObjectSpecChoice = aoPtctpt.QueryData == null ? ObjectDataChoiceType.ParticipantObjectName : ObjectDataChoiceType.ParticipantObjectQuery
                        };
                        // TODO: Object Data
                        foreach (var kv in aoPtctpt.ObjectData)
                        {
                            if (!String.IsNullOrEmpty(kv.Key))
                            {
                                atnaAo.ObjectDetail.Add(new ObjectDetailType()
                                {
                                    Type  = kv.Key,
                                    Value = kv.Value
                                });
                            }
                        }
                        am.AuditableObjects.Add(atnaAo);
                    }

                    // Send the message
                    this.m_tracer.TraceVerbose("Dispatching audit {0} via SYSLOG", ad.Key);
                    this.m_transporter.SendMessage(am);
                }
                catch (Exception e)
                {
                    this.m_tracer.TraceError(e.ToString());
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConceptReferenceTermResourceHandler"/> class.
 /// </summary>
 public ConceptReferenceTermResourceHandler()
 {
     ApplicationContext.Current.Started += (o, e) => { this.repository = ApplicationContext.Current.GetService <IConceptRepositoryService>(); };
 }
Beispiel #10
0
        /// <summary>
        /// Maps the organizations.
        /// </summary>
        /// <param name="csdOrganizations">The CSD organizations.</param>
        /// <returns>Returns a list of organizations.</returns>
        private static IEnumerable <Entity> MapOrganizations(IEnumerable <organization> csdOrganizations, CsdOptions options)
        {
            var organizations = new List <Entity>();
            IConceptRepositoryService icpr = ApplicationContext.Current.GetService <IConceptRepositoryService>();

            var idx = 0;

            foreach (var csdOrganization in csdOrganizations)
            {
                Entity importItem = null;
                if (!options.OrganizationsAsPlaces)
                {
                    importItem = GetOrCreateEntity <Organization>(csdOrganization.entityID, options.EntityUidAuthority, options);
                }
                else
                {
                    importItem = GetOrCreateEntity <Place>(csdOrganization.entityID, options.EntityUidAuthority, options);
                    // Set proper class code for the place
                    importItem.ClassConceptKey = EntityClassKeys.Place;
                }

                // addresses
                if (csdOrganization.address?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization addresses...");

                    var addresses = ReconcileVersionedAssociations(importItem.Addresses, csdOrganization.address?.Select(a => MapEntityAddress(a, new Uri(AddressTypeCodeSystem)))).Cast <EntityAddress>();

                    importItem.Addresses.AddRange(addresses);
                }

                // If organization as place
                if (options.OrganizationsAsPlaces)  // Import village hiearchy as address
                {
                    importItem.Addresses = new List <EntityAddress>()
                    {
                        TraversePlaceHeirarchyAsAddress(csdOrganization, csdOrganizations)
                    };
                }

                // map type concept
                if (csdOrganization.codedType?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization type concept...");

                    // we don't support multiple specialties for a organization at the moment, so we only take the first one
                    // TODO: cleanup
                    var typeConcept = MapCodedType(csdOrganization.codedType[0].code, csdOrganization.codedType[0].codingScheme);
                    importItem.TypeConceptKey = typeConcept?.Key;

                    // We now need to create the proper class concept key
                    Guid classKey = Guid.Empty;
                    if (typeConcept != null && !m_classCodeTypeMaps.TryGetValue(typeConcept.Key.Value, out classKey))
                    {
                        // Look for a relationship in the EntityClass
                        var adptConcept = icpr.FindConcepts(o => o.Relationship.Any(r => r.SourceEntityKey == typeConcept.Key) && o.ConceptSets.Any(s => s.Key == ConceptSetKeys.EntityClass)).FirstOrDefault();
                        if (adptConcept != null)
                        {
                            importItem.ClassConceptKey = adptConcept.Key;
                        }
                        else if (adptConcept == null && typeConcept.ConceptSetsXml.Contains(ConceptSetKeys.EntityClass) ||
                                 icpr.FindConcepts(o => o.ConceptSets.Any(c => c.Key == ConceptSetKeys.EntityClass) && o.Key == typeConcept.Key).Any())
                        {
                            importItem.ClassConceptKey = typeConcept.Key;
                        }

                        if (importItem.ClassConceptKey.HasValue)
                        {
                            m_classCodeTypeMaps.Add(typeConcept.Key.Value, importItem.ClassConceptKey.Value);
                        }
                        else
                        {
                            m_classCodeTypeMaps.Add(importItem.ClassConceptKey.Value, Guid.Empty);
                        }
                        classKey = importItem.ClassConceptKey ?? EntityClassKeys.Place;
                    }

                    importItem.ClassConceptKey = classKey;
                }

                // map specializations

                if (csdOrganization.specialization?.Any() == true && importItem is Organization)
                {
                    ShowInfoMessage("Mapping organization industry concept...");

                    // we don't support multiple industry values for a organization at the moment, so we only take the first one
                    // TODO: cleanup
                    (importItem as Organization).IndustryConceptKey = MapCodedType(csdOrganization.specialization[0].code, csdOrganization.specialization[0].codingScheme)?.Key;
                }

                // map extensions
                if (csdOrganization.extension?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization extensions...");

                    var extensions = ReconcileVersionedAssociations(importItem.Extensions, csdOrganization.extension.Select(e => MapEntityExtension(e.urn, e.Any.InnerText))).Cast <EntityExtension>();

                    importItem.Extensions.AddRange(extensions);
                }

                // map identifiers
                if (csdOrganization.otherID?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization identifiers...");

                    var identifiers = ReconcileVersionedAssociations(importItem.Identifiers, csdOrganization.otherID.Select(MapEntityIdentifier)).Cast <EntityIdentifier>();

                    importItem.Identifiers.AddRange(identifiers);
                }

                Entity parent = null;

                // map parent relationships
                if (csdOrganization.parent?.entityID != null)
                {
                    ShowInfoMessage("Mapping organization parent relationships...");

                    importItem.Relationships.RemoveAll(r => r.RelationshipTypeKey == EntityRelationshipTypeKeys.Parent);

                    if (!options.OrganizationsAsPlaces)
                    {
                        parent = GetOrCreateEntity <Organization>(csdOrganization.parent.entityID, options.EntityUidAuthority, options);
                    }
                    else
                    {
                        parent = GetOrCreateEntity <Place>(csdOrganization.parent.entityID, options.EntityUidAuthority, options);
                    }

                    importItem.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Parent, parent));
                }

                // map primary name
                if (csdOrganization.primaryName != null)
                {
                    ShowInfoMessage("Mapping organization names...");

                    importItem.Names.RemoveAll(c => c.NameUseKey == NameUseKeys.OfficialRecord);
                    importItem.Names.Add(new EntityName(NameUseKeys.OfficialRecord, csdOrganization.primaryName));
                }

                // map names
                if (csdOrganization.otherName?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization additional names...");

                    var names = ReconcileVersionedAssociations(importItem.Names, csdOrganization.otherName.Select(c => MapEntityNameOrganization(NameUseKeys.Assigned, c))).Cast <EntityName>();

                    importItem.Names.AddRange(names);
                }

                // map tags
                if (csdOrganization.record?.sourceDirectory != null)
                {
                    ShowInfoMessage("Mapping organization tags...");

                    importItem.Tags.RemoveAll(t => t.TagKey == "sourceDirectory");
                    importItem.Tags.Add(new EntityTag("sourceDirectory", csdOrganization.record.sourceDirectory));
                }

                // map contacts
                if (csdOrganization.contact?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization contact relationships...");

                    // HACK
                    importItem.Relationships.RemoveAll(r => r.RelationshipTypeKey == EntityRelationshipTypeKeys.Contact);
                    importItem.Relationships.AddRange(csdOrganization.contact.Select(o => MapEntityRelationshipOrganizationContact(o, options)));
                }

                // map contact points
                if (csdOrganization.contactPoint?.Any() == true)
                {
                    ShowInfoMessage("Mapping organization telecommunications...");

                    var telecoms = ReconcileVersionedAssociations(importItem.Telecoms, csdOrganization.contactPoint.Select(c => MapContactPoint(TelecomAddressUseKeys.Public, c))).Cast <EntityTelecomAddress>();

                    importItem.Telecoms.AddRange(telecoms);
                }

                // map status concept
                if (csdOrganization.record?.status != null)
                {
                    ShowInfoMessage("Mapping organization status...");

                    importItem.StatusConceptKey = MapStatusCode(csdOrganization.record.status, "http://openiz.org/csd/CSD-OrganizationStatusCodes");
                }

                organizations.Add(importItem);

                if (parent != null && organizations.Any(c => c.Identifiers.All(i => i.Value != csdOrganization.parent?.entityID)))
                {
                    organizations.Add(parent);
                }

                if (!entityMap.ContainsKey(csdOrganization.entityID))
                {
                    entityMap.Add(csdOrganization.entityID, importItem);
                }

                if (parent != null && !entityMap.ContainsKey(csdOrganization.parent?.entityID))
                {
                    entityMap.Add(csdOrganization.parent?.entityID, parent);
                }

                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine($"Mapped organization {(options.OrganizationsAsPlaces ? "as place" : "")} ({idx++}/{csdOrganizations.Count()}): {importItem.Key.Value} {string.Join(" ", importItem.Names.SelectMany(n => n.Component).Select(c => c.Value))}");
                Console.ResetColor();
            }

            return(organizations);
        }
Beispiel #11
0
        /// <summary>
        /// Traverses a place hierarchy as an address structure
        /// </summary>
        private static EntityAddress TraversePlaceHeirarchyAsAddress(organization importItem, IEnumerable <organization> context)
        {
            EntityAddress retVal = new EntityAddress()
            {
                AddressUseKey = AddressUseKeys.Direct
            };

            // First Census tract?
            var codeID = importItem.otherID.FirstOrDefault(o => o.code == "code");

            // Process components
            var parent = importItem;

            IConceptRepositoryService icpr = ApplicationContext.Current.GetService <IConceptRepositoryService>();

            while (parent != null)
            {
                EntityAddressComponent comp = new EntityAddressComponent();
                comp.Value = parent.primaryName;
                // Get the component type from CSD
                Concept codeType = null;
                foreach (var ct in parent.codedType)
                {
                    codeType = MapCodedType(ct.code, ct.codingScheme);
                    if (codeType != null)
                    {
                        break;
                    }
                }

                Guid addressCompKey = Guid.Empty;
                if (codeType != null && !m_addressCodeTypeMaps.TryGetValue(codeType.Key.Value, out addressCompKey))
                {
                    if (codeType != null)
                    {
                        // Look for a relationship in the AddressPartType
                        var adptConcept = icpr.FindConcepts(o => o.Relationship.Any(r => r.SourceEntityKey == codeType.Key) && o.ConceptSets.Any(s => s.Mnemonic == "AddressComponentType")).FirstOrDefault();
                        if (adptConcept != null)
                        {
                            comp.ComponentTypeKey = adptConcept.Key;
                        }
                    }
                    if (!comp.ComponentTypeKey.HasValue && codeType.ConceptSetsXml.Contains(ConceptSetKeys.AddressComponentType) ||
                        icpr.FindConcepts(o => o.ConceptSets.Any(c => c.Key == ConceptSetKeys.AddressComponentType) && o.Key == codeType.Key).Any())
                    {
                        comp.ComponentTypeKey = codeType.Key;
                    }

                    if (comp.ComponentTypeKey.HasValue)
                    {
                        m_addressCodeTypeMaps.Add(codeType.Key.Value, comp.ComponentTypeKey.Value);
                    }
                    else
                    {
                        m_addressCodeTypeMaps.Add(codeType.Key.Value, Guid.Empty);
                    }
                    addressCompKey = comp.ComponentTypeKey.GetValueOrDefault();
                }

                if (addressCompKey != Guid.Empty)
                {
                    comp.ComponentTypeKey = addressCompKey;
                }
                // Add
                if (comp.ComponentTypeKey.HasValue)
                {
                    retVal.Component.Add(comp);
                }

                // Get parent
                parent = context.FirstOrDefault(o => o.entityID == parent.parent?.entityID);
            }

            return(retVal);
        }