/// <summary>
        /// Check if the provided framework has already been sync'd.
        /// If not, it will be added.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <param name="frameworkId"></param>
        /// <returns></returns>
        //public bool HandleFrameworkRequest( CassFramework request,
        //		int userId,
        //		ref SaveStatus status,
        //		ref int frameworkId )
        //{
        //	bool isValid = true;
        //	if ( request == null || string.IsNullOrWhiteSpace(request._IdAndVersion) )
        //	{
        //		status.AddWarning( "The Cass Request doesn't contain a valid Cass Framework class." );
        //		return false;
        //	}
        //	ThisEntity item = Get( request._IdAndVersion );
        //	if (item != null && item.Id > 0)
        //	{
        //		//TODO - do we want to attempt an update - if changed
        //		//		- if we plan to implement a batch refresh of sync'd content, then not necessary
        //		frameworkId = item.Id;
        //		return true;
        //	}
        //	//add the framework...
        //	ThisEntity entity = new ThisEntity();
        //	entity.Name = request.Name;
        //	entity.Description = request.Description;
        //	entity.FrameworkUrl = request.Url;
        //	entity.RepositoryUri = request._IdAndVersion;

        //	//TDO - need owning org - BUT, first person to reference a framework is not necessarily the owner!!!!!
        //	//actually, we may not care here. Eventually get a ctid from CASS
        //	//entity.OwningOrganizationId = 0;

        //	isValid = Save( entity, userId, ref status );
        //	frameworkId = entity.Id;
        //	return isValid;
        //}


        //actually not likely to have a separate list of frameworks
        //public bool SaveList( List<ThisEntity> list, ref SaveStatus status )
        //{
        //	if ( list == null || list.Count == 0 )
        //		return true;

        //	bool isAllValid = true;
        //	foreach ( ThisEntity item in list )
        //	{
        //		Save( item, ref status );
        //	}

        //	return isAllValid;
        //}

        /// <summary>
        /// Add/Update a Reference_Framework
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity,
                         ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

            DBEntity efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                if (ValidateProfile(entity, ref status) == false)
                {
                    return(false);
                }

                if (entity.Id == 0)
                {
                    // - need to check for existance
                    DoesItemExist(entity);
                }

                if (entity.Id == 0)
                {
                    // - Add
                    efEntity = new DBEntity();
                    MapToDB(entity, efEntity);


                    efEntity.Created = DateTime.Now;
                    //efEntity.RowId = Guid.NewGuid();

                    context.Reference_Frameworks.Add(efEntity);

                    count = context.SaveChanges();

                    entity.Id = efEntity.Id;
                    //entity.RowId = efEntity.RowId;
                    if (count == 0)
                    {
                        status.AddWarning(string.Format(" Unable to add Profile: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.Name) ? "no description" : entity.Name));
                    }
                }
                else
                {
                    efEntity = context.Reference_Frameworks.SingleOrDefault(s => s.Id == entity.Id);
                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //entity.RowId = efEntity.RowId;
                        //update
                        MapToDB(entity, efEntity);
                        //has changed?
                        if (HasStateChanged(context))
                        {
                            count = context.SaveChanges();
                        }
                    }
                }
            }
            return(isValid);
        }
        /// <summary>
        /// Delete a JurisdictionProfile
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Delete(int Id, ref string statusMessage)
        {
            bool isValid = false;

            using (var context = new EntityContext())
            {
                if (Id == 0)
                {
                    statusMessage = "Error - missing an identifier for the JurisdictionProfile";
                    return(false);
                }

                DBEntity efEntity =
                    context.Entity_JurisdictionProfile.SingleOrDefault(s => s.Id == Id);
                if (efEntity != null && efEntity.Id > 0)
                {
                    context.Entity_JurisdictionProfile.Remove(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        isValid = true;
                    }
                }
                else
                {
                    statusMessage = string.Format("JurisdictionProfile record was not found: {0}", Id);
                    isValid       = false;
                }
            }

            return(isValid);
        }
Example #3
0
        public bool Delete(int Id, ref string statusMessage)
        {
            bool isValid = false;

            if (Id == 0)
            {
                statusMessage = "Error - missing an identifier for the PathwaySet";
                return(false);
            }
            using (var context = new EntityContext())
            {
                DBEntity efEntity = context.PathwaySet
                                    .SingleOrDefault(s => s.Id == Id);

                if (efEntity != null && efEntity.Id > 0)
                {
                    context.PathwaySet.Remove(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        isValid = true;
                    }
                }
                else
                {
                    statusMessage = "Error - delete failed, as record was not found.";
                }
            }

            return(isValid);
        }
        public bool UpdateModifiedDate(Guid entityUid, ref SaveStatus status)
        {
            bool isValid = false;

            if (!IsValidGuid(entityUid))
            {
                status.AddError(thisClassName + ".UpdateModifiedDate(). Error - missing a valid identifier for the Entity");
                return(false);
            }
            using (var context = new EntityContext())
            {
                DBentity efEntity = context.Entity
                                    .FirstOrDefault(s => s.EntityUid == entityUid);

                if (efEntity != null && efEntity.Id > 0)
                {
                    efEntity.LastUpdated = DateTime.Now;
                    int count = context.SaveChanges();
                    if (count >= 0)
                    {
                        isValid = true;
                        LoggingHelper.DoTrace(7, thisClassName + string.Format(".UpdateModifiedDate - update last updated for TypeId: {0}, BaseId: {1}", efEntity.EntityTypeId, efEntity.EntityBaseId));
                    }
                }
                else
                {
                    status.AddError(thisClassName + ".UpdateModifiedDate(). Error - Entity  was not found.");
                    LoggingHelper.LogError(thisClassName + string.Format(".UpdateModifiedDate - record was not found. entityUid: {0}", entityUid), true);
                }
            }

            return(isValid);
        }///
Example #5
0
        }        //

        public bool SetImport_PendingRequestHandled(int recordId, bool importWasSuccessful)
        {
            bool isValid = false;

            if (recordId <= 0)
            {
                return(false);
            }
            using (var context = new EntityContext())
            {
                var efEntity = context.Import_PendingRequest
                               .FirstOrDefault(s => s.Id == recordId);

                if (efEntity != null && efEntity.Id > 0)
                {
                    efEntity.WasProcessed        = true;
                    efEntity.ImportWasSuccessful = importWasSuccessful;
                    if (importWasSuccessful)
                    {
                        efEntity.ImportedDate = DateTime.Now;
                    }
                    int count = context.SaveChanges();
                    if (count >= 0)
                    {
                        isValid = true;
                    }
                }
                else
                {
                    LoggingHelper.LogError(thisClassName + string.Format(".SetImport_PendingRequestHandled - record was not found. recordId: {0}", recordId), true);
                }
            }

            return(isValid);
        }        ///
        /// <summary>
        /// Delete all records that are not in the provided list.
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="list"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool DeleteNotInList(Guid parentUid, List <Pathway> list, ref List <string> messages)
        {
            bool isValid = true;

            if (!list.Any())
            {
                return(true);
            }
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                messages.Add(thisClassName + string.Format(".DeleteNotInList() Error - the parent entity for [{0}] was not found.", parentUid));
                return(false);
            }

            using (var context = new EntityContext())
            {
                var existing = context.Entity_HasPathway.Where(s => s.EntityId == parent.Id).ToList();
                var inputIds = list.Select(x => x.Id).ToList();

                //delete records which are not selected
                var notExisting = existing.Where(x => !inputIds.Contains(x.PathwayId)).ToList();
                foreach (var item in notExisting)
                {
                    context.Entity_HasPathway.Remove(item);
                    context.SaveChanges();
                }
            }
            return(isValid);
        }
        }         //

        /// <summary>
        /// Delete all pathways for a parent, typically a pathwaySet
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="recordId"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool DeleteAll(Guid parentUid, ref SaveStatus status)
        {
            bool isValid = false;

            //need to get Entity.Id
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError("Error - the parent entity was not found.");
                return(false);
            }
            try
            {
                using (var context = new EntityContext())
                {
                    context.Entity_HasPathway.RemoveRange(context.Entity_HasPathway.Where(s => s.EntityId == parent.Id));
                    int count = context.SaveChanges();
                    if (count >= 0)
                    {
                        isValid = true;
                    }
                    else
                    {
                        //may not be any?
                        //may be should to a read check first?
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".DeleteAll( Guid parentUid, ref SaveStatus status )");
            }
            return(isValid);
        }
        /// <summary>
        /// Delete all profiles for parent
        /// </summary>
        /// <param name="dataSetProfileId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool DeleteAll(int dataSetProfileId, ref List <string> messages)
        {
            bool isValid = true;
            int  count   = 0;

            if (dataSetProfileId < 1)
            {
                messages.Add(thisClassName + "DeleteAll. Error - the dataSetProfileId was not provided.");
                return(false);
            }
            using (var context = new EntityContext())
            {
                var results = context.DataSetTimeFrame
                              .Where(s => s.DataSetProfileId == dataSetProfileId)
                              .ToList();
                if (results == null || results.Count == 0)
                {
                    return(true);
                }

                foreach (var item in results)
                {
                    //need to remove DataProfile
                    new DataProfileManager().DeleteAll(item.Id, ref messages);

                    context.DataSetTimeFrame.Remove(item);
                    count = context.SaveChanges();
                    if (count > 0)
                    {
                    }
                }
            }

            return(isValid);
        }
Example #9
0
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;

            //Entity parent = EntityManager.GetEntity( parentUid );
            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }
            using (var context = new EntityContext())
            {
                context.Entity_IdentifierValue.RemoveRange(context.Entity_IdentifierValue.Where(s => s.EntityId == parent.Id));
                int count = context.SaveChanges();
                if (count > 0)
                {
                    isValid = true;
                }
                else
                {
                    //if doing a delete on spec, may not have been any properties
                }
            }

            return(isValid);
        }
Example #10
0
        public void AssignDurationSummary(  )
        {
            ThisEntity row = new ThisEntity();

            using (var context = new EntityContext())
            {
                List <EM.Entity_DurationProfile> results = context.Entity_DurationProfile
                                                           .OrderBy(s => s.Id)
                                                           .ToList();

                if (results != null && results.Count > 0)
                {
                    foreach (EM.Entity_DurationProfile item in results)
                    {
                        row = new ThisEntity();
                        MapFromDB(item, row);
                        if (row.ExactDuration.HasValue || row.IsRange)
                        {
                            item.DurationSummary = row.DurationSummary;

                            if (HasStateChanged(context))
                            {
                                //note: testing - the latter may be true if the child has changed - but shouldn't as the mapping only updates the parent
                                //item.LastUpdated = System.DateTime.Now;
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
        public bool WidgetSelectionDelete(int widgetId, string widgetSection, int entityTypeId, int recordId, ref List <string> messages)
        {
            bool isOK = true;

            try
            {
                using (var context = new EntityContext())
                {
                    var p = context.Widget_Selection.FirstOrDefault(s => s.WidgetId == widgetId &&
                                                                    s.WidgetSection == widgetSection &&
                                                                    s.EntityTypeId == entityTypeId &&
                                                                    s.RecordId == recordId);
                    if (p != null && p.Id > 0)
                    {
                        context.Widget_Selection.Remove(p);
                        int count = context.SaveChanges();
                    }
                    else
                    {
                        messages.Add("Warning - the record was not found.");
                        isOK = true;
                    }
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + "WidgetSelectionDelete");
                messages.Add(ex.Message);
                isOK = false;
            }
            return(isOK);
        }
        public bool DeleteAll(int costProfileId, ref SaveStatus status)
        {
            bool isValid             = false;
            int  expectedDeleteCount = 0;

            using (var context = new EntityContext())
            {
                try
                {
                    var results = context.Entity_CostProfileItem.Where(s => s.CostProfileId == costProfileId)
                                  .ToList();
                    if (results == null || results.Count == 0)
                    {
                        return(true);
                    }
                    expectedDeleteCount = results.Count;
                    foreach (var item in results)
                    {
                        context.Entity_CostProfileItem.Remove(item);
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            isValid = true;
                        }
                        else
                        {
                            //if doing a delete on spec, may not have been any properties
                        }
                    }
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException dbcex)
                {
                    if (dbcex.Message.IndexOf("an unexpected number of rows (0)") > 0)
                    {
                        //don't know why this happens, quashing for now.
                        LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, expectedDeletes: {1}. DbUpdateConcurrencyException: {2}", costProfileId, expectedDeleteCount, dbcex.Message));
                        isValid = true;
                    }
                    else
                    {
                        var msg = BaseFactory.FormatExceptions(dbcex);
                        LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, DbUpdateConcurrencyException: {1}", costProfileId, msg));
                    }
                }
                catch (Exception ex)
                {
                    var msg = BaseFactory.FormatExceptions(ex);
                    LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, Exception: {1}", costProfileId, msg));

                    if (msg.IndexOf("was deadlocked on lock resources") > 0)
                    {
                        //retry = true;
                    }
                }
            }

            return(isValid);
        }
        /// <summary>
        /// SearchPendingReindexes Add
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, ref List <String> messages)
        {
            DBEntity efEntity = new DBEntity();

            if (!IsValid(entity, ref messages))
            {
                return(0);
            }
            try
            {
                using (var context = new EntityContext())
                {
                    //check if a pending record exists
                    DBEntity exists = context.SearchPendingReindex
                                      .FirstOrDefault(s => s.EntityTypeId == entity.EntityTypeId && s.RecordId == entity.RecordId && s.StatusId == 1);
                    if (exists != null && exists.Id > 0)
                    {
                        //could ignore,or check for a change of request type of add or delete
                        if (exists.IsUpdateOrDeleteTypeId == entity.IsUpdateOrDeleteTypeId)
                        {
                            return(exists.Id);
                        }
                        //otherwise do an update?
                        Update(entity, ref messages);
                        return(exists.Id);
                    }

                    MapToDB(entity, efEntity);
                    efEntity.Created     = System.DateTime.Now;
                    efEntity.LastUpdated = System.DateTime.Now;

                    context.SearchPendingReindex.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id = efEntity.Id;

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        messages.Add("Error - the profile was not saved. ");
                        string message = string.Format(thisClassName + ".Add. Failed. The process appeared to not work, but was not an exception, so we have no message, or no clue. EntityTypeId: {0}, RecordId: {1}", entity.EntityTypeId, entity.RecordId);
                        // EmailManager.NotifyAdmin( thisClassName + ". Add Failed", message );
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(). EntityTypeId: {0}, RecordId: {1}", entity.EntityTypeId, entity.RecordId));
            }


            return(efEntity.Id);
        }
        public int AddPendingRecord(Guid entityUid, string ctid, string registryAtId, ref string status)
        {
            DBEntity efEntity = new DBEntity();

            try
            {
                //var pathwayCTIDTemp = "ce-abcb5fe0-8fde-4f06-9d70-860cd5bdc763";
                using (var context = new EntityContext())
                {
                    if (!IsValidGuid(entityUid))
                    {
                        status = thisClassName + " - A valid GUID must be provided to create a pending entity";
                        return(0);
                    }
                    //quick check to ensure not existing
                    ThisEntity entity = GetByCtid(ctid);
                    if (entity != null && entity.Id > 0)
                    {
                        return(entity.Id);
                    }

                    //only add DB required properties
                    //NOTE - an entity will be created via trigger
                    efEntity.Name        = "Placeholder until full document is downloaded";
                    efEntity.Description = "Placeholder until full document is downloaded";
                    efEntity.PathwayCTID = "";
                    //temp
                    efEntity.ComponentTypeId = 1;
                    //realitically the component should be added in the same workflow
                    efEntity.EntityStateId = 1;
                    efEntity.RowId         = entityUid;
                    //watch that Ctid can be  updated if not provided now!!
                    efEntity.CTID           = ctid;
                    efEntity.SubjectWebpage = registryAtId;

                    efEntity.Created     = System.DateTime.Now;
                    efEntity.LastUpdated = System.DateTime.Now;

                    context.PathwayComponent.Add(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        return(efEntity.Id);
                    }

                    status = thisClassName + " Error - the save was not successful, but no message provided. ";
                }
            }

            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".AddPendingRecord. entityUid:  {0}, ctid: {1}", entityUid, ctid));
                status = thisClassName + " Error - the save was not successful. " + message;
            }
            return(0);
        }
Example #15
0
        /// <summary>
        /// Add an Entity_IdentifierValueManager
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        private int Add(Entity parent,
                        ThisEntity entity,
                        ref SaveStatus status)
        {
            int id    = 0;
            int count = 0;

            //Entity parent = EntityManager.GetEntity( parentUid );
            if (parent == null || parent.Id == 0)
            {
                status.AddError("Error - the parent entity was not found.");
                return(0);
            }
            using (var context = new EntityContext())
            {
                DBEntity efEntity = new DBEntity();
                try
                {
                    efEntity = new DBEntity();

                    MapToDB(entity, efEntity);
                    efEntity.EntityId = parent.Id;
                    efEntity.Created  = System.DateTime.Now;

                    context.Entity_IdentifierValue.Add(efEntity);

                    // submit the change to database
                    count = context.SaveChanges();
                    if (count > 0)
                    {
                        id = efEntity.Id;
                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        status.AddError("Error - the add was not successful.");
                        string message = thisClassName + string.Format(".Add Failed", "Attempted to add a Entity_IdentifierValue for a profile. The process appeared to not work, but there was no exception, so we have no message, or no clue. Parent Profile: {0}, Type: {1}, learningOppId: {2}, createdById: {3}", parent.EntityUid, parent.EntityType, entity.IdentifierType);
                        EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Entity_Entity_IdentifierValue");
                    status.AddError("Error - the save was not successful. " + message);
                    LoggingHelper.LogError(dbex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                }
                catch (Exception ex)
                {
                    string message = FormatExceptions(ex);
                    status.AddError("Error - the save was not successful. " + message);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                }
            }
            return(id);
        }
Example #16
0
        public bool UpdateAll(int requestTypeId, ref List <String> messages, int entityTypeId = 0)
        {
            bool isValid = false;
            int  count   = 0;

            if (requestTypeId < 1 || requestTypeId > 2)
            {
                return(false);
            }
            try
            {
                //could be a proc
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.SearchPendingReindex
                                              .Where
                                              (
                        s => s.StatusId == 1 &&
                        s.IsUpdateOrDeleteTypeId == requestTypeId &&
                        (entityTypeId == 0 || s.EntityTypeId == entityTypeId)
                                              )
                                              .ToList();
                    if (results != null && results.Count > 0)
                    {
                        foreach (var efEntity in results)
                        {
                            efEntity.StatusId = 2;
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;
                                count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error
                                    statusMessage = "Error - the update was not successful. ";
                                    messages.Add(string.Format(thisClassName + ".Update Failed. The process appeared to not work, but was not an exception, so we have no message, or no clue. EntityTypeId: {0}, RecordId: {1}", efEntity.EntityTypeId, efEntity.RecordId));
                                    //EmailManager.NotifyAdmin( thisClassName + ". ConditionProfile_Update Failed", message );
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".UpdateAll. requestTypeId: {0}", requestTypeId));
            }


            return(isValid);
        }
        /// <summary>
        /// Update a ThisEntity
        /// - base only, caller will handle parts?
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Update(ThisEntity entity, ref string statusMessage)
        {
            bool isValid = false;
            int  count   = 0;

            try
            {
                using (var context = new EntityContext())
                {
                    if (!IsValid(entity, ref messages))
                    {
                        return(0);
                    }

                    DBEntity efEntity = context.Credential_ConnectionProfile
                                        .SingleOrDefault(s => s.Id == entity.Id);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //for updates, chances are some fields will not be in interface, don't map these (ie created stuff)
                        MapToDB(entity, efEntity);
                        if (HasStateChanged(context))
                        {
                            efEntity.LastUpdated     = System.DateTime.Now;
                            efEntity.LastUpdatedById = entity.LastUpdatedById;
                            count = context.SaveChanges();
                            //can be zero if no data changed
                            if (count >= 0)
                            {
                                isValid = true;
                            }
                            else
                            {
                                //?no info on error
                                statusMessage = "Error - the update was not successful. ";
                                string message = string.Format(thisClassName + ".ConditionProfile_Update Failed", "Attempted to update a ThisEntity. The process appeared to not work, but was not an exception, so we have no message, or no clue. CredentialId: {0}, Id: {1}, updatedById: {2}", entity.ParentId, entity.Id, entity.LastUpdatedById);
                                EmailManager.NotifyAdmin(thisClassName + ". ConditionProfile_Update Failed", message);
                            }
                        }
                        //continue with parts regardless
                        //opMgr.ConditionProfile_UpdateParts( entity, false, ref statusMessage );
                    }
                    else
                    {
                        statusMessage = "Error - update failed, as record was not found.";
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Update. id: {0}", entity.Id));
            }


            return(isValid);
        }
Example #18
0
        /// <summary>
        /// Delete a Financial Alignment profile, and related Entity
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Delete(int Id, ref string statusMessage)
        {
            bool isValid = false;

            if (Id == 0)
            {
                statusMessage = "Error - missing an identifier for the FinancialAlignmentProfile";
                return(false);
            }
            using (var context = new EntityContext())
            {
                try
                {
                    DBEntity efEntity = context.Entity_FinancialAlignmentProfile
                                        .SingleOrDefault(s => s.Id == Id);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        Guid rowId = efEntity.RowId;

                        context.Entity_FinancialAlignmentProfile.Remove(efEntity);
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            isValid = true;
                            //do with trigger now
                            //new EntityManager().Delete( rowId, ref statusMessage );
                        }
                    }
                    else
                    {
                        statusMessage = "Error - delete failed, as record was not found.";
                    }
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + ".Delete()");

                    if (ex.InnerException != null && ex.InnerException.Message != null)
                    {
                        statusMessage = ex.InnerException.Message;

                        if (ex.InnerException.InnerException != null && ex.InnerException.InnerException.Message != null)
                        {
                            statusMessage = ex.InnerException.InnerException.Message;
                        }
                    }
                    if (statusMessage.ToLower().IndexOf("the delete statement conflicted with the reference constraint") > -1)
                    {
                        statusMessage = "Error: this Financial Alignment cannot be deleted as it is being referenced by other items, such as roles or credentials. These associations must be removed before this Financial Alignment can be deleted.";
                    }
                }
            }

            return(isValid);
        }
Example #19
0
        /// <summary>
        /// Delete an Occupation, and related Entity
        /// </summary>
        /// <param name="id"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Delete(int id, ref string statusMessage)
        {
            bool isValid = false;

            if (id == 0)
            {
                statusMessage = "Error - missing an identifier for the Occupation";
                return(false);
            }

            using (var context = new EntityContext())
            {
                try
                {
                    context.Configuration.LazyLoadingEnabled = false;
                    DBEntity efEntity = context.OccupationProfile
                                        .SingleOrDefault(s => s.Id == id);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //need to remove from Entity.
                        //could use a pre-delete trigger?
                        //what about roles

                        context.OccupationProfile.Remove(efEntity);
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            isValid = true;
                            //add pending delete request
                            List <String> messages = new List <string>();
                            new SearchPendingReindexManager().AddDeleteRequest(CodesManager.ENTITY_TYPE_OCCUPATIONS_PROFILE, id, ref messages);
                            //
                            //new SearchPendingReindexManager().Add( CodesManager.ENTITY_TYPE_ORGANIZATION, orgId, 1, ref messages );
                            //also check for any relationships
                            //new Entity_AgentRelationshipManager().ReindexAgentForDeletedArtifact( orgUid );
                        }
                    }
                    else
                    {
                        statusMessage = "Error - Occupation_Delete failed, as record was not found.";
                    }
                }
                catch (Exception ex)
                {
                    statusMessage = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + ".Occupation_Delete()");

                    if (statusMessage.ToLower().IndexOf("the delete statement conflicted with the reference constraint") > -1)
                    {
                        statusMessage = "Error: this Occupation cannot be deleted as it is being referenced by other items, such as roles or credentials. These associations must be removed before this Occupation can be deleted.";
                    }
                }
            }
            return(isValid);
        }
Example #20
0
        /// <summary>
        /// add a ConditionProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, DateTime updateDate, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                try
                {
                    MapToDB(entity, efEntity);

                    efEntity.EntityId = entity.EntityId;
                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }
                    efEntity.Created = efEntity.LastUpdated = updateDate;

                    context.Entity_AggregateDataProfile.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;

                        UpdateParts(entity, updateDate, ref status);

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        status.AddWarning("Error - the profile was not saved. ");
                        string message = string.Format("{0}.Add() Failed", "Attempted to add a AggregateDataProfile. The process appeared to not work, but was not an exception, so we have no message, or no clue. AggregateDataProfile. EntityId: {1}", thisClassName, entity.EntityId);
                        EmailManager.NotifyAdmin(thisClassName + ".Add() Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, "AggregateDataProfileManager.Add()", string.Format("EntityId: 0   ", entity.EntityId));
                    status.AddWarning(message);
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(), EntityId: {0}", entity.EntityId));
                }
            }

            return(efEntity.Id);
        }
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;

            //Entity parent = EntityManager.GetEntity( parentUid );
            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }
            try
            {
                using (var context = new EntityContext())
                {
                    var results = context.Entity_ProcessProfile.Where(s => s.EntityId == parent.Id)
                                  .ToList();
                    if (results == null || results.Count == 0)
                    {
                        return(true);
                    }

                    foreach (var item in results)
                    {
                        //21-03-31 mp - just removing the profile will not remove its entity and the latter's children!
                        string statusMessage = "";
                        new EntityManager().Delete(item.RowId, string.Format("ProcessProfile: {0} for EntityType: {1} ({2})", item.Id, parent.EntityTypeId, parent.EntityBaseId), ref statusMessage);

                        context.Entity_ProcessProfile.Remove(item);
                        var count = context.SaveChanges();
                        if (count > 0)
                        {
                        }
                    }
                    //context.Entity_ProcessProfile.RemoveRange( context.Entity_ProcessProfile.Where( s => s.EntityId == parent.Id ) );
                    //int count = context.SaveChanges();
                    //if ( count > 0 )
                    //{
                    //	isValid = true;
                    //}
                    //else
                    //{
                    //	//if doing a delete on spec, may not have been any properties
                    //}
                }
            }
            catch (Exception ex)
            {
                var msg = BaseFactory.FormatExceptions(ex);
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. ParentType: {0}, baseId: {1}, exception: {2}", parent.EntityType, parent.EntityBaseId, msg));
            }


            return(isValid);
        }
Example #22
0
        public int Add(ThisEntity entity, ref List <string> messages)
        {
            DBEntity efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                try
                {
                    //won't have ctid if encountered exception
                    efEntity.Ctid              = entity.Ctid ?? "";
                    efEntity.EntityTypedId     = entity.EntityTypedId;
                    efEntity.DocumentUpdatedAt = entity.DocumentUpdatedAt;
                    efEntity.EnvelopeId        = entity.EnvelopeId;
                    //efEntity.Message = entity.Message; //See Import.Message
                    efEntity.Payload = entity.Payload;
                    //efEntity.ResourcePublicKey = entity.ResourcePublicKey;

                    efEntity.DownloadDate         = System.DateTime.Now;
                    efEntity.IsMostRecentDownload = true;

                    //set any existing downloads for this entity to not most recent
                    ResetIsMostRecentDownload(efEntity.Ctid);

                    context.Import_Staging.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id = efEntity.Id;
                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        messages.Add(thisClassName + "Error - the add was not successful. ");
                        string message = string.Format(thisClassName + ".Add() Failed", "Attempted to add a Import document. The process appeared to not work, but was not an exception, so we have no message, or no clue. EntityTypeId: {0}; EnvelopeId: {1}", entity.EntityTypedId, entity.EnvelopeId);
                        EmailManager.NotifyAdmin(thisClassName + ".Add() Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Import");
                    messages.Add("Error - the save was not successful. " + message);
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(), EntityTypeId: {0}; EnvelopeId: {1}", entity.EntityTypedId, entity.EnvelopeId));
                    messages.Add("Unexpected system error. The site administration has been notified.");
                }
            }

            return(entity.Id);
        }        //
        /// <summary>
        /// Update a Record
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Update(ThisEntity entity, ref List <String> messages)
        {
            bool isValid = false;
            int  count   = 0;

            try
            {
                if (!IsValid(entity, ref messages))
                {
                    return(false);
                }

                using (var context = new EntityContext())
                {
                    DBEntity efEntity = context.SearchPendingReindex
                                        .FirstOrDefault(s => s.Id == entity.Id);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //for updates, chances are some fields will not be in interface, don't map these (ie created stuff)
                        MapToDB(entity, efEntity);
                        if (HasStateChanged(context))
                        {
                            efEntity.LastUpdated = System.DateTime.Now;

                            count = context.SaveChanges();
                            //can be zero if no data changed
                            if (count >= 0)
                            {
                                isValid = true;
                            }
                            else
                            {
                                //?no info on error
                                messages.Add("Error - the update was not successful. ");
                                string message = string.Format(thisClassName + ".Update Failed. The process appeared to not work, but was not an exception, so we have no message, or no clue. EntityTypeId: {0}, RecordId: {1}", entity.EntityTypeId, entity.RecordId);
                                //EmailManager.NotifyAdmin( thisClassName + ". ConditionProfile_Update Failed", message );
                            }
                        }
                    }
                    else
                    {
                        messages.Add("Error - update failed, as record was not found.");
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Update. EntityTypeId: {0}, RecordId: {1}", entity.EntityTypeId, entity.RecordId));
            }


            return(isValid);
        }
Example #24
0
        /// <summary>
        /// Delete all relationships for parent - FOR REFERENCES, DELETE ACTUAL TransferValueProfile AS WELL
        /// NOTE: there should be a check for reference entities, and delete if no other references.
        /// OR: have a clean up process to delete orphans.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }
            using (var context = new EntityContext())
            {
                //check if target is a reference object and is only in use here
                var results = context.Entity_TransferValueProfile
                              .Where(s => s.EntityId == parent.Id)
                              .OrderBy(s => s.TransferValueProfile.Name)
                              .ToList();
                if (results == null || results.Count == 0)
                {
                    return(true);
                }

                foreach (var item in results)
                {
                    //if a reference, delete actual TransferValueProfile if not used elsewhere
                    if (item.TransferValueProfile != null && item.TransferValueProfile.EntityStateId == 2)
                    {
                        //do a getall for the current TransferValueProfileId. If the TransferValueProfile is only referenced once, delete the TransferValueProfile as well.
                        var exists = context.Entity_TransferValueProfile
                                     .Where(s => s.TransferValueProfileId == item.TransferValueProfileId)
                                     .ToList();
                        if (exists != null && exists.Count() == 1)
                        {
                            var statusMsg = "";
                            //this method will also add pending reques to remove from elastic.
                            //20-11-11 mp - BE CLEAR - ONLY DONE FOR A REFERENCE
                            //actually this delete will probably also delete the Entity_TransferValueProfile
                            //new TransferValueProfileManager().Delete( item.TransferValueProfileId, ref statusMsg );
                            //continue;
                        }
                    }
                    context.Entity_TransferValueProfile.Remove(item);
                    count = context.SaveChanges();
                    if (count > 0)
                    {
                    }
                }
            }

            return(isValid);
        }
        /// <summary>
        /// Delete all relationships for parent
        /// NOTE: there should be a check for reference entities, and delete if no other references.
        /// OR: have a clean up process to delete orphans.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }
            using (var context = new EntityContext())
            {
                //check if target is a reference object and is only in use here
                var results = context.Entity_LearningOpportunity
                              .Where(s => s.EntityId == parent.Id)
                              .OrderBy(s => s.LearningOpportunity.Name)
                              .ToList();
                if (results == null || results.Count == 0)
                {
                    return(true);
                }

                foreach (var item in results)
                {
                    //if a reference, delete actual LearningOpportunity if not used elsewhere
                    if (item.LearningOpportunity != null && item.LearningOpportunity.EntityStateId == 2)
                    {
                        //do a getall. If only one, delete it.
                        var exists = context.Entity_LearningOpportunity
                                     .Where(s => s.LearningOpportunityId == item.LearningOpportunityId)
                                     .ToList();
                        if (exists != null && exists.Count() == 1)
                        {
                            var statusMsg = "";
                            //this method will also add pending request to remove from elastic.
                            //20-12-18 mp - Only done for a reference lopp but what about a full lopp that may now be an orphan? We are not allowing lopps without parent, but will still exist in registry!!!
                            //actually this delete will probably also delete the Entity_LearningOpportunity
                            //new LearningOpportunityManager().Delete( item.LearningOpportunityId, ref statusMsg );
                            //continue;
                        }
                    }
                    context.Entity_LearningOpportunity.Remove(item);
                    count = context.SaveChanges();
                    if (count > 0)
                    {
                    }
                }
            }

            return(isValid);
        }
Example #26
0
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;

            //Entity parent = EntityManager.GetEntity( parentUid );
            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }
            try
            {
                using (var context = new EntityContext())
                {
                    var results = context.Entity_Assertion.Where(s => s.EntityId == parent.Id)
                                  .ToList();
                    if (results == null || results.Count == 0)
                    {
                        return(true);
                    }
                    foreach (var item in results)
                    {
                        context.Entity_Assertion.Remove(item);
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            isValid = true;
                        }
                        else
                        {
                            //if doing a delete on spec, may not have been any properties
                        }
                    }
                    //context.Entity_Assertion.RemoveRange( context.Entity_Assertion.Where( s => s.EntityId == parent.Id ) );
                    //int count = context.SaveChanges();
                    //if ( count > 0 )
                    //{
                    //	isValid = true;
                    //}
                    //else
                    //{
                    //	//if doing a delete on spec, may not have been any properties
                    //}
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".DeleteAll( Entity parent, ref SaveStatus status )");
            }
            return(isValid);
        }
Example #27
0
        private bool Save(ThisEntity item, Entity parent, DateTime updateDate, ref SaveStatus status)
        {
            bool isValid = true;

            item.EntityId = parent.Id;

            using (var context = new EntityContext())
            {
                if (!ValidateProfile(item, ref status))
                {
                    return(false);
                }

                //should always be add if always resetting the entity
                if (item.Id > 0)
                {
                    DBEntity p = context.Entity_AggregateDataProfile
                                 .FirstOrDefault(s => s.Id == item.Id);
                    if (p != null && p.Id > 0)
                    {
                        item.RowId    = p.RowId;
                        item.EntityId = p.EntityId;
                        MapToDB(item, p);

                        if (HasStateChanged(context))
                        {
                            p.LastUpdated = System.DateTime.Now;
                            context.SaveChanges();
                        }
                        //regardless, check parts
                        isValid = UpdateParts(item, updateDate, ref status);
                    }
                    else
                    {
                        //error should have been found
                        isValid = false;
                        status.AddWarning(string.Format("Error: the requested record was not found: recordId: {0}", item.Id));
                    }
                }
                else
                {
                    int newId = Add(item, updateDate, ref status);
                    if (newId == 0 || status.HasErrors)
                    {
                        isValid = false;
                    }
                }
            }
            return(isValid);
        }
Example #28
0
        }        //

        /// <summary>
        /// Delete all properties for parent (in preparation for import)
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool DeleteAll(Entity parent, ref SaveStatus status)
        {
            bool isValid = true;

            //Entity parent = EntityManager.GetEntity( parentUid );
            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the provided target parent entity was not provided.");
                return(false);
            }

            using (var context = new EntityContext())
            {
                var results = context.Entity_ReferenceFramework
                              .Where(s => s.EntityId == parent.Id)
                              .OrderBy(s => s.CategoryId)
                              .ThenBy(s => s.Created)
                              .ToList();
                if (results == null || !results.Any())
                {
                    return(true);
                }

                try
                {
                    context.Entity_ReferenceFramework.RemoveRange(results);
                    //context.Entity_ReferenceFramework.RemoveRange( context.Entity_ReferenceFramework.Where( s => s.EntityId == parent.Id ) );
                    //attempt to address DbUpdateConcurrencyException
                    context.SaveChanges();
                }
                catch (Exception cex)
                {
                    isValid = false;

                    // Update the values of the entity that failed to save from the store
                    //don't want this
                    //cex.Entries.Single().Reload();
                    //OR
                    // Update original values from the database
                    //Don't think this is what we want either.
                    //var entry = cex.Entries.Single();
                    //entry.OriginalValues.SetValues( entry.GetDatabaseValues() );

                    var msg = BaseFactory.FormatExceptions(cex);
                    LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. ParentType: {0}, baseId: {1}, DbUpdateConcurrencyException: {2}", parent.EntityType, parent.EntityBaseId, msg));
                }
            }

            return(isValid);
        }
Example #29
0
        /// <summary>
        /// Add an Entity mirror
        /// NOTE: ALL ENTITY ADDS WOULD NORMALLY BE DONE VIA TRIGGERS.
        /// However, as on import, we want to delete all the child entities for a top level entity like credential. The latter is accomplished by deleting the Entity. We then need to re- add the Entity.
        /// </summary>
        /// <param name="entityUid">RowId of the base Object</param>
        /// <param name="baseId">Integer PK of the base object</param>
        /// <param name="entityTypeId"></param>
        /// <param name="baseName"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        private int Add(Guid entityUid, int baseId, int entityTypeId, string baseName, ref string statusMessage)
        {
            DBentity efEntity = new DBentity();

            using (var context = new EntityContext())
            {
                try
                {
                    efEntity.EntityUid      = entityUid;
                    efEntity.EntityBaseId   = baseId;
                    efEntity.EntityTypeId   = entityTypeId;
                    efEntity.EntityBaseName = baseName;
                    efEntity.Created        = efEntity.LastUpdated = System.DateTime.Now;

                    context.Entity.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        statusMessage = "successful";

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        statusMessage = "Error - the add was not successful. ";
                        string message = thisClassName + string.Format(". Add Failed", "Attempted to add an Entity. The process appeared to not work, but was not an exception, so we have no message, or no clue. entityUid: {0}, entityTypeId: {1}", entityUid.ToString(), entityTypeId);
                        EmailManager.NotifyAdmin("AssessmentManager. Assessment_Add Failed", message);
                        return(0);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Entity");
                    statusMessage = "Error - the save was not successful. " + message;
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(). entityUid: {0}, entityTypeId: {1}", entityUid.ToString(), entityTypeId));
                }
            }

            return(0);
        }
Example #30
0
        }//

        public int AddMessages(SaveStatus entity, int parentId, ref List <string> messages)
        {
            ImportMessage efEntity = new ImportMessage();
            int           msgCount = 0;

            using (var context = new EntityContext())
            {
                try
                {
                    if (entity.Messages == null || entity.Messages.Count == 0)
                    {
                        return(0);
                    }

                    foreach (StatusMessage msg in entity.Messages)
                    {
                        efEntity          = new ImportMessage();
                        efEntity.ParentId = parentId;
                        if (!string.IsNullOrWhiteSpace(msg.Message))
                        {
                            efEntity.Message = msg.Message.Substring(0, (msg.Message.Length < 500 ? msg.Message.Length - 1 : 500));
                        }
                        efEntity.Severity = msg.IsWarning ? 1 : 2;
                        efEntity.Created  = System.DateTime.Now;

                        context.Import_Message.Add(efEntity);
                        int count = context.SaveChanges();
                        if (count < 1)
                        {
                            messages.Add("Error - the add was not successful, no reason. ");
                        }
                        else
                        {
                            msgCount++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".AddMessages(), Failed for ImportId: {0}; ", parentId));
                    messages.Add(thisClassName + string.Format(".AddMessages(), Failed for ImportId: {0}; message: {1}", parentId, ex.Message));
                }
            }

            return(msgCount);
        }