/// <summary> /// Create original identifier for a link /// </summary> private void CreateOriginalIdentifier(IDbConnection conn, IDbTransaction tx, decimal identifier, HealthServiceRecordSite healthServiceRecordSite, DomainIdentifier id) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { // Participant HealthcareParticipant paticipantComponent = healthServiceRecordSite.Component as HealthcareParticipant; cmd.CommandText = "add_link_hc_ptcpt_orig_id"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, identifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, paticipantComponent.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_cls_in", DbType.Decimal, (decimal)healthServiceRecordSite.SiteRoleType)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "orig_id_domain_in", DbType.StringFixedLength, id.Domain)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "orig_id_in", DbType.StringFixedLength, (object)id.Identifier ?? DBNull.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "license_ind_in", DbType.Boolean, id.IsLicenseAuthority)); // Insert cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } }
/// <summary> /// Depersist the /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, System.ComponentModel.IContainer container, SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType?role, bool loadFast) { // De-persist using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null)) { cmd.CommandText = "get_ext"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_id_in", DbType.Decimal, identifier)); using (IDataReader rdr = cmd.ExecuteReader()) if (rdr.Read()) { ExtendedAttribute ext = new ExtendedAttribute() { Id = Convert.ToDecimal(rdr["ext_id"]), Name = Convert.ToString(rdr["ext_name"]), PropertyPath = Convert.ToString(rdr["ext_path"]), ValueData = (byte[])rdr["ext_data"] }; // Sanity check if (ext.Value.GetType().AssemblyQualifiedName != Convert.ToString(rdr["ext_typ"])) { throw new ConstraintException(); } return(ext); } } return(null); }
/// <summary> /// Create a location /// </summary> private void CreateLocation(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, Place loc) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "crt_plc"; // Insert the code decimal?codeId = loc.LocationType != null ? (decimal?)DbUtil.CreateCodedValue(conn, tx, loc.LocationType) : null, addrSetId = loc.Address != null ? (decimal?)DbUtil.CreateAddressSet(conn, tx, loc.Address) : null; // parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_name_in", DbType.StringFixedLength, (object)loc.Name ?? DBNull.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_cls_cs_in", DbType.StringFixedLength, ((object)loc.Class ?? "PLC"))); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_addr_set_id_in", DbType.Decimal, (object)addrSetId ?? DBNull.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_typ_cd_id_in", DbType.Decimal, (object)codeId ?? DBNull.Value)); // Execute the parameter loc.Id = Convert.ToDecimal(cmd.ExecuteScalar()); // Register an alternate identifier if they exist foreach (var id in loc.AlternateIdentifiers) { CreateAlternateIdentifier(conn, tx, loc.Id, id); } } finally { cmd.Dispose(); } }
/// <summary> /// De-persist the MI /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, System.ComponentModel.IContainer container, HealthServiceRecordSiteRoleType?roleType, bool loadFast) { // De-persist the masking record ISystemConfigurationService sysConfig = ApplicationContext.ConfigurationService; // Load the observation event MaskingIndicator retVal = new MaskingIndicator(); using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null)) { cmd.CommandText = "get_psn_msk_ind"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "msk_id_in", DbType.Decimal, identifier)); // Execute the reader using (IDataReader rdr = cmd.ExecuteReader()) { if (rdr.Read()) { retVal.MaskingCode = new MARC.HI.EHRS.SVC.Core.DataTypes.CodeValue(Convert.ToString(rdr["msk_cs"])); } } // Append to the container if (container is Person) { (container as Person).Add(retVal, Guid.NewGuid().ToString(), MARC.HI.EHRS.SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType.FilterOf, null); } } return(retVal); }
/// <summary> /// Persist the data /// </summary> public SVC.Core.DataTypes.VersionedDomainIdentifier Persist(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, System.ComponentModel.IComponent data, bool isUpdate) { ExtendedAttribute instance = data as ExtendedAttribute; using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx)) { // persist cmd.CommandText = "crt_ext"; // parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_rep_in", DbType.String, "BIN")); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_typ_in", DbType.String, instance.Value.GetType().AssemblyQualifiedName)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_data_in", DbType.Binary, instance.ValueData)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_name_in", DbType.String, instance.Name)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ext_path_in", DbType.String, instance.PropertyPath)); // Create the response instance.Id = Convert.ToDecimal(cmd.ExecuteScalar()); } // Return constructed version pointer return(new SVC.Core.DataTypes.VersionedDomainIdentifier() { Identifier = instance.Id.ToString(), Domain = ApplicationContext.ConfigurationService.OidRegistrar.GetOid(ClientRegistryOids.EVENT_OID).Oid }); }
/// <summary> /// De-persist the portion /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, System.ComponentModel.IContainer container, SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType?role, bool loadFast) { using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null)) { cmd.CommandText = "get_dev"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "dev_id_in", DbType.Decimal, identifier)); // Execute reader using (IDataReader rdr = cmd.ExecuteReader()) if (rdr.Read()) { return new RepositoryDevice() { AlternateIdentifier = new SVC.Core.DataTypes.DomainIdentifier() { Identifier = Convert.ToString(rdr["dev_ext"]), Domain = Convert.ToString(rdr["dev_root"]) }, Jurisdiction = rdr["dev_jur"] != DBNull.Value ? Convert.ToString(rdr["dev_jur"]) : null, Name = rdr["dev_name"] != DBNull.Value ? Convert.ToString(rdr["dev_name"]) : null, Id = identifier } } ; } return(null); } #endregion }
/// <summary> /// Persist the MI /// </summary> public MARC.HI.EHRS.SVC.Core.DataTypes.VersionedDomainIdentifier Persist(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, System.ComponentModel.IComponent data, bool isUpdate) { // Masking indicator MaskingIndicator mi = data as MaskingIndicator; // Health service record event identifier that this MI applies to Person psnParent = mi.Site.Container as Person; // Is there an HSR parent that this masking indicator applies to? if (psnParent == null) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DBCF002")); } // Now to create the comment IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { // Call the create masking indicator function in DB cmd.CommandText = "crt_psn_msk_ind"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_id_in", DbType.Decimal, psnParent.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_vrsn_id_in", DbType.Decimal, psnParent.VersionId)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "msk_cs_in", DbType.String, mi.MaskingCode.Code)); return(new MARC.HI.EHRS.SVC.Core.DataTypes.VersionedDomainIdentifier() { Identifier = cmd.ExecuteScalar().ToString() }); } finally { cmd.Dispose(); } }
/// <summary> /// De-persist the component from the database /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, IContainer container, HealthServiceRecordSiteRoleType?roleType, bool loadFast) { Place retVal = new Place(); IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null); try { // Determine the container RegistrationEvent hsrParent = container as RegistrationEvent; retVal = GetLocation(conn, null, new DomainIdentifier() { Identifier = identifier.ToString() }); // Data reader if (hsrParent != null) { hsrParent.Add(retVal, Guid.NewGuid().ToString(), roleType.Value, retVal.AlternateIdentifiers); } else { container.Add(retVal); } } finally { cmd.Dispose(); } return(retVal); }
/// <summary> /// Persists the component /// </summary> public SVC.Core.DataTypes.VersionedDomainIdentifier Persist(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, System.ComponentModel.IComponent data, bool isUpdate) { RepositoryDevice device = data as RepositoryDevice; using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx)) { if (device.AlternateIdentifier == null || String.IsNullOrEmpty(device.AlternateIdentifier.Domain)) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DTPE009")); } // create parmaeters cmd.CommandText = "crt_dev"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "dev_root_in", DbType.String, device.AlternateIdentifier.Domain)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "dev_ext_in", DbType.String, String.IsNullOrEmpty(device.AlternateIdentifier.Identifier) ? DBNull.Value : (object)device.AlternateIdentifier.Identifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "dev_name_in", DbType.String, device.Name)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "dev_jur_in", DbType.String, device.Jurisdiction)); // Versioned domain identifier return(new SVC.Core.DataTypes.VersionedDomainIdentifier() { Identifier = Convert.ToString(cmd.ExecuteScalar()), Domain = ApplicationContext.ConfigurationService.OidRegistrar.GetOid(ClientRegistryOids.DEVICE_CRID).Oid }); } }
/// <summary> /// Get telecommunications addresses /// </summary> private IEnumerable <TelecommunicationsAddress> GetTelecomAddresses(IDbConnection conn, IDbTransaction tx, decimal identifier) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { List <TelecommunicationsAddress> retVal = new List <TelecommunicationsAddress>(); cmd.CommandText = "get_hc_ptcpt_tel"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, identifier)); IDataReader rdr = cmd.ExecuteReader(); try { while (rdr.Read()) { retVal.Add(new TelecommunicationsAddress() { Value = Convert.ToString(rdr["tel_value"]), Use = Convert.ToString(rdr["tel_use"]) }); } return(retVal); } finally { rdr.Close(); rdr.Dispose(); } } finally { cmd.Dispose(); } }
/// <summary> /// Get telecommunications addresses /// </summary> private IEnumerable <DomainIdentifier> GetAlternateIdentifiers(IDbConnection conn, IDbTransaction tx, decimal identifier) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { List <DomainIdentifier> retVal = new List <DomainIdentifier>(); cmd.CommandText = "get_ptcpt_alt_id"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, identifier)); IDataReader rdr = cmd.ExecuteReader(); try { while (rdr.Read()) { retVal.Add(new DomainIdentifier() { Domain = Convert.ToString(rdr["alt_id_domain"]), Identifier = Convert.ToString(rdr["alt_id"]) }); } return(retVal); } finally { rdr.Close(); rdr.Dispose(); } } finally { cmd.Dispose(); } }
/// <summary> /// Create a registration event version linking to the person reflecting a change /// </summary> private RegistrationEvent GetRegistrationEvent(IDbConnection conn, IDbTransaction tx, Person psn) { // First, get the registration version for the person id decimal regEvtVrsn = 0, regEvtId = 0; using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx)) { cmd.CommandText = "get_psn_hsr_evt"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_id", DbType.Decimal, psn.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_vrsn_id", DbType.Decimal, psn.VersionId)); // Get the registration version using (IDataReader rdr = cmd.ExecuteReader()) { if (!rdr.Read()) { throw new ConstraintException("Cannot determine the registration event"); } regEvtVrsn = Convert.ToDecimal(rdr["hsr_vrsn_id"]); regEvtId = Convert.ToDecimal(rdr["hsr_id"]); } } // Load and return return(new RegistrationEventPersister().DePersist(conn, regEvtId, regEvtVrsn, null, null, true) as RegistrationEvent); }
/// <summary> /// Returns true if the component has a current version /// </summary> private bool HasCurrentVersion(IDbConnection conn, IDbTransaction tx, decimal hsr_id) { // Get the current version IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); cmd.CommandText = "get_hsr_crnt_vrsn"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, hsr_id)); return(cmd.ExecuteScalar() != DBNull.Value); }
/// <summary> /// Create an HSR record /// </summary> private VersionedDomainIdentifier CreateHSRRecord(IDbConnection conn, IDbTransaction tx, ChangeSummary hsr) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); cmd.CommandText = "crt_hsr"; // Get the terminology service ISystemConfigurationService iscs = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService; // Parameters // classifier = 0x400 = Change Summary cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_cls_in", DbType.Decimal, RegistrationEventType.ComponentEvent | RegistrationEventType.Revise)); // event type code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "evt_typ_cd_id_in", DbType.Decimal, DbUtil.CreateCodedValue(conn, tx, hsr.ChangeType))); // refuted indicator cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "refuted_ind_in", DbType.Boolean, false)); decimal?efftTimeId = null; if (hsr.EffectiveTime != null) { efftTimeId = DbUtil.CreateTimeset(conn, tx, hsr.EffectiveTime); } cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "efft_ts_set_id_in", DbType.Decimal, efftTimeId == null ? (object)DBNull.Value : efftTimeId.Value)); // status code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "status_cs_in", DbType.Decimal, hsr.Status == null ? (object)DBNull.Value : (int)hsr.Status)); // authored time cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "aut_utc_in", DbType.DateTime, hsr.Timestamp == default(DateTime) ? (object)DBNull.Value : hsr.Timestamp)); // language code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lang_cs_in", DbType.String, hsr.LanguageCode)); // Execute the command IDataReader resultRdr = cmd.ExecuteReader(); try { // Create the return value VersionedDomainIdentifier id = new VersionedDomainIdentifier(); if (!resultRdr.Read()) { return(null); } id.Version = Convert.ToString(resultRdr["VRSN_ID"]); id.Identifier = Convert.ToString(resultRdr["ID"]); id.Domain = iscs.OidRegistrar.GetOid(ClientRegistryOids.EVENT_OID).Oid; return(id); } finally { resultRdr.Close(); } }
/// <summary> /// Link this HSR record to another /// </summary> private void LinkHSRRecord(IDbConnection conn, IDbTransaction tx, HealthServiceRecordComponentRef hsr) { // TODO: Check to ensure that we don't double replace or double succeed a record // An HSR can only be linked to another HSR, so ... // first we need to find the HSR container to link to IContainer hsrContainer = hsr.Site.Container; while (!(hsrContainer is RegistrationEvent) && hsrContainer != null) { hsrContainer = (hsrContainer as IComponent).Site.Container; } RegistrationEvent parentHsr = hsrContainer as RegistrationEvent; // Get the root container HealthServiceRecordContainer parentContainer = hsr.Site.Container as HealthServiceRecordContainer; while (parentContainer.Site != null) { parentContainer = parentContainer.Site.Container as HealthServiceRecordContainer; } // Now we want to link if (parentHsr == null) { throw new InvalidOperationException("Can only link a Health Service Record event to a Registration Event"); } else if (parentContainer.Id.Equals(hsr.Id)) { throw new InvalidOperationException("Can't link a record to itself"); } // Insert link IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "add_hsr_lnk"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "cmp_hsr_id_in", DbType.Decimal, hsr.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "cbc_hsr_id_in", DbType.Decimal, parentHsr.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lnk_cls_in", DbType.Decimal, (decimal)(hsr.Site as HealthServiceRecordSite).SiteRoleType)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "conduction_in", DbType.Boolean, (hsr.Site as HealthServiceRecordSite).ContextConduction)); cmd.ExecuteNonQuery(); } catch (Exception) { throw new ConstraintException(String.Format("Cannot locate referenced record for '{0}' relationship", (hsr.Site as HealthServiceRecordSite).SiteRoleType)); } finally { cmd.Dispose(); } }
/// <summary> /// Link this HSR record to another /// </summary> internal void LinkHSRRecord(IDbConnection conn, IDbTransaction tx, HealthServiceRecordContainer hsr) { // An HSR can only be linked to another HSR, so ... // first we need to find the HSR container to link to IContainer hsrContainer = hsr.Site.Container; while (!(hsrContainer is RegistrationEvent) && hsrContainer != null) { hsrContainer = (hsrContainer as IComponent).Site.Container; } RegistrationEvent parentHsr = hsrContainer as RegistrationEvent; // Now we want to link if (parentHsr == null) { throw new InvalidOperationException("Can only link an Health Service Record event to another Health Service Record Event"); } // Insert link IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "add_hsr_lnk"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "cmp_hsr_id_in", DbType.Decimal, hsr.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "cbc_hsr_id_in", DbType.Decimal, parentHsr.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lnk_cls_in", DbType.Decimal, (decimal)(hsr.Site as HealthServiceRecordSite).SiteRoleType)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "conduction_in", DbType.Boolean, (hsr.Site as HealthServiceRecordSite).ContextConduction)); try { cmd.ExecuteNonQuery(); } catch (DbException e) { throw new InvalidOperationException(string.Format("Cannot insert link between {0} and {1}. {2}", hsr.Id, parentHsr.Id, e.Message)); } } finally { cmd.Dispose(); } }
/// <summary> /// Link participant to a health service record /// </summary> private void LinkHealthServiceRecord(IDbConnection conn, IDbTransaction tx, decimal identifier, HealthServiceRecordSite healthServiceRecordSite) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "link_hc_ptcpt"; // Represented organization HealthcareParticipant paticipantComponent = healthServiceRecordSite.Component as HealthcareParticipant; var repOrganizations = from HealthServiceRecordComponent comp in paticipantComponent.Components where (comp.Site as HealthServiceRecordSite).SiteRoleType == HealthServiceRecordSiteRoleType.RepresentitiveOf select comp; HealthcareParticipant representedOrganization = repOrganizations.Count() > 0 ? repOrganizations.First() as HealthcareParticipant : null; if (representedOrganization != null) { representedOrganization.Id = Convert.ToDecimal(Persist(conn, tx, representedOrganization, false).Identifier); } // Parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, identifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, paticipantComponent.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_cls_in", DbType.Decimal, (decimal)healthServiceRecordSite.SiteRoleType)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_rep_org_id_in", DbType.Decimal, representedOrganization == null ? DBNull.Value : (object)representedOrganization.Id)); // Insert cmd.ExecuteNonQuery(); // Insert original identifiers if (healthServiceRecordSite.OriginalIdentifier != null) { foreach (var id in healthServiceRecordSite.OriginalIdentifier) { CreateOriginalIdentifier(conn, tx, identifier, healthServiceRecordSite, id); } } } finally { cmd.Dispose(); } }
/// <summary> /// Create an alternate identifier for the SDL /// </summary> private void CreateAlternateIdentifier(IDbConnection conn, IDbTransaction tx, decimal identifier, DomainIdentifier altId) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "crt_plc_alt_id"; // parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, identifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "alt_id_domain_in", DbType.StringFixedLength, altId.Domain)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "alt_id_in", DbType.StringFixedLength, (object)altId.Identifier ?? DBNull.Value)); // Execute cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } }
/// <summary> /// Link two clients together /// </summary> private decimal LinkClients(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, decimal source, decimal target, string kind, StatusType status) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "crt_psn_rltnshp"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "src_psn_id_in", DbType.Decimal, source)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "trg_psn_id_in", DbType.Decimal, target)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "status_cs_in", DbType.Decimal, (int)status)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "kind_in", DbType.StringFixedLength, kind)); // Insert return((decimal)cmd.ExecuteScalar()); } catch { throw; } finally { cmd.Dispose(); } }
/// <summary> /// Update location /// </summary> private void UpdateLocation(IDbConnection conn, IDbTransaction tx, Place loc) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "upd_plc"; // parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, loc.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_addr_set_id_in", DbType.Decimal, loc.Address == null ? DBNull.Value : (Object)DbUtil.CreateAddressSet(conn, tx, loc.Address))); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_typ_cd_id_in", DbType.Decimal, loc.LocationType == null ? DBNull.Value : (Object)DbUtil.CreateCodedValue(conn, tx, loc.LocationType))); // Execute cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } }
/// <summary> /// Link a service delivery location record to an HSR /// </summary> private void LinkHealthServiceRecord(IDbConnection conn, IDbTransaction tx, decimal hsrId, HealthServiceRecordSite loc) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "link_plc"; // Parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, hsrId)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, (loc.Component as Place).Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_cls_in", DbType.Decimal, (decimal)loc.SiteRoleType)); // Insert cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } }
/// <summary> /// Create a telecomm address /// </summary> private void CreateTelecommunicationsAddress(IDbConnection conn, IDbTransaction tx, TelecommunicationsAddress tel, decimal pId) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "add_hc_ptcpt_tel"; // Parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, pId)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "tel_value_in", DbType.String, tel.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "tel_use_in", DbType.String, tel.Use ?? "DIR")); // Now insert cmd.ExecuteNonQuery(); } catch (DataException) { } finally { cmd.Dispose(); } }
/// <summary> /// Create an HSR version /// </summary> private decimal CreateHSRVersion(IDbConnection conn, IDbTransaction tx, RegistrationEvent hsr) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { cmd.CommandText = "crt_hsr_vrsn"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, hsr.Id)); decimal?codeId = null; if (hsr.EventType != null) { codeId = DbUtil.CreateCodedValue(conn, tx, hsr.EventType); } cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "evt_typ_cd_id_in", DbType.Decimal, codeId.HasValue ? (object)codeId.Value : DBNull.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "refuted_ind_in", DbType.Boolean, hsr.Refuted)); // Effective time if needed decimal?hsrEfftTsId = null; if (hsr.EffectiveTime != null) { hsrEfftTsId = DbUtil.CreateTimeset(conn, tx, hsr.EffectiveTime); } // Parameters cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "efft_ts_set_id_in", DbType.Decimal, (object)hsrEfftTsId ?? DBNull.Value)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "status_cs_in", DbType.Decimal, hsr.Status == StatusType.Unknown ? (object)DBNull.Value : (int)hsr.Status)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "aut_utc_in", DbType.DateTime, hsr.Timestamp == default(DateTime) ? (object)DBNull.Value : hsr.Timestamp)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lang_cs_in", DbType.StringFixedLength, (object)hsr.LanguageCode ?? DBNull.Value)); return(Convert.ToDecimal(cmd.ExecuteScalar())); } finally { cmd.Dispose(); } }
/// <summary> /// Persist the person relationship /// </summary> public SVC.Core.DataTypes.VersionedDomainIdentifier Persist(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, System.ComponentModel.IComponent data, bool isUpdate) { // Is this a replacement var pp = new PersonPersister(); PersonRegistrationRef refr = data as PersonRegistrationRef; Person psn = pp.GetPerson(conn, tx, refr.AlternateIdentifiers[0], true); Person cntrPsn = data.Site.Container as Person; if (psn == null || cntrPsn == null) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DBCF00B")); } else if (psn.Id == cntrPsn.Id) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DBCF00D")); } // Load the container person from DB so we get all data Person dbCntrPsn = pp.GetPerson(conn, tx, new SVC.Core.DataTypes.DomainIdentifier() { Domain = ApplicationContext.ConfigurationService.OidRegistrar.GetOid(ClientRegistryOids.CLIENT_CRID).Oid, Identifier = cntrPsn.Id.ToString() }, true); pp.MergePersons(dbCntrPsn, cntrPsn); // Load the components for the person #if DEBUG Trace.TraceInformation("Registration reference {0} > {1}", psn.Id, dbCntrPsn.Id); #endif DbUtil.DePersistComponents(conn, psn, this, true); if (psn == null || dbCntrPsn == null) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DBCF00B")); } dbCntrPsn.Site = (data.Site.Container as IComponent).Site; var role = (refr.Site as HealthServiceRecordSite).SiteRoleType; var symbolic = (refr.Site as HealthServiceRecordSite).IsSymbolic; // If true, the replacement does not cascade and is a symbolic replacement of only the identifiers listed // Replacement? if (role == HealthServiceRecordSiteRoleType.ReplacementOf) { // First, we obsolete all records with the existing person foreach (var id in psn.AlternateIdentifiers.FindAll(o => refr.AlternateIdentifiers.Exists(a => a.Domain == o.Domain))) { id.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Remove; } //psn.AlternateIdentifiers.RemoveAll(o => o.UpdateMode != SVC.Core.DataTypes.UpdateModeType.Remove); // Not symbolic, means that we do a hard replace // Symbolic replace = Just replace the reference to that identifier // Hard replace = Merge the new and old record and then replace them if (!symbolic) { #if DEBUG Trace.TraceInformation("Performing an administrative migration of identifiers and information from {0} > {1}", psn.Id, dbCntrPsn.Id); #endif // Now to copy the components of the current version down //foreach (IComponent cmp in refr.Site.Container.Components) // if (cmp != refr) // dbCntrPsn.Add((cmp as HealthServiceRecordComponent).Clone() as IComponent); // Merge the two records in memory taking the newer data // This is a merge from old to new in order to capture any data elements // that have been updated in the old that might be newer (or more accurate) than the // the new if (psn.AlternateIdentifiers == null) { dbCntrPsn.AlternateIdentifiers = new List <SVC.Core.DataTypes.DomainIdentifier>(); } else if (psn.OtherIdentifiers == null) { dbCntrPsn.OtherIdentifiers = new List <KeyValuePair <SVC.Core.DataTypes.CodeValue, SVC.Core.DataTypes.DomainIdentifier> >(); } foreach (var id in psn.AlternateIdentifiers) { // Remove the identifier from the original id.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Remove; // If this is a duplicate id then don't add if (dbCntrPsn.AlternateIdentifiers.Exists(i => i.Domain == id.Domain && i.Identifier == id.Identifier)) { continue; } bool isPrivate = false; var oidData = ApplicationContext.ConfigurationService.OidRegistrar.FindData(id.Domain); if (oidData != null) { isPrivate = !(oidData.Attributes.Exists(o => o.Key == "IsMergeSurvivor") && Convert.ToBoolean(oidData.Attributes.Find(o => o.Key == "IsMergeSurvivor").Value)); } // Add to alternate identifiers dbCntrPsn.AlternateIdentifiers.Add(new SVC.Core.DataTypes.DomainIdentifier() { AssigningAuthority = id.AssigningAuthority, UpdateMode = SVC.Core.DataTypes.UpdateModeType.AddOrUpdate, IsLicenseAuthority = false, IsPrivate = isPrivate, // TODO: Make this a configuration flag (cntrPsn.AlternateIdentifiers.Exists(i=>i.Domain == id.Domain)), Identifier = id.Identifier, Domain = id.Domain }); } foreach (var id in psn.OtherIdentifiers) { // Remove the identifier from the original id.Value.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Remove; // If this is a duplicate id then don't add if (dbCntrPsn.OtherIdentifiers.Exists(i => i.Value.Domain == id.Value.Domain && i.Value.Identifier == id.Value.Identifier)) { continue; } // Add to other identifiers var oth = new KeyValuePair <SVC.Core.DataTypes.CodeValue, SVC.Core.DataTypes.DomainIdentifier>( id.Key, new SVC.Core.DataTypes.DomainIdentifier() { AssigningAuthority = id.Value.AssigningAuthority, UpdateMode = SVC.Core.DataTypes.UpdateModeType.Add, IsLicenseAuthority = false, IsPrivate = (dbCntrPsn.OtherIdentifiers.Exists(i => i.Value.Domain == id.Value.Domain)), Identifier = id.Value.Identifier, Domain = id.Value.Domain }); // Copy extensions var extns = psn.FindAllExtensions(o => o.PropertyPath == String.Format("OtherIdentifiers[{0}{1}]", oth.Value.Domain, oth.Value.Identifier)); if (extns != null) { foreach (var ex in extns) { if (dbCntrPsn.FindExtension(o => o.PropertyPath == ex.PropertyPath && o.Name == ex.Name) == null) { dbCntrPsn.Add(ex); } } } dbCntrPsn.OtherIdentifiers.Add(oth); } // Make sure we don't update what we don't need to dbCntrPsn.Addresses = psn.Addresses = null; dbCntrPsn.Citizenship = psn.Citizenship = null; dbCntrPsn.Employment = psn.Employment = null; dbCntrPsn.Language = psn.Language = null; dbCntrPsn.Names = psn.Names = null; dbCntrPsn.Race = psn.Race = null; dbCntrPsn.TelecomAddresses = psn.TelecomAddresses = null; dbCntrPsn.BirthTime = psn.BirthTime = null; dbCntrPsn.DeceasedTime = psn.DeceasedTime = null; // Remove the old person from the db psn.Status = SVC.Core.ComponentModel.Components.StatusType.Obsolete; // obsolete the old person } else // migrate identifiers { foreach (var id in refr.AlternateIdentifiers) { bool isPrivate = false; var oidData = ApplicationContext.ConfigurationService.OidRegistrar.FindData(id.Domain); if (oidData != null) { isPrivate = !(oidData.Attributes.Exists(o => o.Key == "IsMergeSurvivor") && Convert.ToBoolean(oidData.Attributes.Find(o => o.Key == "IsMergeSurvivor").Value)); } dbCntrPsn.AlternateIdentifiers.Add(new SVC.Core.DataTypes.DomainIdentifier() { AssigningAuthority = id.AssigningAuthority, UpdateMode = SVC.Core.DataTypes.UpdateModeType.AddOrUpdate, IsLicenseAuthority = false, IsPrivate = isPrivate, // TODO: Make this a configuration flag (cntrPsn.AlternateIdentifiers.Exists(i=>i.Domain == id.Domain)), Identifier = id.Identifier, Domain = id.Domain }); } // set to ignore if (psn.Names != null) { foreach (var rc in psn.Names) { rc.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Ignore; } } // set to ignore if (psn.Addresses != null) { foreach (var rc in psn.Addresses) { rc.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Ignore; } } // set to ignore if (psn.Race != null) { foreach (var rc in psn.Race) { rc.UpdateMode = SVC.Core.DataTypes.UpdateModeType.Ignore; } } } // Now update the person //psn.Site = refr.Site; //pp.Persist(conn, tx, psn, true); // update the person record #if DEBUG Trace.TraceInformation("Step 1 : Prepare update to person #{0}", psn.Id, cntrPsn.Id, !symbolic); #endif var regEvent = this.GetRegistrationEvent(conn, tx, psn); // get the registration event var changeSummary = DbUtil.GetRegistrationEvent(refr).FindComponent(HealthServiceRecordSiteRoleType.ReasonFor | HealthServiceRecordSiteRoleType.OlderVersionOf) as ChangeSummary; if (changeSummary != null) { regEvent.RemoveAllFromRole(HealthServiceRecordSiteRoleType.ReasonFor | HealthServiceRecordSiteRoleType.OlderVersionOf); regEvent.Add(new ChangeSummary() { ChangeType = changeSummary.ChangeType, EffectiveTime = changeSummary.EffectiveTime, LanguageCode = changeSummary.LanguageCode, Status = changeSummary.Status, Timestamp = changeSummary.Timestamp }, "CHG", HealthServiceRecordSiteRoleType.ReasonFor | HealthServiceRecordSiteRoleType.OlderVersionOf, null); } if (!symbolic) { regEvent.Status = StatusType.Obsolete; // obsolete } regEvent.RemoveAllFromRole(HealthServiceRecordSiteRoleType.SubjectOf); regEvent.Add(psn, "SUBJ", HealthServiceRecordSiteRoleType.SubjectOf, null); #if DEBUG Trace.TraceInformation("Step 2 : Perform update to person #{0}", psn.Id); #endif new RegistrationEventPersister().Persist(conn, tx, regEvent, true); refr.AlternateIdentifiers.Clear(); refr.AlternateIdentifiers.Add(new SVC.Core.DataTypes.DomainIdentifier() { Domain = ApplicationContext.ConfigurationService.OidRegistrar.GetOid("CR_CID").Oid, Identifier = psn.Id.ToString() }); //pp.CreatePersonVersion(conn, tx, psn); //DbUtil.PersistComponents(conn, tx, false, this, psn); // Now, we have to prepare an event so that this all makes sense // if we de-persist the most recent version (to reflect changes made) // Store the merged new record #if DEBUG Trace.TraceInformation("Step 3 : Perform update to person #{0}", dbCntrPsn.Id); #endif pp.CreatePersonVersion(conn, tx, dbCntrPsn); // Components DbUtil.PersistComponents(conn, tx, false, this, dbCntrPsn); // Now update the backreference to up the chain it gets updated cntrPsn.VersionId = dbCntrPsn.VersionId; } // Create the link #if DEBUG Trace.TraceInformation("Creating link between persons {0} > {1}", psn.Id, dbCntrPsn.Id); #endif using (var cmd = DbUtil.CreateCommandStoredProc(conn, tx)) { cmd.CommandText = "crt_psn_lnk"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_id_in", DbType.Decimal, dbCntrPsn.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_vrsn_id_in", DbType.Decimal, dbCntrPsn.VersionId)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lnk_psn_id_in", DbType.Decimal, psn.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lnk_cls_in", DbType.Decimal, (decimal)role)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "symbolic_in", DbType.Boolean, symbolic)); cmd.ExecuteNonQuery(); } // Send notification that duplicates were resolved //if (symbolic) //{ // // Send an duplicates resolved message // IClientNotificationService notificationService = ApplicationContext.CurrentContext.GetService(typeof(IClientNotificationService)) as IClientNotificationService; // if (notificationService != null) // notificationService.NotifyDuplicatesResolved(cntrPsn, refr.AlternateIdentifiers[0]); //} refr.Id = psn.Id; // Person identifier return(new SVC.Core.DataTypes.VersionedDomainIdentifier() { Identifier = psn.Id.ToString(), Version = psn.VersionId.ToString() }); }
/// <summary> /// De-persist /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, IContainer container, HealthServiceRecordSiteRoleType?roleType, bool loadFast) { HealthcareParticipant retVal = new HealthcareParticipant(); IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null); try { // Determine the container RegistrationEvent hsrParent = container as RegistrationEvent; retVal = GetProvider(conn, null, new DomainIdentifier() { Identifier = identifier.ToString() }); // Data reader if (hsrParent != null) { cmd.CommandText = "get_hsr_ptcpt"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, hsrParent.Id)); //cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "vrsn_id_in", DbType.Decimal, hsrParent.VersionIdentifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_id_in", DbType.Decimal, identifier)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "ptcpt_cls_in", DbType.Decimal, (decimal)roleType.Value)); // Role Decimal repOrgId = default(decimal); List <DomainIdentifier> originalIds = new List <DomainIdentifier>(); // Execute a reader IDataReader reader = cmd.ExecuteReader(); try { // Read a row while (reader.Read()) { repOrgId = reader["ptcpt_rep_org_id"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(reader["ptcpt_rep_org_id"]); originalIds.Add(new DomainIdentifier() { Domain = Convert.ToString(reader["orig_id_domain"]), Identifier = Convert.ToString(reader["orig_id"]), IsLicenseAuthority = Convert.ToBoolean(reader["license_ind"]) }); } } finally { reader.Close(); } // Representative of if (repOrgId != default(decimal)) { retVal.Add(GetProvider(conn, null, new DomainIdentifier() { Identifier = repOrgId.ToString() }), "REPOF", HealthServiceRecordSiteRoleType.RepresentitiveOf, null); } // Add to parent hsrParent.Add(retVal, Guid.NewGuid().ToString(), roleType.Value, originalIds); } else if (container != null) { container.Add(retVal); } } finally { cmd.Dispose(); } // TODO: Get original identifiers for this link return(retVal); }
/// <summary> /// Get location data from the database /// </summary> /// <param name="conn"></param> /// <param name="tx"></param> /// <param name="domainIdentifier"></param> /// <returns></returns> private Place GetLocation(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, DomainIdentifier domainIdentifier) { // Get configuration service ISystemConfigurationService config = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService; // Create database command IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); try { // Fetch the client data using shrid if (String.IsNullOrEmpty(domainIdentifier.Domain) || domainIdentifier.Domain.Equals(config.OidRegistrar.GetOid(ClientRegistryOids.LOCATION_CRID).Oid)) { cmd.CommandText = "get_plc"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, Convert.ToDecimal(domainIdentifier.Identifier))); } else // get using alt id { cmd.CommandText = "get_plc_extern"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_domain_in", DbType.StringFixedLength, domainIdentifier.Domain)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.StringFixedLength, (object)domainIdentifier.Identifier ?? DBNull.Value)); } // Execute the reader IDataReader reader = cmd.ExecuteReader(); // read data if (!reader.Read()) { return(null); } // Parse data Place retVal = new Place(); decimal?codeTypeId = null, addrSetId = null; try { retVal.Id = Convert.ToDecimal(reader["plc_id"]); // Define set identifiers retVal.Name = reader["plc_name"] == DBNull.Value ? null : Convert.ToString(reader["plc_name"]); retVal.Class = reader["plc_cls_cs"] == DBNull.Value ? null : Convert.ToString(reader["plc_cls_cs"]); addrSetId = reader["plc_addr_set_id"] == DBNull.Value ? null : (decimal?)Convert.ToDecimal(reader["plc_addr_set_id"]); codeTypeId = reader["plc_typ_cd_id"] == DBNull.Value ? null : (decimal?)Convert.ToDecimal(reader["plc_typ_cd_id"]); } finally { // Close the reader reader.Close(); } // Get addr set if (addrSetId.HasValue) { retVal.Address = DbUtil.GetAddress(conn, tx, addrSetId, false); } // Get type code if (codeTypeId.HasValue) { retVal.LocationType = DbUtil.GetCodedValue(conn, tx, codeTypeId); } // Read alternate identifiers retVal.AlternateIdentifiers.AddRange(GetAlternateIdentifiers(conn, tx, retVal.Id)); // Return type return(retVal); } finally { cmd.Dispose(); } }
/// <summary> /// De-persist a record from the database /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, IContainer container, HealthServiceRecordSiteRoleType?roleType, bool loadFast) { // Return value PersonalRelationship retVal = new PersonalRelationship(); // De-persist the observation record ISystemConfigurationService sysConfig = ApplicationContext.ConfigurationService; // De-persist using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null)) { cmd.CommandText = "get_psn_rltnshp"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "psn_rltnshp_id_in", DbType.Decimal, identifier)); String clientId = String.Empty; // Execute the reader using (IDataReader rdr = cmd.ExecuteReader()) { if (rdr.Read()) { retVal.Id = identifier; retVal.RelationshipKind = Convert.ToString(rdr["kind_cs"]); // Add prs retVal.AlternateIdentifiers.Add(new DomainIdentifier() { Domain = sysConfig.OidRegistrar.GetOid(ClientRegistryOids.RELATIONSHIP_OID).Oid, Identifier = rdr["rltnshp_id"].ToString() }); retVal.Id = Convert.ToDecimal(rdr["rltnshp_id"]); clientId = rdr["src_psn_id"].ToString(); } else { return(null); } } // First, de-persist the client portions var clientDataRetVal = new PersonPersister().GetPerson(conn, null, new DomainIdentifier() { Domain = sysConfig.OidRegistrar.GetOid(ClientRegistryOids.CLIENT_CRID).Oid, Identifier = clientId.ToString() }, true); if (clientDataRetVal.Names != null) { retVal.LegalName = clientDataRetVal.Names.Find(o => o.Use == NameSet.NameSetUse.Legal) ?? clientDataRetVal.Names[0]; } if (clientDataRetVal.RoleCode == PersonRole.PAT) { retVal.AlternateIdentifiers.AddRange(clientDataRetVal.AlternateIdentifiers.Where(o => o.Domain != sysConfig.OidRegistrar.GetOid(ClientRegistryOids.RELATIONSHIP_OID).Oid)); } else { retVal.AlternateIdentifiers.AddRange(clientDataRetVal.AlternateIdentifiers.Where(o => o.Domain != sysConfig.OidRegistrar.GetOid(ClientRegistryOids.CLIENT_CRID).Oid)); } retVal.Add(clientDataRetVal, "SUBJ", HealthServiceRecordSiteRoleType.SubjectOf, null); } return(retVal); }
/// <summary> /// De-persist the specified change summary /// </summary> public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, System.ComponentModel.IContainer container, SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType?role, bool loadFast) { // TODO: Ensure that when a parent with context conduction exists, to grab contextual data (authors, etc...) from the parent ChangeSummary retVal = new ChangeSummary(); // Configuration service ISystemConfigurationService configService = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService; // Get the health service event IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null); try { cmd.CommandText = "get_hsr_crnt_vrsn"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, identifier)); decimal tsId = default(decimal), cdId = default(decimal), rplcVersionId = default(decimal); // Read data IDataReader reader = cmd.ExecuteReader(); try { if (!reader.Read()) { return(null); } retVal.Id = Convert.ToDecimal(reader["hsr_id"]); retVal.VersionIdentifier = Convert.ToDecimal(reader["hsr_vrsn_id"]); retVal.AlternateIdentifier = new VersionedDomainIdentifier() { Domain = configService.OidRegistrar.GetOid(ClientRegistryOids.EVENT_OID).Oid, Identifier = retVal.Id.ToString(), Version = retVal.VersionIdentifier.ToString() }; retVal.LanguageCode = reader["lang_cs"].ToString(); retVal.Timestamp = DateTime.Parse(Convert.ToString(reader["aut_utc"])); retVal.Status = (StatusType)Convert.ToDecimal(reader["status_cs_id"]); tsId = reader["efft_ts_set_id"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(reader["efft_ts_set_id"]); cdId = Convert.ToDecimal(reader["evt_typ_cd_id"]); rplcVersionId = reader["rplc_vrsn_id"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(reader["rplc_vrsn_id"]); } finally { reader.Close(); } // Read codes and times retVal.ChangeType = DbUtil.GetCodedValue(conn, null, cdId); if (tsId != default(decimal)) { retVal.EffectiveTime = DbUtil.GetEffectiveTimestampSet(conn, null, tsId); } if (container != null) { container.Add(retVal); } if (role.HasValue && (role.Value & HealthServiceRecordSiteRoleType.ReplacementOf) == HealthServiceRecordSiteRoleType.ReplacementOf) { ; } else { DbUtil.DePersistComponents(conn, retVal, this, loadFast); } } finally { cmd.Dispose(); } return(retVal); }
/// <summary> /// Persist a component to the database /// </summary> public MARC.HI.EHRS.SVC.Core.DataTypes.VersionedDomainIdentifier Persist(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, System.ComponentModel.IComponent data, bool isUpdate) { // Get config service ISystemConfigurationService configService = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService; // Create the personal relationship in a strongly typed fashion PersonalRelationship pr = data as PersonalRelationship; Person clientContainer = pr.Site.Container as Person, relationshipPerson = null; // Get the person persister var persister = new PersonPersister(); // First, let's see if we can fetch the client if (pr.Id != default(decimal)) { var personalRelationship = this.DePersist(conn, pr.Id, pr.Site.Container, (pr.Site as HealthServiceRecordSite).SiteRoleType, true) as PersonalRelationship; relationshipPerson = personalRelationship.FindComponent(HealthServiceRecordSiteRoleType.SubjectOf) as Person; } else if (pr.AlternateIdentifiers != null) { int i = 0; while (relationshipPerson == null && i < pr.AlternateIdentifiers.Count) { relationshipPerson = persister.GetPerson(conn, tx, pr.AlternateIdentifiers[i++], true); } } if (relationshipPerson == null) { List <DomainIdentifier> candidateId = new List <DomainIdentifier>(); // Is this an existing person (same name and relation) using (IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx)) { cmd.CommandText = "get_psn_rltnshps"; cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "src_psn_id_in", DbType.Decimal, clientContainer.Id)); cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "src_psn_vrsn_id_in", DbType.Decimal, clientContainer.VersionId)); using (IDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if (rdr["kind_cs"].ToString() == pr.RelationshipKind) { candidateId.Add(new DomainIdentifier() { Domain = configService.OidRegistrar.GetOid("CR_CID").Oid, Identifier = rdr["src_psn_id"].ToString() }); } } } } // Now load candidates and check foreach (var id in candidateId) { var candidate = persister.GetPerson(conn, tx, id, true); if (NON_DUPLICATE_REL.Contains(pr.RelationshipKind)) { relationshipPerson = candidate; break; } else if (candidate.Names.Exists(n => n.SimilarityTo(pr.LegalName) >= DatabasePersistenceService.ValidationSettings.PersonNameMatch)) { relationshipPerson = candidate; break; } } } // Did we get one? // If not, then we need to register a patient in the database if (relationshipPerson == null) { if (pr.LegalName == null) { throw new DataException(ApplicationContext.LocaleService.GetString("DBCF00B")); } relationshipPerson = new Person() { AlternateIdentifiers = pr.AlternateIdentifiers, Names = new List <NameSet>() { pr.LegalName }, Addresses = new List <AddressSet>() { pr.PerminantAddress }, GenderCode = pr.GenderCode, BirthTime = pr.BirthTime, TelecomAddresses = pr.TelecomAddresses, Status = StatusType.Active, RoleCode = PersonRole.PRS }; var registrationEvent = DbUtil.GetRegistrationEvent(pr).Clone() as RegistrationEvent; registrationEvent.Id = default(decimal); registrationEvent.EventClassifier = RegistrationEventType.ComponentEvent; registrationEvent.RemoveAllFromRole(HealthServiceRecordSiteRoleType.SubjectOf); registrationEvent.Add(relationshipPerson, "SUBJ", HealthServiceRecordSiteRoleType.SubjectOf, null); registrationEvent.Status = StatusType.Completed; // Persist or merge? new RegistrationEventPersister().Persist(conn, tx, registrationEvent, isUpdate); //var clientIdentifier = persister.Persist(conn, tx, relationshipPerson, isUpdate); // Should persist } else if (relationshipPerson.RoleCode != PersonRole.PAT) { var updatedPerson = new Person() { Id = relationshipPerson.Id, AlternateIdentifiers = pr.AlternateIdentifiers, Names = new List <NameSet>() { pr.LegalName }, Addresses = new List <AddressSet>() { }, GenderCode = pr.GenderCode, BirthTime = pr.BirthTime, TelecomAddresses = pr.TelecomAddresses, Status = StatusType.Active, RoleCode = relationshipPerson.RoleCode }; if (pr.PerminantAddress != null) { updatedPerson.Addresses.Add(pr.PerminantAddress); } persister.MergePersons(updatedPerson, relationshipPerson, true); relationshipPerson = updatedPerson; var registrationEvent = DbUtil.GetRegistrationEvent(pr).Clone() as RegistrationEvent; registrationEvent.Id = default(decimal); registrationEvent.EventClassifier = RegistrationEventType.ComponentEvent; registrationEvent.RemoveAllFromRole(HealthServiceRecordSiteRoleType.SubjectOf); registrationEvent.Add(relationshipPerson, "SUBJ", HealthServiceRecordSiteRoleType.SubjectOf, null); registrationEvent.Status = StatusType.Completed; new RegistrationEventPersister().Persist(conn, tx, registrationEvent, isUpdate); } // Validate if (!NON_DUPLICATE_REL.Contains(pr.RelationshipKind) && pr.AlternateIdentifiers.Count == 0 && !relationshipPerson.Names.Exists(o => QueryUtil.MatchName(pr.LegalName, o) >= DatabasePersistenceService.ValidationSettings.PersonNameMatch)) { throw new DataException(ApplicationContext.LocaleService.GetString("DBCF00A")); } // If the container for this personal relationship is a client, then we'll need to link that // personal relationship with the client to whom they have a relation with. if (clientContainer != null) // We need to do some linking { pr.Id = LinkClients(conn, tx, relationshipPerson.Id, clientContainer.Id, pr.RelationshipKind, pr.Status); } else if (clientContainer == null) // We need to do some digging to find out "who" this person is related to (the record target) { throw new ConstraintException(ApplicationContext.LocaleService.GetString("DBCF003")); } // todo: Container is a HSR return(new VersionedDomainIdentifier() { Domain = configService.OidRegistrar.GetOid(ClientRegistryOids.RELATIONSHIP_OID).Oid, Identifier = pr.Id.ToString() }); }
/// <summary> /// Create the HSR record /// </summary> internal VersionedDomainIdentifier CreateHSRRecord(IDbConnection conn, IDbTransaction tx, RegistrationEvent hsr) { IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx); cmd.CommandText = "crt_hsr"; // Get the terminology service //ITerminologyService its = ApplicationContext.CurrentContext.GetService(typeof(ITerminologyService)) as ITerminologyService; ISystemConfigurationService iscs = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService; // Validate the language code //if (its != null) //{ // var validationError = its.Validate(hsr.LanguageCode, null, CodeSystemName.ISO639); // if (validationError.Outcome != MARC.HI.EHRS.SVC.Core.Terminology.ValidationOutcome.ValidWithWarning && // validationError.Outcome != MARC.HI.EHRS.SVC.Core.Terminology.ValidationOutcome.Valid) // throw new ConstraintException("Language MUST be a valid ISO639 Country code in the format XX-XX"); //} // Parameters // classifier cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_cls_in", DbType.Decimal, (int)hsr.EventClassifier)); // event type code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "evt_typ_cd_id_in", DbType.Decimal, DbUtil.CreateCodedValue(conn, tx, hsr.EventType))); // refuted indicator cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "refuted_ind_in", DbType.Boolean, hsr.Refuted)); decimal?efftTimeId = null; if (hsr.EffectiveTime != null) { efftTimeId = DbUtil.CreateTimeset(conn, tx, hsr.EffectiveTime); } cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "efft_ts_set_id_in", DbType.Decimal, efftTimeId == null ? (object)DBNull.Value : efftTimeId.Value)); // status code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "status_cs_in", DbType.Decimal, hsr.Status == null ? (object)DBNull.Value : (int)hsr.Status)); // authored time cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "aut_utc_in", DbType.DateTime, hsr.Timestamp == default(DateTime) ? (object)DBNull.Value : hsr.Timestamp)); // language code cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lang_cs_in", DbType.String, hsr.LanguageCode)); // Execute the command IDataReader resultRdr = cmd.ExecuteReader(); try { // Create the return value VersionedDomainIdentifier id = new VersionedDomainIdentifier(); if (!resultRdr.Read()) { return(null); } id.Version = Convert.ToString(resultRdr["VRSN_ID"]); id.Identifier = Convert.ToString(resultRdr["ID"]); id.Domain = iscs.OidRegistrar.GetOid(ClientRegistryOids.REGISTRATION_EVENT).Oid; return(id); } finally { resultRdr.Close(); } }