Example #1
0
        /// <summary>
        /// Insert the specified sbadm
        /// </summary>
        public override Core.Model.Acts.SubstanceAdministration InsertInternal(DataContext context, Core.Model.Acts.SubstanceAdministration data, IPrincipal principal)
        {
            if (data.DoseUnit != null)
            {
                data.DoseUnit = data.DoseUnit?.EnsureExists(context, principal) as Concept;
            }
            if (data.Route != null)
            {
                data.Route = data.Route?.EnsureExists(context, principal) as Concept;
            }
            else if (!data.RouteKey.HasValue)
            {
                data.RouteKey = NullReasonKeys.NoInformation;
            }

            // JF: Correct dose unit key
            if (AdoPersistenceService.GetConfiguration().DataCorrectionKeys.Contains("invalid-sbadm-dose-unit") &&
                data.DoseUnitKey == Guid.Parse("a77b8d83-1cc9-4806-a268-5d1738154afa"))
            {
                data.DoseUnitKey = Guid.Parse("a4fc5c93-31c2-4f87-990e-c5a4e5ea2e76");
            }
            data.DoseUnitKey = data.DoseUnit?.Key ?? data.DoseUnitKey;
            data.RouteKey    = data.Route?.Key ?? data.RouteKey;
            return(base.InsertInternal(context, data, principal));
        }
        /// <summary>
        /// Performs the actual query
        /// </summary>
        public override IEnumerable <TModel> QueryInternal(DataContext context, Expression <Func <TModel, bool> > query, Guid queryId, int offset, int?count, out int totalResults, IPrincipal principal, bool countResults = true)
        {
            int resultCount = 0;
            var results     = this.QueryInternal(context, query, queryId, offset, count, out resultCount, countResults).ToList();

            totalResults = resultCount;

            if (!AdoPersistenceService.GetConfiguration().SingleThreadFetch)
            {
                return(results.AsParallel().Select(o =>
                {
                    var subContext = context;
                    var newSubContext = results.Count() > 1;

                    try
                    {
                        if (newSubContext)
                        {
                            subContext = subContext.OpenClonedContext();
                        }

                        if (o is Guid)
                        {
                            return this.Get(subContext, (Guid)o, principal);
                        }
                        else
                        {
                            return this.CacheConvert(o, subContext, principal);
                        }
                    }
                    catch (Exception e)
                    {
                        this.m_tracer.TraceEvent(TraceEventType.Error, e.HResult, "Error performing sub-query: {0}", e);
                        throw;
                    }
                    finally
                    {
                        if (newSubContext)
                        {
                            subContext.Dispose();
                        }
                    }
                }));
            }
            else
            {
                return(results.Select(o =>
                {
                    if (o is Guid)
                    {
                        return this.Get(context, (Guid)o, principal);
                    }
                    else
                    {
                        return this.CacheConvert(o, context, principal);
                    }
                }));
            }
        }
        /// <summary>
        /// Insert or update contents of the bundle
        /// </summary>
        /// <returns></returns>
        public override Bundle InsertInternal(DataContext context, Bundle data, IPrincipal principal)
        {
            if (data.Item == null)
            {
                return(data);
            }
            this.m_tracer.TraceInformation("Bundle has {0} objects...", data.Item.Count);
            data = this.ReorganizeForInsert(data);
            this.m_tracer.TraceInformation("After reorganization has {0} objects...", data.Item.Count);

            if (AdoPersistenceService.GetConfiguration().PrepareStatements)
            {
                context.PrepareStatements = true;
            }
            for (int i = 0; i < data.Item.Count; i++)
            {
                var itm    = data.Item[i];
                var idp    = typeof(IDataPersistenceService <>).MakeGenericType(new Type[] { itm.GetType() });
                var svc    = ApplicationContext.Current.GetService(idp);
                var method = "Insert";

                if (itm.TryGetExisting(context, principal, true) != null)
                {
                    method = "Update";
                }

                this.m_tracer.TraceInformation("Will {0} object from bundle {1}...", method, itm);
                this.ProgressChanged?.Invoke(this, new ProgressChangedEventArgs((float)(i + 1) / data.Item.Count, itm));

                var mi = svc.GetType().GetRuntimeMethod(method, new Type[] { typeof(DataContext), itm.GetType(), typeof(IPrincipal) });
                try
                {
                    data.Item[i] = mi.Invoke(svc, new object[] { context, itm, principal }) as IdentifiedData;
                }
                catch (TargetInvocationException e)
                {
                    throw e.InnerException;
                }
            }

            // Cache items
            foreach (var itm in data.Item)
            {
                itm.LoadState = LoadState.FullLoad;
                context.AddCacheCommit(itm);
            }
            return(data);
        }
        /// <summary>
        /// Reorganize all the major items for insert
        /// </summary>
        private Bundle ReorganizeForInsert(Bundle bundle)
        {
            Bundle retVal = new Bundle()
            {
                Item = new List <IdentifiedData>()
            };

            foreach (var itm in bundle.Item.Where(o => o != null))
            {
                this.m_tracer.TraceInformation("Reorganizing {0}..", itm.Key);
                // Are there any relationships
                if (itm is Entity)
                {
                    var ent = itm as Entity;
                    foreach (var rel in ent.Relationships)
                    {
                        this.m_tracer.TraceInformation("Processing {0} / relationship / {1} ..", itm.Key, rel.TargetEntityKey);

                        var bitm = bundle.Item.FirstOrDefault(o => o.Key == rel.TargetEntityKey);
                        if (bitm == null)
                        {
                            continue;
                        }

                        if (retVal.Item.Any(o => o.Key == rel.TargetEntityKey))
                        {
                            continue;
                        }
                        this.m_tracer.TraceInformation("Bumping (due to relationship): {0}", bitm);

                        retVal.Item.Add(bitm); // make sure it gets inserted first
                    }
                }
                else if (itm is Act)
                {
                    var act = itm as Act;
                    foreach (var rel in act.Relationships)
                    {
                        this.m_tracer.TraceInformation("Processing {0} / relationship / {1} ..", itm.Key, rel.TargetActKey);
                        var bitm = bundle.Item?.FirstOrDefault(o => o.Key == rel?.TargetActKey);
                        if (bitm == null)
                        {
                            continue;
                        }

                        if (retVal.Item.Any(o => o.Key == rel.TargetActKey))
                        {
                            continue;
                        }
                        this.m_tracer.TraceInformation("Bumping (due to relationship): {0}", bitm);
                        retVal.Item.Add(bitm); // make sure it gets inserted first
                    }

                    foreach (var rel in act.Participations)
                    {
                        this.m_tracer.TraceInformation("Processing {0} / participation / {1} ..", itm.Key, rel.PlayerEntityKey);
                        var bitm = bundle.Item?.FirstOrDefault(o => o.Key == rel?.PlayerEntityKey);
                        if (bitm == null)
                        {
                            continue;
                        }

                        if (retVal.Item.Any(o => o.Key == rel.PlayerEntityKey))
                        {
                            continue;
                        }

                        this.m_tracer.TraceInformation("Bumping (due to participation): {0}", bitm);
                        retVal.Item.Add(bitm); // make sure it gets inserted first
                    }


                    // Old versions of the mobile had an issue with missing record targets
                    if (AdoPersistenceService.GetConfiguration().DataCorrectionKeys.Contains("correct-missing-rct"))
                    {
                        var patientEncounter = bundle.Item.OfType <PatientEncounter>().FirstOrDefault();

                        if (patientEncounter != null)
                        {
                            var rct = act.Participations.FirstOrDefault(o => o.ParticipationRoleKey == OpenIZ.Core.Model.Constants.ActParticipationKey.RecordTarget);
                            if (!(rct == null || rct.PlayerEntityKey.HasValue))
                            {
                                var perct = patientEncounter.Participations.FirstOrDefault(o => o.ParticipationRoleKey == ActParticipationKey.RecordTarget);

                                act.Participations.Remove(rct);
                                act.Participations.Add(new ActParticipation(ActParticipationKey.RecordTarget, perct.PlayerEntityKey));
                            }
                        }
                    }
                }

                this.m_tracer.TraceInformation("Re-adding: {0}", itm);
                retVal.Item.Add(itm);
            }

            return(retVal);
        }
Example #5
0
        /// <summary>
        /// Ensures a model has been persisted
        /// </summary>
        public static IIdentifiedEntity EnsureExists(this IIdentifiedEntity me, DataContext context, IPrincipal principal)
        {
            if (me == null)
            {
                return(null);
            }

            // Me
            var    vMe  = me as IVersionedEntity;
            String dkey = String.Format("{0}.{1}", me.GetType().FullName, me.Key);

            IIdentifiedEntity existing = me.TryGetExisting(context, principal);
            var idpInstance            = AdoPersistenceService.GetPersister(me.GetType());

            // Don't touch the child just return reference
            if (!AdoPersistenceService.GetConfiguration().AutoInsertChildren)
            {
                if (existing != null)
                {
                    if (me.Key != existing.Key ||
                        vMe?.VersionKey != (existing as IVersionedEntity)?.VersionKey)
                    {
                        me.CopyObjectData(existing); // copy data into reference
                    }
                    return(existing);
                }
                else
                {
                    throw new KeyNotFoundException(me.Key.Value.ToString());
                }
            }

            // Existing exists?
            if (existing != null && me.Key.HasValue)
            {
                // Exists but is an old version
                if ((existing as IVersionedEntity)?.VersionKey != vMe?.VersionKey &&
                    vMe?.VersionKey != null && vMe?.VersionKey != Guid.Empty)
                {
                    // Update method
                    IVersionedEntity updated = idpInstance.Update(context, me, principal) as IVersionedEntity;
                    me.Key = updated.Key;
                    if (vMe != null)
                    {
                        vMe.VersionKey = (updated as IVersionedEntity).VersionKey;
                    }
                    return(updated);
                }
                return(existing);
            }
            else if (existing == null) // Insert
            {
                IIdentifiedEntity inserted = idpInstance.Insert(context, me, principal) as IIdentifiedEntity;
                me.Key = inserted.Key;

                if (vMe != null)
                {
                    vMe.VersionKey = (inserted as IVersionedEntity).VersionKey;
                }
                return(inserted);
            }
            return(existing);
        }
Example #6
0
        /// <summary>
        /// Update the specified data
        /// </summary>
        public Core.Model.Acts.Act UpdateCoreProperties(DataContext context, Core.Model.Acts.Act data, IPrincipal principal)
        {
            if (data.ClassConcept != null)
            {
                data.ClassConcept = data.ClassConcept?.EnsureExists(context, principal) as Concept;
            }
            if (data.MoodConcept != null)
            {
                data.MoodConcept = data.MoodConcept?.EnsureExists(context, principal) as Concept;
            }
            if (data.ReasonConcept != null)
            {
                data.ReasonConcept = data.ReasonConcept?.EnsureExists(context, principal) as Concept;
            }
            if (data.StatusConcept != null)
            {
                data.StatusConcept = data.StatusConcept?.EnsureExists(context, principal) as Concept;
            }
            if (data.TypeConcept != null)
            {
                data.TypeConcept = data.TypeConcept?.EnsureExists(context, principal) as Concept;
            }
            if (data.Template != null)
            {
                data.Template = data.Template?.EnsureExists(context, principal) as TemplateDefinition;
            }

            data.ClassConceptKey  = data.ClassConcept?.Key ?? data.ClassConceptKey;
            data.MoodConceptKey   = data.MoodConcept?.Key ?? data.MoodConceptKey;
            data.ReasonConceptKey = data.ReasonConcept?.Key ?? data.ReasonConceptKey;
            data.StatusConceptKey = data.StatusConcept?.Key ?? data.StatusConceptKey ?? StatusKeys.New;

            // Do the update
            var retVal = base.UpdateInternal(context, data, principal);

            if (data.Extensions != null)
            {
                base.UpdateVersionedAssociatedItems <Core.Model.DataTypes.ActExtension, DbActExtension>(
                    data.Extensions.Where(o => o != null && !o.IsEmpty()),
                    retVal,
                    context,
                    principal);
            }

            if (data.Identifiers != null)
            {
                base.UpdateVersionedAssociatedItems <Core.Model.DataTypes.ActIdentifier, DbActIdentifier>(
                    data.Identifiers.Where(o => o != null && !o.IsEmpty()),
                    retVal,
                    context,
                    principal);
            }

            if (data.Notes != null)
            {
                base.UpdateVersionedAssociatedItems <Core.Model.DataTypes.ActNote, DbActNote>(
                    data.Notes.Where(o => o != null && !o.IsEmpty()),
                    retVal,
                    context,
                    principal);
            }

            if (data.Participations != null)
            {
                // Correct mixed keys
                if (AdoPersistenceService.GetConfiguration().DataCorrectionKeys.Contains("edmonton-participation-keyfix"))
                {
                    // Obsolete all
                    foreach (var itm in context.Query <DbActParticipation>(o => o.SourceKey == retVal.Key && o.ObsoleteVersionSequenceId == null && o.ParticipationRoleKey == ActParticipationKey.Consumable))
                    {
                        itm.ObsoleteVersionSequenceId = retVal.VersionSequence;
                        context.Update(itm);
                    }
                    // Now we want to re-point to correct the issue
                    foreach (var itm in context.Query <DbActParticipation>(o => o.SourceKey == retVal.Key && o.ParticipationRoleKey == ActParticipationKey.Consumable && o.ObsoleteVersionSequenceId == retVal.VersionSequence))
                    {
                        var dItm = data.Participations.Find(o => o.Key == itm.Key);
                        if (dItm != null)
                        {
                            itm.TargetKey = dItm.PlayerEntityKey.Value;
                        }
                        itm.ObsoleteVersionSequenceId = null;
                        context.Update(itm);
                    }
                }

                // Update versioned association items
                base.UpdateVersionedAssociatedItems <Core.Model.Acts.ActParticipation, DbActParticipation>(
                    data.Participations.Where(o => o != null && !o.IsEmpty()),
                    retVal,
                    context,
                    principal);
            }

            if (data.Relationships != null)
            {
                base.UpdateVersionedAssociatedItems <Core.Model.Acts.ActRelationship, DbActRelationship>(
                    data.Relationships.Where(o => o != null && !o.IsEmpty() && (o.SourceEntityKey == data.Key || !o.SourceEntityKey.HasValue)),
                    retVal,
                    context,
                    principal);
            }

            if (data.Tags != null)
            {
                base.UpdateAssociatedItems <Core.Model.DataTypes.ActTag, DbActTag>(
                    data.Tags.Where(o => o != null && !o.IsEmpty()),
                    retVal,
                    context,
                    principal);
            }

            return(retVal);
        }