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 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 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);
        }
        public bool UpdateProperties(ThisEntity entity, Entity relatedEntity, ref SaveStatus status)
        {
            bool isAllValid           = true;
            EntityPropertyManager mgr = new EntityPropertyManager();

            //first clear all propertiesd
            //mgr.DeleteAll( relatedEntity, ref status );
            //Entity_ReferenceManager erm = new Entity_ReferenceManager();
            //already did a deleteAll in UpdateParts

            return(isAllValid);
        }
        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;
            }
        }
        public bool UpdateParts(ThisEntity entity, ref SaveStatus status)
        {
            bool   isAllValid    = true;
            Entity relatedEntity = EntityManager.GetEntity(entity.RowId);

            if (relatedEntity == null || relatedEntity.Id == 0)
            {
                status.AddError("Error - the related Entity was not found.");
                return(false);
            }

            if (UpdateProperties(entity, relatedEntity, ref status) == false)
            {
                isAllValid = false;
            }

            //Entity_ReferenceFrameworkManager erfm = new Entity_ReferenceFrameworkManager();
            //erfm.DeleteAll( relatedEntity, ref status );

            //if ( erfm.SaveList( relatedEntity.Id, CodesManager.PROPERTY_CATEGORY_SOC, entity.Jobs, ref status ) == false )
            //	isAllValid = false;
            //if ( erfm.SaveList( relatedEntity.Id, CodesManager.PROPERTY_CATEGORY_NAICS, entity.Industries, ref status ) == false )
            //	isAllValid = false;


            //Entity_ReferenceManager erm = new Entity_ReferenceManager();
            //erm.DeleteAll( relatedEntity, ref status );
            //if ( erm.Add( entity.Subject, entity.RowId, CodesManager.ENTITY_TYPE_Job_PROFILE, ref status, CodesManager.PROPERTY_CATEGORY_SUBJECT, false ) == false )
            //	isAllValid = false;

            //if ( erm.Add( entity.Keyword, entity.RowId, CodesManager.ENTITY_TYPE_Job_PROFILE, ref status, CodesManager.PROPERTY_CATEGORY_KEYWORD, false ) == false )
            //	isAllValid = false;


            AddProfiles(entity, relatedEntity, ref status);


            return(isAllValid);
        }
        }         //

        #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 ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;


            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                //status.AddWarning( "An Job Description must be entered" );
            }


            if (string.IsNullOrWhiteSpace(profile.SubjectWebpage))
            {
                status.AddWarning("Error - A Subject Webpage name must be entered");
            }

            else if (!IsUrlValid(profile.SubjectWebpage, ref commonStatusMessage))
            {
                status.AddWarning("The Job Subject Webpage is invalid. " + commonStatusMessage);
            }


            return(status.WasSectionValid);
        }
        public static List <ThisEntity> Search(string pFilter, string pOrderBy, int pageNumber, int pageSize, ref int pTotalRows, bool autocomplete = false)
        {
            string            connectionString = DBConnectionRO();
            ThisEntity        item             = new ThisEntity();
            List <ThisEntity> list             = new List <ThisEntity>();
            var    result = new DataTable();
            string temp   = "";
            string org    = "";
            int    orgId  = 0;

            using (SqlConnection c = new SqlConnection(connectionString))
            {
                c.Open();

                if (string.IsNullOrEmpty(pFilter))
                {
                    pFilter = "";
                }

                using (SqlCommand command = new SqlCommand("[Job_Search]", c))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@Filter", pFilter));
                    command.Parameters.Add(new SqlParameter("@SortOrder", pOrderBy));
                    command.Parameters.Add(new SqlParameter("@StartPageIndex", pageNumber));
                    command.Parameters.Add(new SqlParameter("@PageSize", pageSize));

                    SqlParameter totalRows = new SqlParameter("@TotalRows", pTotalRows);
                    totalRows.Direction = ParameterDirection.Output;
                    command.Parameters.Add(totalRows);
                    try
                    {
                        using (SqlDataAdapter adapter = new SqlDataAdapter())
                        {
                            adapter.SelectCommand = command;
                            adapter.Fill(result);
                        }
                        string rows = command.Parameters[command.Parameters.Count - 1].Value.ToString();

                        pTotalRows = Int32.Parse(rows);
                    }
                    catch (Exception ex)
                    {
                        pTotalRows = 0;
                        LoggingHelper.LogError(ex, thisClassName + string.Format(".Search() - Execute proc, Message: {0} \r\n Filter: {1} \r\n", ex.Message, pFilter));

                        item             = new Job();
                        item.Name        = "Unexpected error encountered. System administration has been notified. Please try again later. ";
                        item.Description = ex.Message;

                        list.Add(item);
                        return(list);
                    }
                }

                foreach (DataRow dr in result.Rows)
                {
                    item              = new ThisEntity();
                    item.Id           = GetRowColumn(dr, "Id", 0);
                    item.Name         = GetRowColumn(dr, "Name", "missing");
                    item.FriendlyName = FormatFriendlyTitle(item.Name);
                    //for autocomplete, only need name
                    if (autocomplete)
                    {
                        list.Add(item);
                        continue;
                    }

                    item.Description = GetRowColumn(dr, "Description", "");
                    string rowId = GetRowColumn(dr, "RowId");
                    item.RowId = new Guid(rowId);

                    item.SubjectWebpage       = GetRowColumn(dr, "SubjectWebpage", "");
                    item.CTID                 = GetRowPossibleColumn(dr, "CTID", "");
                    item.CredentialRegistryId = GetRowPossibleColumn(dr, "CredentialRegistryId", "");



                    //org = GetRowPossibleColumn( dr, "Organization", "" );
                    //orgId = GetRowPossibleColumn( dr, "OrgId", 0 );
                    //if ( orgId > 0 )
                    //	item.OwningOrganization = new Organization() { Id = orgId, Name = org };

                    //
                    //temp = GetRowColumn( dr, "DateEffective", "" );
                    //if ( IsValidDate( temp ) )
                    //	item.DateEffective = DateTime.Parse( temp ).ToString("yyyy-MM-dd");
                    //else
                    //	item.DateEffective = "";

                    item.Created     = GetRowColumn(dr, "Created", System.DateTime.MinValue);
                    item.LastUpdated = GetRowColumn(dr, "LastUpdated", System.DateTime.MinValue);

                    list.Add(item);
                }

                return(list);
            }
        }         //
 public void AddProfiles(ThisEntity entity, Entity relatedEntity, ref SaveStatus status)
 {
 }         //
        /// <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);
        }