public static ThisEntity GetBySubjectWebpage(string swp)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                context.Configuration.LazyLoadingEnabled = false;
                DBEntity from = context.JobProfile
                                .FirstOrDefault(s => s.SubjectWebpage.ToLower() == swp.ToLower());

                if (from != null && from.Id > 0)
                {
                    entity.RowId          = from.RowId;
                    entity.Id             = from.Id;
                    entity.Name           = from.Name;
                    entity.EntityStateId  = from.EntityStateId;
                    entity.Description    = from.Description;
                    entity.SubjectWebpage = from.SubjectWebpage;

                    entity.CTID = from.CTID;
                    //entity.CredentialRegistryId = from.CredentialRegistryId;
                }
            }
            return(entity);
        }
        public static void MapFromDB(DBEntity input, ThisEntity output,
                                     bool includingProperties)
        {
            input.Id            = output.Id;
            input.RowId         = output.RowId;
            input.EntityStateId = output.EntityStateId;

            //
            input.Name        = output.Name;
            input.Description = output.Description == null ? "" : output.Description;
            input.CTID        = output.CTID;

            input.SubjectWebpage = output.SubjectWebpage;
            if (IsValidDate(output.Created))
            {
                input.Created = ( DateTime )output.Created;
            }
            if (IsValidDate(output.LastUpdated))
            {
                input.LastUpdated = ( DateTime )output.LastUpdated;
            }


            //=====
            //var relatedEntity = EntityManager.GetEntity( input.RowId, false );
            //if ( relatedEntity != null && relatedEntity.Id > 0 )
            //	input.EntityLastUpdated = relatedEntity.LastUpdated;
        }         //
        //public static List<ThisEntity> GetAll( ref int totalRecords, int maxRecords = 100 )
        //{
        //	List<ThisEntity> list = new List<ThisEntity>();
        //	ThisEntity entity = new ThisEntity();
        //	using ( var context = new EntityContext() )
        //	{
        //		List<DBEntity> results = context.JobProfile
        //					 .Where( s => s.EntityStateId > 2 )
        //					 .OrderBy( s => s.Name )
        //					 .ToList();
        //		if ( results != null && results.Count > 0 )
        //		{
        //			totalRecords = results.Count();

        //			foreach ( DBEntity item in results )
        //			{
        //				entity = new ThisEntity();
        //				MapFromDB( item, entity, false );
        //				list.Add( entity );
        //				if ( maxRecords > 0 && list.Count >= maxRecords )
        //					break;
        //			}
        //		}
        //	}

        //	return list;
        //}
        public static ThisEntity GetForDetail(int id)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.JobProfile
                                .SingleOrDefault(s => s.Id == id);

                if (item != null && item.Id > 0)
                {
                    //check for virtual deletes
                    if (item.EntityStateId == 0)
                    {
                        return(entity);
                    }

                    MapFromDB(item, entity,
                              true                           //includingProperties
                              );
                }
            }

            return(entity);
        }
        /// <summary>
        /// Delete an Job, 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 Job";
                return(false);
            }

            using (var context = new EntityContext())
            {
                try
                {
                    context.Configuration.LazyLoadingEnabled = false;
                    DBEntity efEntity = context.JobProfile
                                        .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.JobProfile.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 - Job_Delete failed, as record was not found.";
                    }
                }
                catch (Exception ex)
                {
                    statusMessage = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + ".Job_Delete()");

                    if (statusMessage.ToLower().IndexOf("the delete statement conflicted with the reference constraint") > -1)
                    {
                        statusMessage = "Error: this Job cannot be deleted as it is being referenced by other items, such as roles or credentials. These associations must be removed before this Job can be deleted.";
                    }
                }
            }
            return(isValid);
        }
        public static ThisEntity GetBasic(int id)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.JobProfile
                                .SingleOrDefault(s => s.Id == id);

                if (item != null && item.Id > 0)
                {
                    MapFromDB(item, entity, false);
                }
            }

            return(entity);
        }
        public static ThisEntity GetByName_SubjectWebpage(string name, string swp)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                context.Configuration.LazyLoadingEnabled = false;
                DBEntity from = context.JobProfile
                                .FirstOrDefault(s => s.Name.ToLower() == name.ToLower() && s.SubjectWebpage == swp);

                if (from != null && from.Id > 0)
                {
                    MapFromDB(from, entity, false);
                }
            }
            return(entity);
        }
        }         //

        public static void MapToDB(ThisEntity input, DBEntity output)
        {
            //want output ensure fields input create are not wiped
            if (output.Id == 0)
            {
                output.CTID = input.CTID;
            }
            //if ( !string.IsNullOrWhiteSpace( input.CredentialRegistryId ) )
            //	output.CredentialRegistryId = input.CredentialRegistryId;

            output.Id           = input.Id;
            output.Name         = GetData(input.Name);
            output.Description  = GetData(input.Description);
            input.EntityStateId = output.EntityStateId;

            output.SubjectWebpage = GetUrlData(input.SubjectWebpage);

            if (IsValidDate(input.LastUpdated))
            {
                output.LastUpdated = input.LastUpdated;
            }
        }
        }         //

        #endregion

        #endregion

        #region == Retrieval =======================
        public static ThisEntity GetByCtid(string ctid)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity from = context.JobProfile
                                .FirstOrDefault(s => s.CTID.ToLower() == ctid.ToLower());

                if (from != null && from.Id > 0)
                {
                    entity.RowId          = from.RowId;
                    entity.Id             = from.Id;
                    entity.EntityStateId  = from.EntityStateId;
                    entity.Name           = from.Name;
                    entity.Description    = from.Description;
                    entity.SubjectWebpage = from.SubjectWebpage;
                    entity.CTID           = from.CTID;
                }
            }

            return(entity);
        }
        public bool Delete(string ctid, ref string statusMessage)
        {
            bool isValid = true;

            if (string.IsNullOrWhiteSpace(ctid))
            {
                statusMessage = thisClassName + ".Delete() Error - a valid CTID must be provided";
                return(false);
            }
            if (string.IsNullOrWhiteSpace(ctid))
            {
                ctid = "SKIP ME";
            }

            using (var context = new EntityContext())
            {
                try
                {
                    context.Configuration.LazyLoadingEnabled = false;
                    DBEntity efEntity = context.JobProfile
                                        .FirstOrDefault(s => (s.CTID == ctid)
                                                        );

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

                        //need to remove from Entity.
                        //-using before delete trigger - verify won't have RI issues
                        string msg = string.Format(" Job. Id: {0}, Name: {1}, Ctid: {2}.", efEntity.Id, efEntity.Name, efEntity.CTID);
                        //18-04-05 mparsons - change to set inactive, and notify - seems to have been some incorrect deletes
                        //context.JobProfile.Remove( efEntity );
                        efEntity.EntityStateId = 0;
                        efEntity.LastUpdated   = System.DateTime.Now;
                        int count = context.SaveChanges();
                        if (count > 0)
                        {
                            new ActivityManager().SiteActivityAdd(new SiteActivity()
                            {
                                ActivityType     = "JobProfile",
                                Activity         = "Import",
                                Event            = "Delete",
                                Comment          = msg,
                                ActivityObjectId = efEntity.Id
                            });
                            isValid = true;
                            //add pending request
                            List <String> messages = new List <string>();
                            new SearchPendingReindexManager().AddDeleteRequest(CodesManager.ENTITY_TYPE_OCCUPATIONS_PROFILE, efEntity.Id, ref messages);
                            //mark owning org for updates (actually should be covered by ReindexAgentForDeletedArtifact
                            //new SearchPendingReindexManager().Add( CodesManager.ENTITY_TYPE_ORGANIZATION, orgId, 1, ref messages );

                            //delete all relationships
                            workIT.Models.SaveStatus        status = new SaveStatus();
                            Entity_AgentRelationshipManager earmgr = new Entity_AgentRelationshipManager();
                            earmgr.DeleteAll(rowId, ref status);
                            //also check for any relationships
                            //There could be other orgs from relationships to be reindexed as well!

                            //also check for any relationships
                            //new Entity_AgentRelationshipManager().ReindexAgentForDeletedArtifact( orgUid );
                        }
                    }
                    else
                    {
                        statusMessage = thisClassName + ".Delete() Warning No action taken, as the record was not found.";
                    }
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + ".Delete(envelopeId)");
                    isValid       = false;
                    statusMessage = FormatExceptions(ex);
                    if (statusMessage.ToLower().IndexOf("the delete statement conflicted with the reference constraint") > -1)
                    {
                        statusMessage = "Error: this Job cannot be deleted as it is being referenced by other items, such as roles or credentials. These associations must be removed before this Job can be deleted.";
                    }
                }
            }
            return(isValid);
        }
        /// <summary>
        /// Update a Job
        /// - base only, caller will handle parts?
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

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

                    if (entity.Id > 0)
                    {
                        //TODO - consider if necessary, or interferes with anything
                        context.Configuration.LazyLoadingEnabled = false;
                        DBEntity efEntity = context.JobProfile
                                            .SingleOrDefault(s => s.Id == entity.Id);

                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //fill in fields that may not be in entity
                            entity.RowId = efEntity.RowId;

                            MapToDB(entity, efEntity);

                            //19-05-21 mp - should add a check for an update where currently is deleted
                            if ((efEntity.EntityStateId) == 0)
                            {
                                var url = string.Format(UtilityManager.GetAppKeyValue("credentialFinderSite") + "Job/{0}", efEntity.Id);
                                //notify, and???
                                //EmailManager.NotifyAdmin( "Previously Deleted Job has been reactivated", string.Format( "<a href='{2}'>Job: {0} ({1})</a> was deleted and has now been reactivated.", efEntity.Name, efEntity.Id, url ) );
                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "JobProfile",
                                    Activity         = "Import",
                                    Event            = "Reactivate",
                                    Comment          = string.Format("Job had been marked as deleted, and was reactivted by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);
                            }
                            //assume and validate, that if we get here we have a full record
                            if ((efEntity.EntityStateId) != 2)
                            {
                                efEntity.EntityStateId = 3;
                            }

                            if (IsValidDate(status.EnvelopeCreatedDate) && status.LocalCreatedDate < efEntity.Created)
                            {
                                efEntity.Created = status.LocalCreatedDate;
                            }
                            if (IsValidDate(status.EnvelopeUpdatedDate) && status.LocalUpdatedDate != efEntity.LastUpdated)
                            {
                                efEntity.LastUpdated = status.LocalUpdatedDate;
                            }
                            if (HasStateChanged(context))
                            {
                                if (IsValidDate(status.EnvelopeUpdatedDate))
                                {
                                    efEntity.LastUpdated = status.LocalUpdatedDate;
                                }
                                else
                                {
                                    efEntity.LastUpdated = DateTime.Now;
                                }
                                //NOTE efEntity.EntityStateId is set to 0 in delete method )
                                count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error
                                    isValid = false;
                                    string message = string.Format(thisClassName + ".Save Failed", "Attempted to update a Job. The process appeared to not work, but was not an exception, so we have no message, or no clue. Job: {0}, Id: {1}", entity.Name, entity.Id);
                                    status.AddError("Error - the update was not successful. " + message);
                                    EmailManager.NotifyAdmin(thisClassName + ".Save Failed Failed", message);
                                }
                            }
                            else
                            {
                                //update entity.LastUpdated - assuming there has to have been some change in related data
                                new EntityManager().UpdateModifiedDate(entity.RowId, ref status, efEntity.LastUpdated);
                            }
                            if (isValid)
                            {
                                if (!UpdateParts(entity, ref status))
                                {
                                    isValid = false;
                                }

                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "JobProfile",
                                    Activity         = "Import",
                                    Event            = "Update",
                                    Comment          = string.Format("Job was updated by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);
                            }
                        }
                        else
                        {
                            status.AddError("Error - update failed, as record was not found.");
                        }
                    }
                    else
                    {
                        //add
                        int newId = Add(entity, ref status);
                        if (newId == 0 || status.HasErrors)
                        {
                            isValid = false;
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                string message = HandleDBValidationError(dbex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name), "Job");
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name), true);
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
                isValid = false;
            }


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

            try
            {
                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.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.JobProfile.Add(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        SiteActivity sa = new SiteActivity()
                        {
                            ActivityType     = "JobProfile",
                            Activity         = "Import",
                            Event            = "Add Pending Job",
                            Comment          = string.Format("Pending Job was added by the import. ctid: {0}, registryAtId: {1}", ctid, registryAtId),
                            ActivityObjectId = efEntity.Id
                        };
                        new ActivityManager().SiteActivityAdd(sa);
                        return(efEntity.Id);
                    }

                    status = thisClassName + ".AddPendingRecord. 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 + ".AddPendingRecord. Error - the save was not successful. " + message;
            }
            return(0);
        }
        public int AddBaseReference(ThisEntity entity, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

            try
            {
                using (var context = new EntityContext())
                {
                    if (entity == null ||
                        (string.IsNullOrWhiteSpace(entity.Name))
                        //||                        string.IsNullOrWhiteSpace( entity.SubjectWebpage ))
                        )
                    {
                        status.AddError(thisClassName + ". AddBaseReference() The Job is incomplete");
                        return(0);
                    }

                    //only add DB required properties
                    //NOTE - an entity will be created via trigger
                    efEntity.EntityStateId  = 2;
                    efEntity.Name           = entity.Name;
                    efEntity.Description    = entity.Description;
                    efEntity.SubjectWebpage = entity.SubjectWebpage;

                    //
                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }
                    //set to return, just in case
                    entity.RowId = efEntity.RowId;
                    //

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

                    context.JobProfile.Add(efEntity);
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id = efEntity.Id;

                        /* handle new parts
                         * AvailableAt
                         * CreditValue
                         * EstimatedDuration
                         * OfferedBy
                         * OwnedBy
                         * assesses
                         */
                        if (UpdateParts(entity, ref status) == false)
                        {
                        }
                        return(efEntity.Id);
                    }

                    status.AddError(thisClassName + ". AddBaseReference() Error - the save was not successful, but no message provided. ");
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                status.AddError(HandleDBValidationError(dbex, thisClassName + ".AddBaseReference() ", "Job"));
                LoggingHelper.LogError(dbex, thisClassName + string.Format(".Add(), Name: {0}, UserId: {1}", entity.Name, entity.CreatedById));
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".AddBaseReference. Name:  {0}, SubjectWebpage: {1}", entity.Name, entity.SubjectWebpage));
                status.AddError(thisClassName + ". AddBaseReference() Error - the save was not successful. " + message);
            }
            return(0);
        }
        /// <summary>
        /// add a Job
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

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

                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }
                    efEntity.EntityStateId = 3;
                    if (IsValidDate(status.EnvelopeCreatedDate))
                    {
                        efEntity.Created     = status.LocalCreatedDate;
                        efEntity.LastUpdated = status.LocalCreatedDate;
                    }
                    else
                    {
                        efEntity.Created     = System.DateTime.Now;
                        efEntity.LastUpdated = System.DateTime.Now;
                    }
                    context.JobProfile.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;
                        //add log entry
                        SiteActivity sa = new SiteActivity()
                        {
                            ActivityType     = "JobProfile",
                            Activity         = "Import",
                            Event            = "Add",
                            Comment          = string.Format("Full Job was added by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                            ActivityObjectId = entity.Id
                        };
                        new ActivityManager().SiteActivityAdd(sa);
                        if (UpdateParts(entity, ref status) == false)
                        {
                        }

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error

                        string message = thisClassName + string.Format(". Add Failed", "Attempted to add a Job. The process appeared to not work, but was not an exception, so we have no message, or no clue. Job: {0}, ctid: {1}", entity.Name, entity.CTID);
                        status.AddError(thisClassName + ". Error - the add was not successful. " + message);
                        EmailManager.NotifyAdmin("JobManager. Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Job");
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. " + message);

                    LoggingHelper.LogError(message, true);
                }
                catch (Exception ex)
                {
                    string message = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(), Name: {0}\r\n", efEntity.Name), true);
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. \r\n" + message);
                }
            }

            return(efEntity.Id);
        }