Exemplo n.º 1
0
        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.Occupations, 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_Occupation_PROFILE, ref status, CodesManager.PROPERTY_CATEGORY_SUBJECT, false ) == false )
            //	isAllValid = false;

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


            AddProfiles(entity, relatedEntity, ref status);


            return(isAllValid);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Get all CompetencyFrameworks for the provided entity
        /// The returned entities are just the base
        /// </summary>
        /// <param name="parentUid"></param>
        /// <returns></returnsThisEntity
        public static List <WPM.CompetencyFramework> GetAll(Guid parentUid)
        {
            var list   = new List <WPM.CompetencyFramework>();
            var entity = new WPM.CompetencyFramework();

            Entity parent = EntityManager.GetEntity(parentUid);

            LoggingHelper.DoTrace(7, string.Format("EntityCompetencyFrameworks_GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId));

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_CompetencyFramework
                                              .Where(s => s.EntityId == parent.Id)
                                              .OrderBy(s => s.CompetencyFramework.Name)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new WPM.CompetencyFramework();
                            if (item.CompetencyFramework != null && item.CompetencyFramework.EntityStateId > 1)
                            {
                                CompetencyFrameworkManager.MapFromDB(item.CompetencyFramework, entity);
                                list.Add(entity);
                            }
                        }
                    }
                    return(list);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".EntityCompetencyFrameworks_GetAll. Guid: {0}, parentType: {1} ({2}), ", parentUid, parent.EntityType, parent.EntityBaseId));
            }
            return(list);
        }
        public static void MapFromDB(DBEntity from, ThisEntity to, bool includingComponents = false)
        {
            to.Id                = from.Id;
            to.RowId             = from.RowId;
            to.ParentComponentId = from.ParentComponentId;
            to.Name              = from.Name;
            to.Description       = from.Description;
            to.PathwayCTID       = from.PathwayCTID;

            to.RelatedEntity = EntityManager.GetEntity(to.RowId, false);
            if (to.RelatedEntity != null && to.RelatedEntity.Id > 0)
            {
                to.EntityLastUpdated = to.RelatedEntity.LastUpdated;
            }

            if (from.PathwayComponent != null && from.PathwayComponent.Id > 0)
            {
                //assign parent pathway component
            }
            to.RequiredNumber = from.RequiredNumber != null ? ( int )from.RequiredNumber : 0;
            //
            if (IsValidDate(from.Created))
            {
                to.Created = ( DateTime )from.Created;
            }
            if (IsValidDate(from.LastUpdated))
            {
                to.LastUpdated = ( DateTime )from.LastUpdated;
            }

            //components
            //actually may always want these, but a list (shallow get) of components
            if (includingComponents)
            {
                //get all target components
                //do we want a deep get or summary? Likely summary here
                to.TargetComponent = Entity_PathwayComponentManager.GetAll(to.RowId, PathwayComponent.PathwayComponentRelationship_TargetComponent, PathwayComponentManager.componentActionOfSummary);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Get all ContactPoint for the parent
        /// Uses the parent Guid to retrieve the related Entity, then uses the ParentEntityId to retrieve the child objects.
        /// </summary>
        /// <param name="parentUid"></param>
        public static List <ThisEntity> GetAll(Guid parentUid)
        {
            ThisEntity        entity = new ThisEntity();
            List <ThisEntity> list   = new List <ThisEntity>();
            //Views.Entity_Summary parent = EntityManager.GetDBEntity( parentUid );
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                return(list);
            }

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_ContactPoint
                                              .Where(s => s.ParentEntityId == parent.Id)
                                              .OrderBy(s => s.Id)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new ThisEntity();
                            MapFromDB(item, entity, true);
                            list.Add(entity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".GetAll");
            }
            return(list);
        }        //
        }        //

        public static List <ThisEntity> GetAll(Guid parentUid, int processProfileTypeId)
        {
            ThisEntity        entity = new ThisEntity();
            List <ThisEntity> list   = new List <ThisEntity>();
            Entity            parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                return(list);
            }

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_ProcessProfile
                                              .Where(s => s.EntityId == parent.Id && s.ProcessTypeId == processProfileTypeId)
                                              .OrderBy(s => s.Id)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new ThisEntity();
                            MapFromDB(item, entity, true, false);
                            list.Add(entity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".GetAll( parentEntityType:{0}, parentBaseId: {1}, processProfileTypeId: {2} )", parent.EntityType, parent.EntityBaseId, processProfileTypeId));
            }
            return(list);
        }        //
        }        //

        /// <summary>
        /// Only retrieve summary information with counts, no details
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="getForList"></param>
        /// <returns></returns>
        public static List <CodeItem> GetAllSummary(Guid parentUid)
        {
            ThisEntity      entity = new ThisEntity();
            List <CodeItem> list   = new List <CodeItem>();
            Entity          parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                return(list);
            }

            try
            {
                using (var context = new EntityContext())
                {
                    context.Configuration.LazyLoadingEnabled = false;

                    var query = from p in context.Entity_ProcessProfile
                                from code in context.Codes_ProcessProfileType
                                .Where(m => m.Id == p.ProcessTypeId)
                                where p.EntityId == parent.Id
                                group p by new { code.Name, code.Id } into g
                        select new CodeItem
                    {
                        Name   = g.Key.Name,
                        Id     = g.Key.Id,
                        Totals = g.Count()
                    };
                    list = query.OrderBy(m => m.Name).ToList();
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".GetAll");
            }
            return(list);
        }        //
Exemplo n.º 7
0
        /// <summary>
        /// Get all assessments for the provided entity
        /// The returned entities are just the base
        /// </summary>
        /// <param name="parentUid"></param>
        /// <returns></returnsThisEntity
        public static List <ThisEntity> GetAll(Guid parentUid, int identityValueTypeId)
        {
            List <ThisEntity> list   = new List <ThisEntity>();
            ThisEntity        entity = new ThisEntity();

            Entity parent = EntityManager.GetEntity(parentUid);

            LoggingHelper.DoTrace(7, string.Format(thisClassName + ".GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId));

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_IdentifierValue
                                              .Where(s => s.EntityId == parent.Id && s.IdentityValueTypeId == identityValueTypeId)
                                              .OrderBy(s => s.Name)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new ThisEntity();
                            MapFromDB(item, entity);
                            list.Add(entity);
                        }
                    }
                    return(list);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".GetAll");
            }
            return(list);
        }
Exemplo n.º 8
0
        public bool UpdateParts(ThisEntity entity, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            Entity relatedEntity = EntityManager.GetEntity(entity.RowId);

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

            //ConditionProfile
            Entity_ConditionProfileManager emanager = new Entity_ConditionProfileManager();

            emanager.DeleteAll(relatedEntity, ref status);

            emanager.SaveList(entity.Requires, Entity_ConditionProfileManager.ConnectionProfileType_Requirement, entity.RowId, ref status);
            emanager.SaveList(entity.Recommends, Entity_ConditionProfileManager.ConnectionProfileType_Recommendation, entity.RowId, ref status);
            emanager.SaveList(entity.Corequisite, Entity_ConditionProfileManager.ConnectionProfileType_Corequisite, entity.RowId, ref status);
            emanager.SaveList(entity.EntryCondition, Entity_ConditionProfileManager.ConnectionProfileType_EntryCondition, entity.RowId, ref status);
            emanager.SaveList(entity.Renewal, Entity_ConditionProfileManager.ConnectionProfileType_Renewal, entity.RowId, ref status);

            return(!status.HasSectionErrors);
        }         //
Exemplo n.º 9
0
        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 for financial assistance profile.");
                return(false);
            }

            EntityPropertyManager mgr = new EntityPropertyManager();

            //first clear all properties
            mgr.DeleteAll(relatedEntity, ref status);

            if (mgr.AddProperties(entity.FinancialAssistanceType, entity.RowId, CodesManager.ENTITY_TYPE_FINANCIAL_ASST_PROFILE, CodesManager.PROPERTY_CATEGORY_FINANCIAL_ASSISTANCE, false, ref status) == false)
            {
                isAllValid = false;
            }


            return(isAllValid);
        }         //
Exemplo n.º 10
0
        public bool SaveList(List <ThisEntity> list, Guid parentUid, int IdentityValueTypeId, ref SaveStatus status, bool doingDelete)
        {
            if (!IsValidGuid(parentUid))
            {
                status.AddError(string.Format("A valid parent identifier was not provided to the {0}.Add method.", thisClassName));
                return(false);
            }


            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError("Error - the parent entity was not found.");
                return(false);
            }
            if (doingDelete)
            {
                DeleteAll(parent, ref status);
            }

            if (list == null || list.Count == 0)
            {
                return(true);
            }

            bool isAllValid = true;

            foreach (ThisEntity item in list)
            {
                item.IdentityValueTypeId = IdentityValueTypeId;
                Add(parent, item, ref status);
            }

            return(isAllValid);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Add an Entity assessment
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="assessmentId"></param>
        /// <param name="relationshipTypeId"></param>
        /// <param name="allowMultiples">If false, check if an assessment exists. If found, do an update</param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public int Add(Guid parentUid,
                       int assessmentId, int relationshipTypeId,
                       bool allowMultiples,
                       ref SaveStatus status)
        {
            int id    = 0;
            int count = 0;

            if (assessmentId == 0)
            {
                status.AddError(string.Format("A valid Assessment identifier was not provided to the {0}.EntityAssessment_Add method.", thisClassName));
                return(0);
            }
            if (relationshipTypeId == 0)
            {
                relationshipTypeId = 1;
            }

            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
                {
                    //first check for duplicates
                    efEntity = context.Entity_Assessment
                               .FirstOrDefault(s => s.EntityId == parent.Id && s.AssessmentId == assessmentId && s.RelationshipTypeId == relationshipTypeId);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //status.AddError( string.Format( "Error - this Assessment has already been added to this profile.", thisClassName ) );
                        return(0);
                    }

                    if (allowMultiples == false)
                    {
                        //check if one exists, and replace if found
                        //efEntity = context.Entity_Assessment
                        //	.FirstOrDefault( s => s.EntityId == parent.Id  );
                        //if ( efEntity != null && efEntity.Id > 0 )
                        //{
                        //	efEntity.AssessmentId = assessmentId;

                        //	count = context.SaveChanges();
                        //	return efEntity.Id;
                        //}
                    }
                    efEntity                    = new DBEntity();
                    efEntity.EntityId           = parent.Id;
                    efEntity.AssessmentId       = assessmentId;
                    efEntity.RelationshipTypeId = relationshipTypeId > 0 ? relationshipTypeId : 1;
                    efEntity.Created            = System.DateTime.Now;

                    context.Entity_Assessment.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(thisClassName + "Error - the add was not successful.");
                        string message = thisClassName + string.Format(".Add Failed", "Attempted to add a Assessment 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}, assessmentId: {2}", parentUid, parent.EntityType, assessmentId);
                        EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Entity_Assessment");
                    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);
        }
        } //

        //public bool AddLanguage( string textValue,
        //	   int entityId,
        //	   ref SaveStatus status,
        //	   int categoryId )
        //{
        //	if ( string.IsNullOrWhiteSpace( textValue ) )
        //	{
        //		return true;
        //	}
        //	using ( var context = new EntityContext() )
        //	{
        //		EnumeratedItem code = new EnumeratedItem();
        //		code = CodesManager.GetLanguage( textValue );
        //		if ( code.Id > 0 )
        //		{
        //			textValue = string.Format( "{0} ({1})", code.Name, code.Value );
        //			AddTextValue( textValue, entityId, ref status, categoryId );
        //		}

        //		else
        //		{
        //			status.AddWarning( thisClassName + string.Format( ". Warning - the langugage code was not found. parentUid: {0}, languagecode: {1}", entityId, textValue ) );
        //		}
        //	}
        //	return true;
        //}
        /// <summary>
        /// Persist Entity Reference
        /// </summary>
        /// <param name="profiles"></param>
        /// <param name="parentUid"></param>
        /// <param name="parentTypeId"></param>
        /// <param name="status"></param>
        /// <param name="categoryId"></param>
        /// <param name="isTitleRequired">If true, a title must exist</param>
        /// <returns></returns>
        public bool Add(List <ThisEntity> profiles,
                        Guid parentUid,
                        int parentTypeId,
                        ref SaveStatus status,
                        int categoryId,
                        bool isTitleRequired)
        {
            if (profiles == null || profiles.Count == 0)
            {
                return(true);
            }

            bool isValid = true;

            status.HasSectionErrors = false;

            if (!IsValidGuid(parentUid))
            {
                status.AddError("Error: the parent identifier was not provided.");
            }
            if (parentTypeId == 0)
            {
                status.AddError("Error: the parent type was not provided.");
            }
            if (status.HasSectionErrors)
            {
                return(false);
            }

            int count = 0;

            if (profiles == null)
            {
                profiles = new List <ThisEntity>();
            }

            DBEntity efEntity = new DBEntity();

            //Views.Entity_Summary parent2 = EntityManager.GetDBEntity( parentUid );
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + string.Format(". Error - the parent entity was not found. parentUid: {0}", parentUid));
                return(false);
            }
            using (var context = new EntityContext())
            {
                //check add/updates first
                if (profiles.Count() > 0)
                {
                    bool isEmpty = false;

                    foreach (ThisEntity entity in profiles)
                    {
                        entity.CategoryId = categoryId;
                        if (Validate(entity, isTitleRequired, ref isEmpty, ref status) == false)
                        {
                            isValid = false;
                            continue;
                        }

                        if (isEmpty)   //skip
                        {
                            continue;
                        }
                        entity.EntityBaseId = parent.EntityBaseId;

                        //21-03-31 existance check
                        //var exists = context.Entity_Reference
                        //	.Where( s => s.EntityId == parent.Id && s.CategoryId == categoryId && s.TextValue == entity.TextValue )
                        //	.ToList();
                        //if (exists != null && exists.Any())
                        //{
                        //	return true;
                        //}
                        //if ( entity.Id == 0 )
                        //{
                        //add
                        efEntity = new DBEntity();
                        MapToDB(entity, efEntity);
                        efEntity.EntityId = parent.Id;
                        efEntity.Created  = efEntity.LastUpdated = DateTime.Now;

                        context.Entity_Reference.Add(efEntity);
                        count = context.SaveChanges();
                        //update profile record so doesn't get deleted
                        entity.Id       = efEntity.Id;
                        entity.ParentId = parent.Id;

                        if (count == 0)
                        {
                            status.AddWarning(string.Format(" Unable to add Profile: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.TextTitle) ? "no description" : entity.TextTitle));
                        }
                        else
                        {
                            if (categoryId == CodesManager.PROPERTY_CATEGORY_SUBJECT)
                            {
                                AddConnections(entity.Id);
                            }
                        }
                    } //foreach
                }
            }

            return(isValid);
        } //
        } //

        /// <summary>
        /// Add for simple strings - textValue only
        /// </summary>
        /// <param name="profiles"></param>
        /// <param name="parentUid"></param>
        /// <param name="status"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public bool AddTextValue(List <string> profiles,
                                 Guid parentUid,
                                 ref SaveStatus status,
                                 int categoryId)
        {
            bool isValid = true;

            if (profiles == null || profiles.Count == 0)
            {
                return(true);
            }
            status.HasSectionErrors = false;

            if (!IsValidGuid(parentUid))
            {
                status.AddError("Error: the parent identifier was not provided.");
                return(false);
            }

            //int count = 0;
            DBEntity efEntity = new DBEntity();
            Entity   parent   = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + string.Format(". Error - the parent entity was not found. parentUid: {0}", parentUid));
                return(false);
            }
            //using ( var context = new EntityContext() )
            //{
            foreach (string textValue in profiles)
            {
                if (string.IsNullOrWhiteSpace(textValue))
                {
                    continue;
                }
                AddTextValue(textValue, parent.Id, ref status, categoryId);
                ////add
                //efEntity = new DBEntity();
                //efEntity.CategoryId = categoryId;
                //efEntity.EntityId = parent.Id;
                //efEntity.TextValue = textValue;
                //efEntity.Created = efEntity.LastUpdated = DateTime.Now;

                //context.Entity_Reference.Add( efEntity );
                //count = context.SaveChanges();

                //if ( count == 0 )
                //{
                //	status.AddWarning( string.Format( " Unable to add Entity_Reference. EntityId: {0}, categoryId: {1}, textValue: {2}  ", parent.Id, categoryId, textValue ));
                //}
                //else
                //{
                //	if ( categoryId == CodesManager.PROPERTY_CATEGORY_SUBJECT )
                //		AddConnections( efEntity.Id );
                //}
            } //foreach
              //}

            return(isValid);
        } //
Exemplo n.º 14
0
        public bool SaveList(List <ThisEntity> list, Guid parentUid, ref SaveStatus status)
        {
            if (!IsValidGuid(parentUid))
            {
                status.AddError(string.Format("A valid parent identifier was not provided to the {0}.Add method.", thisClassName));
                return(false);
            }

            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError(thisClassName + ". Error - the parent entity was not found.");
                return(false);
            }
            //21-03-31 mp	- back to deleteAll - problem with related tables like entity.reference (also maybe cost items?) not getting deleted, so adding dups
            //				- consider an existance check. Easier for entity.reference, but not for jurisdictions
            DeleteAll(parent, ref status);
            //now maybe still do a delete all until implementing a balance line
            //could set date and delete all before this date!
            DateTime updateDate = DateTime.Now;

            if (IsValidDate(status.EnvelopeUpdatedDate))
            {
                updateDate = status.LocalUpdatedDate;
            }

            //var current = GetAll( parent.EntityUid );
            bool isAllValid = true;

            if (list == null || list.Count == 0)
            {
                //if ( current != null && current.Any() )
                //{
                //	DeleteAll( parent, ref status );
                //}
                return(true);
            }
            //else    //may not need this if the new list version works
            //if ( list.Count == 1 && current.Count == 1 )
            //{
            //	//just do update of one
            //	var entity = list[ 0 ];
            //	entity.Id = current[ 0 ].Id;

            //	Save( entity, parent, ref status );
            //}
            else
            {
                //21-03-16 mp - go back to delete all for now
                //DeleteAll( parent, ref status );
                int cntr = 0;
                foreach (ThisEntity item in list)
                {
                    //if ( current != null && current.Count > cntr )
                    //{
                    //	item.Id = current[ cntr ].Id;
                    //}
                    Save(item, parent, ref status);
                    cntr++;
                }
                //delete any records with last updated less than updateDate
                //this will not work if doing many re-imports - with same date
                //DeleteAll( parent, ref status, updateDate );
            }
            return(isAllValid);
        }
        }               //

        /// <summary>
        /// May be workaround, may be permanent, getting combined
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="alignmentType"></param>
        /// <returns></returns>
        //public static List<CredentialAlignmentObjectProfile> GetAllAs_CredentialAlignmentObjectProfile( Guid parentUid, ref Dictionary<string, RegistryImport> frameworksList)
        //{
        //	CredentialAlignmentObjectProfile entity = new CredentialAlignmentObjectProfile();
        //	List<CredentialAlignmentObjectProfile> list = new List<CredentialAlignmentObjectProfile>();
        //          //var frameworksList = new Dictionary<string, RegistryImport>();
        //          string prevFramework = "";
        //	Entity parent = EntityManager.GetEntity( parentUid );
        //	if ( parent == null || parent.Id == 0 )
        //	{
        //		return list;
        //	}
        //	try
        //	{
        //		using ( var context = new ViewContext() )
        //		{
        //			/*
        //			List<DBEntity> results = context.Entity_Competency
        //					.Where( s => s.EntityId == parent.Id
        //					)
        //					.OrderBy( s => s.EducationFramework )
        //					.ThenBy( s => s.TargetNodeName )
        //					.ToList();
        //			if ( results != null && results.Count > 0 )
        //			{
        //				foreach ( DBEntity item in results )
        //				{
        //					entity = new CredentialAlignmentObjectProfile();
        //					MapFromDB( item, entity );
        //					list.Add( entity );
        //				}
        //			}
        //			*/
        //			List<Views.EntityCompetencyFramework_Items_Summary> results = context.EntityCompetencyFramework_Items_Summary
        //					.Where( s => s.EntityId == parent.Id
        //					)
        //					.OrderBy( s => s.FrameworkName )
        //					.ThenBy( s => s.Competency )
        //					.ToList();
        //			if ( results != null && results.Count > 0 )
        //			{
        //				foreach ( var item in results )
        //				{
        //					entity = new CredentialAlignmentObjectProfile();
        //					MapFromDB( item, entity );
        //                          if ( prevFramework != entity.FrameworkName )
        //                          {
        //                              if ( !string.IsNullOrWhiteSpace(entity.FrameworkCtid) )
        //                              {
        //                                  //var fw = new Dictionary<string, RegistryImport>();
        //                                  RegistryImport ri = ImportManager.GetByCtid(entity.FrameworkCtid);
        //                                  if ( frameworksList.ContainsKey(entity.FrameworkName) == false )
        //                                      frameworksList.Add(entity.FrameworkName, ri);
        //                              }
        //                              prevFramework = entity.FrameworkName;
        //                          }

        //                          list.Add( entity );
        //				}
        //                  }
        //		}
        //	}
        //	catch ( Exception ex )
        //	{
        //		LoggingHelper.LogError( ex, thisClassName + ".GetAllAs_CredentialAlignmentObjectProfile" );
        //	}
        //	return list;
        //}//

        //public static void MapFromDB( Views.EntityCompetencyFramework_Items_Summary from, CredentialAlignmentObjectProfile to )
        //{
        //	to.Id = from.EntityCompetencyId;
        //	to.ParentId = from.EntityId;
        //          //to.EducationFrameworkId = from.EducationFrameworkId ?? 0;
        //          to.FrameworkName = from.FrameworkName;
        //          //add url?? to Entity for now?
        //          //don't populate if for registry
        //          //18-06-28 mparsons - aim to make FrameworkUrl obsolete!
        //          //                  - SourceUrl should be populated
        //          //if ( from.FrameworkUrl.ToLower().IndexOf("credentialengineregistry.org/resources/ce-") == -1 )
        //          //{
        //          //    to.FrameworkUrl = from.FrameworkUrl;
        //          //}
        //          //else if ( !string.IsNullOrWhiteSpace(from.SourceUrl) )
        //          //    to.FrameworkUrl = from.SourceUrl;
        //          //
        //          to.SourceUrl = from.SourceUrl;
        //          to.FrameworkUri = from.FrameworkUri;
        //          to.FrameworkCtid = from.FrameworkCtid;

        //          //
        //	to.TargetNode = from.TargetNode;
        //	to.TargetNodeDescription = from.TargetNodeDescription;
        //	to.TargetNodeName = from.Competency;
        //	to.Weight = ( from.Weight ?? 0M );
        //	to.CodedNotation = from.CodedNotation;

        //	if ( IsValidDate( from.Created ) )
        //		to.Created = ( DateTime ) from.Created;

        //}

        /// <summary>
        /// Need to fake this out, until enlightenment occurs
        /// </summary>
        /// <param name="parentUid"></param>
        /// <returns></returns>
        public static List <CredentialAlignmentObjectFrameworkProfile> GetAllAs_CAOFramework(Guid parentUid, ref Dictionary <string, RegistryImport> frameworksList)
        {
            CredentialAlignmentObjectFrameworkProfile        entity = new CredentialAlignmentObjectFrameworkProfile();
            List <CredentialAlignmentObjectFrameworkProfile> list   = new List <CredentialAlignmentObjectFrameworkProfile>();
            //var frameworksList = new Dictionary<string, RegistryImport>();
            string viewerUrl = UtilityManager.GetAppKeyValue("cassResourceViewerUrl");
            bool   hidingFrameworksNotPublished   = UtilityManager.GetAppKeyValue("hideFrameworksNotPublished", false);
            CredentialAlignmentObjectItem caoItem = new CredentialAlignmentObjectItem();
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                return(list);
            }

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_Competency
                                              .Where(s => s.EntityId == parent.Id
                                                     )
                                              .OrderBy(s => s.FrameworkName)
                                              .ThenBy(s => s.TargetNodeName)
                                              .ToList();
                    if (results != null && results.Count > 0)
                    {
                        string prevName = "";
                        foreach (DBEntity item in results)
                        {
                            if (prevName != item.FrameworkName)
                            {
                                if (!string.IsNullOrWhiteSpace(prevName))
                                {
                                    //actually try handling in detail page - not working

                                    if (!entity.IsARegistryFrameworkUrl ||
                                        !hidingFrameworksNotPublished ||
                                        (entity.IsARegistryFrameworkUrl && entity.ExistsInRegistry)
                                        )
                                    {
                                        if (!entity.IsDeleted)
                                        {
                                            list.Add(entity);
                                        }
                                    }
                                }

                                entity = new CredentialAlignmentObjectFrameworkProfile();
                                if (item.EducationFramework != null && item.EducationFramework.Id > 0)
                                {
                                    entity.FrameworkName = item.EducationFramework.FrameworkName;
                                    entity.FrameworkUri  = item.EducationFramework.FrameworkUri;
                                    entity.SourceUrl     = item.EducationFramework.SourceUrl;
                                    if (entity.IsARegistryFrameworkUrl &&
                                        (item.EducationFramework.ExistsInRegistry ?? false)
                                        )
                                    {
                                        entity.ExistsInRegistry = true;
                                        if (item.EducationFramework.EntityStateId == 0)
                                        {
                                            //need to skip - need more than this. A non-registry framework will not exist in registry
                                            entity.IsDeleted = true;
                                        }
                                    }

                                    //18-12-13 mp - can only use viewer, if a cer URL - although this may change for other sources
                                    if (!string.IsNullOrWhiteSpace(viewerUrl) && entity.IsARegistryFrameworkUrl)
                                    {
                                        entity.CaSSViewerUrl = string.Format(viewerUrl, UtilityManager.GenerateMD5String(entity.FrameworkUri));
                                    }
                                    //if ( item.FrameworkUrl.ToLower().IndexOf("credentialengineregistry.org/resources/ce-") == -1 )
                                    //    entity.SourceUrl = item.EducationFramework.SourceUrl;
                                    //else
                                    //    entity.SourceUrl = item.EducationFramework.SourceUrl ?? "";

                                    if (!string.IsNullOrWhiteSpace(item.EducationFramework.CTID))
                                    {
                                        entity.FrameworkPayload = ImportManager.GetByCtid(item.EducationFramework.CTID);
                                        if (!string.IsNullOrWhiteSpace(entity.FrameworkPayload.Payload) &&
                                            frameworksList.ContainsKey(entity.FrameworkName) == false)
                                        {
                                            frameworksList.Add(entity.FrameworkName, entity.FrameworkPayload);
                                        }
                                    }
                                }
                                else
                                {
                                    //this should not happen - should log this
                                    entity.FrameworkName = item.FrameworkName;
                                    entity.SourceUrl     = item.FrameworkUrl ?? "";
                                    //should we populate frameworkUri as well?
                                    entity.FrameworkUri = item.FrameworkUrl ?? "";
                                }


                                entity.ParentId = item.EducationFrameworkId ?? 0;
                                prevName        = item.FrameworkName;
                            }

                            caoItem = new CredentialAlignmentObjectItem();
                            MapFromDB(item, caoItem);
                            entity.Items.Add(caoItem);
                            entity.HasCompetencies = true;
                        }
                        //add last one
                        if (!string.IsNullOrWhiteSpace(prevName))
                        {
                            if (!entity.IsARegistryFrameworkUrl ||
                                !hidingFrameworksNotPublished ||
                                (entity.IsARegistryFrameworkUrl && entity.ExistsInRegistry)
                                )
                            {
                                if (!entity.IsDeleted)
                                {
                                    list.Add(entity);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".GetAllAs_CAOFramework");
            }
            return(list);
        }        //
Exemplo n.º 16
0
        /// <summary>
        /// Add an Entity_CommonCondition
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="profileId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public int Entity_HasConditionManifest_Add(Guid parentUid,
                                                   int profileId,
                                                   ref SaveStatus status)
        {
            int id    = 0;
            int count = 0;

            if (profileId == 0)
            {
                status.AddError(string.Format("A valid ConditionManifest identifier was not provided to the {0}.Add method.", thisClassName));
                return(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())
            {
                EM.Entity_ConditionManifest efEntity = new EM.Entity_ConditionManifest();
                try
                {
                    //first check for duplicates
                    efEntity = context.Entity_ConditionManifest
                               .SingleOrDefault(s => s.EntityId == parent.Id &&
                                                s.ConditionManifestId == profileId);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //status.AddError( string.Format( "Error - this ConditionManifest has already been added to this profile.", thisClassName ) );
                        return(0);
                    }

                    efEntity                     = new EM.Entity_ConditionManifest();
                    efEntity.EntityId            = parent.Id;
                    efEntity.ConditionManifestId = profileId;

                    efEntity.Created = System.DateTime.Now;

                    context.Entity_ConditionManifest.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 ConditionManifest 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}", parentUid, parent.EntityType, profileId);
                        EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Entity_CommonCondition");
                    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);
        }
Exemplo n.º 17
0
        public static void FillCountsForOrganizationQAPerformed(Organization org, ref int totalRecords)
        {
            Entity agentEntity = EntityManager.GetEntity(org.RowId);

            using (var context = new ViewContext())
            {
                //first check how long this step takes
                DateTime start = DateTime.Now;
                LoggingHelper.DoTrace(7, "FillCountsForOrganizationQAPerformed start");
                //List<Views.Organization_CombinedQAPerformed> agentRoles = context.Organization_CombinedQAPerformed
                //	.Where( s => s.OrgUid == org.RowId
                //		 && s.IsQARole == true
                //		 && s.TargetEntityStateId > 1 )
                //		 .OrderBy( s => s.TargetEntityTypeId )
                //		 .ThenBy( s => s.TargetOwningOrganizationName )
                //		 .ThenBy( s => s.TargetEntityName )
                //		 .ThenBy( s => s.AgentToSourceRelationship )
                //		 .ThenBy( s => s.roleSource )
                //	.ToList();



                //if ( agentRoles != null && agentRoles.Count() > 0 )
                //{
                //	//
                //	totalRecords = agentRoles.Count();
                //	//may want a fudge factor?
                //	org.QAPerformedOnCredentialsCount = agentRoles.Where( s => s.TargetEntityTypeId == 1 ).Distinct().Count();
                //	org.QAPerformedOnOrganizationsCount = agentRoles.Where( s => s.TargetEntityTypeId == 2 ).Distinct().Count();
                //	org.QAPerformedOnAssessmentsCount = agentRoles.Where( s => s.TargetEntityTypeId == 3 ).Distinct().Count();
                //	org.QAPerformedOnLoppsCount = agentRoles.Where( s => s.TargetEntityTypeId == 7 ).Distinct().Count();

                //}



                var query = from qa in context.Organization_CombinedQAPerformed
                            .Where(s => s.OrgUid == org.RowId &&
                                   s.IsQARole == true &&
                                   s.TargetEntityStateId > 1)
                            .OrderBy(s => s.TargetEntityTypeId)
                            .ThenBy(s => s.TargetOwningOrganizationName)
                            .ThenBy(s => s.TargetEntityName)
                            .ThenBy(s => s.AgentToSourceRelationship)
                            .ThenBy(s => s.roleSource)
                            select new
                {
                    qa.TargetEntityTypeId,
                    qa.TargetEntityBaseId,
                    qa.TargetOwningOrganizationId
                };
                DateTime end     = DateTime.Now;
                var      elasped = end.Subtract(start).TotalSeconds;
                LoggingHelper.DoTrace(7, string.Format("FillCountsForOrganizationQAPerformed retrieve seconds: {0}", elasped));

                var results = query.Distinct().ToList();
                if (results != null && results.Count() > 0)
                {
                    //
                    totalRecords = results.Count();
                    //may want a fudge factor?
                    org.QAPerformedOnCredentialsCount   = results.Where(s => s.TargetEntityTypeId == 1 && s.TargetOwningOrganizationId != org.Id).Distinct().Count();
                    org.QAPerformedOnOrganizationsCount = results.Where(s => s.TargetEntityTypeId == 2).Distinct().Count();
                    org.QAPerformedOnAssessmentsCount   = results.Where(s => s.TargetEntityTypeId == 3 && s.TargetOwningOrganizationId != org.Id).Distinct().Count();
                    org.QAPerformedOnLoppsCount         = results.Where(s => s.TargetEntityTypeId == 7 && s.TargetOwningOrganizationId != org.Id).Distinct().Count();

                    DateTime listEnd = DateTime.Now;
                    elasped = listEnd.Subtract(end).TotalSeconds;
                    LoggingHelper.DoTrace(7, string.Format("FillCountsForOrganizationQAPerformed loaded list seconds: {0}", elasped));
                }
            }
        }         //
Exemplo n.º 18
0
        public static List <OrganizationAssertion> GetAllCombined2(int orgId, int maxRecords = 10)
        {
            //Organization org = OrganizationManager.GetForSummary( orgId, true );
            //return GetAllCombined( org.RowId, maxRecords );
            OrganizationAssertion        orp  = new OrganizationAssertion();
            List <OrganizationAssertion> list = new List <OrganizationAssertion>();
            EnumeratedItem eitem = new EnumeratedItem();

            Guid   prevTargetUid  = new Guid();
            string prevRoleSource = "";
            int    prevRoleTypeId = 0;
            Entity agentEntity    = EntityManager.GetEntity(2, orgId);

            using (var context = new ViewContext())
            {
                List <Views.Organization_CombinedQAPerformed> agentRoles = context.Organization_CombinedQAPerformed
                                                                           .Where(s => s.OrgUid == agentEntity.EntityUid &&
                                                                                  s.IsQARole == true &&
                                                                                  s.TargetEntityStateId > 1)
                                                                           .OrderBy(s => s.TargetEntityTypeId)
                                                                           .ThenBy(s => s.TargetEntityBaseId)
                                                                           .ThenBy(s => s.TargetEntityName)
                                                                           .ThenBy(s => s.AgentToSourceRelationship)
                                                                           .ThenBy(s => s.roleSource)
                                                                           .Take(maxRecords)
                                                                           .ToList();

                foreach (var entity in agentRoles)
                {
                    //loop until change in entity type?
                    if (prevTargetUid != entity.TargetEntityUid)
                    {
                        //handle previous fill
                        if (IsGuidValid(prevTargetUid) && orp.AgentAssertion.Items.Count > 0)
                        {
                            list.Add(orp);
                        }

                        prevTargetUid  = entity.TargetEntityUid;
                        prevRoleSource = entity.roleSource;
                        prevRoleTypeId = entity.RelationshipTypeId;

                        orp          = new OrganizationAssertion();
                        orp.Id       = 0;
                        orp.ParentId = agentEntity.EntityBaseId;


                        orp.AgentAssertion          = CodesManager.GetEnumeration(CodesManager.PROPERTY_CATEGORY_ENTITY_AGENT_ROLE);
                        orp.AgentAssertion.ParentId = entity.OrgId;

                        orp.AgentAssertion.Items       = new List <EnumeratedItem>();
                        orp.TargetEntityType           = entity.TargetEntityType;
                        orp.TargetEntityBaseId         = ( int )entity.TargetEntityBaseId;
                        orp.TargetEntityName           = entity.TargetEntityName;
                        orp.TargetEntitySubjectWebpage = entity.TargetEntitySubjectWebpage;
                        orp.TargetEntityStateId        = ( int )entity.TargetEntityStateId;
                        orp.AgentToSourceRelationship  = entity.AgentToSourceRelationship;
                        //if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_CREDENTIAL )
                        //{
                        //	//17-08-27 mp - just get the basic for each entity!
                        //	orp.TargetCredential = CredentialManager.GetBasic( entity.TargetEntityBaseId ?? 0 );

                        //}
                        //else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ORGANIZATION )
                        //{
                        //	//orp.TargetOrganization = OrganizationManager.GetBasics( entity.TargetEntityUid );
                        //	orp.TargetOrganization.Id = entity.TargetEntityBaseId ?? 0;
                        //	orp.TargetOrganization.RowId = entity.TargetEntityUid;
                        //	orp.TargetOrganization.Name = entity.TargetEntityName;

                        //	orp.TargetOrganization.Description = entity.TargetEntityDescription;
                        //	orp.TargetOrganization.EntityStateId = entity.TargetEntityStateId ?? 2;
                        //	orp.TargetOrganization.SubjectWebpage = entity.TargetEntitySubjectWebpage;
                        //	orp.TargetOrganization.ImageUrl = entity.TargetEntityImageUrl;
                        //}
                        //else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE )
                        //{
                        //	orp.TargetAssessment = AssessmentManager.GetBasic( entity.TargetEntityBaseId ?? 0 );
                        //}
                        //else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE )
                        //{
                        //	orp.TargetLearningOpportunity = LearningOpportunityManager.GetBasic( entity.TargetEntityBaseId ?? 0 );
                        //}
                    }

                    //check for a change in roleSource
                    if (prevRoleSource != entity.roleSource)
                    {
                        if (prevRoleTypeId == entity.RelationshipTypeId)
                        {
                            //add as matched assertion
                            //may want to delay addding enumeration item
                            continue;
                        }
                    }
                    //add relationship
                    eitem = new EnumeratedItem();
                    //??
                    eitem.Id = entity.RelationshipTypeId;

                    //eitem.RowId = entity.RowId.ToString();
                    //not used here
                    eitem.RecordId = entity.RelationshipTypeId;
                    //eitem.CodeId = entity.RelationshipTypeId;

                    prevRoleTypeId = entity.RelationshipTypeId;
                    prevRoleSource = entity.roleSource;

                    eitem.Name       = entity.AgentToSourceRelationship;
                    eitem.SchemaName = entity.ReverseSchemaTag;

                    orp.AgentAssertion.Items.Add(eitem);
                }
                //check for remaining
                if (IsGuidValid(prevTargetUid) && orp.AgentAssertion.Items.Count > 0)
                {
                    list.Add(orp);
                }
            }
            return(list);
        }
Exemplo n.º 19
0
        //public static List<OrganizationRoleProfile> GetAll( Guid agentUid )
        //{
        //    OrganizationRoleProfile orp = new OrganizationRoleProfile();
        //    List<OrganizationRoleProfile> list = new List<OrganizationRoleProfile>();
        //    EnumeratedItem eitem = new EnumeratedItem();

        //    Guid prevTargetUid = new Guid();
        //    Entity agentEntity = EntityManager.GetEntity( agentUid );

        //    using ( var context = new ViewContext() )
        //    {
        //        List<DBEntitySummary> agentRoles = context.Entity_Assertion_Summary
        //            .Where( s => s.AgentUid == agentUid
        //                 && s.IsQARole == true
        //                 && s.TargetEntityStateId > 1 )
        //                 .OrderBy( s => s.TargetEntityTypeId )
        //                 .ThenBy( s => s.TargetEntityName )
        //                 .ThenBy( s => s.AgentToSourceRelationship )
        //            .ToList();

        //        foreach ( DBEntitySummary entity in agentRoles )
        //        {
        //            //loop until change in entity type?
        //            if ( prevTargetUid != entity.TargetEntityUid )
        //            {
        //                //handle previous fill
        //                if ( IsGuidValid( prevTargetUid ) && orp.AgentRole.Items.Count > 0 )
        //                    list.Add( orp );

        //                prevTargetUid = entity.TargetEntityUid;

        //                orp = new OrganizationRoleProfile();
        //                orp.Id = 0;
        //                orp.ParentId = agentEntity.EntityBaseId;
        //                orp.ParentTypeId = agentEntity.EntityTypeId;

        //                orp.ProfileSummary = entity.TargetEntityName;

        //                orp.AgentRole = CodesManager.GetEnumeration( CodesManager.PROPERTY_CATEGORY_ENTITY_AGENT_ROLE );
        //                orp.AgentRole.ParentId = entity.OrgId;

        //                orp.AgentRole.Items = new List<EnumeratedItem>();
        //                orp.SourceEntityType = entity.TargetEntityType;

        //                if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_CREDENTIAL )
        //                {
        //                    //17-08-27 mp - just get the basic for each entity!
        //                    orp.TargetCredential = CredentialManager.GetBasic( entity.TargetEntityBaseId ?? 0 );

        //                }
        //                else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ORGANIZATION )
        //                {
        //                    orp.TargetOrganization.Id = entity.TargetEntityBaseId ?? 0;
        //                    orp.TargetOrganization.RowId = entity.TargetEntityUid;
        //                    orp.TargetOrganization.Name = entity.TargetEntityName;

        //                    orp.TargetOrganization.Description = entity.TargetEntityDescription;
        //                    orp.TargetOrganization.SubjectWebpage = entity.TargetEntitySubjectWebpage;
        //                    orp.TargetOrganization.ImageUrl = entity.TargetEntityImageUrl;
        //                }
        //                else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE )
        //                {
        //                    orp.TargetAssessment = AssessmentManager.GetBasic( entity.TargetEntityBaseId ?? 0 );
        //                }
        //                else if ( entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE )
        //                {
        //                    orp.TargetLearningOpportunity = LearningOpportunityManager.GetBasic( entity.TargetEntityBaseId ?? 0 );
        //                }
        //            }

        //            //add relationship
        //            eitem = new EnumeratedItem();
        //            //??
        //            eitem.Id = entity.AssertionTypeId;
        //            //eitem.RowId = entity.RowId.ToString();
        //            //not used here
        //            eitem.RecordId = entity.AssertionTypeId;
        //            eitem.CodeId = entity.AssertionTypeId;

        //            eitem.Name = entity.AgentToSourceRelationship;
        //            eitem.SchemaName = entity.ReverseSchemaTag;
        //            //eitem.Selected = true;
        //            //if ( ( bool )entity.IsQARole )
        //            //{
        //            //    eitem.IsSpecialValue = true;
        //            //    if ( IsDevEnv() )
        //            //        eitem.Name += " (QA)";
        //            //}

        //            orp.AgentRole.Items.Add( eitem );

        //        }
        //        //check for remaining
        //        if ( IsGuidValid( prevTargetUid ) && orp.AgentRole.Items.Count > 0 )
        //            list.Add( orp );

        //    }
        //    return list;

        //} //

        //
        public static List <OrganizationAssertion> GetAllCombined(int orgId, int maxRecords = 10)
        {
            //Organization org = OrganizationManager.GetForSummary( orgId, true );
            //return GetAllCombined( org.RowId, maxRecords );
            OrganizationAssertion        orp  = new OrganizationAssertion();
            List <OrganizationAssertion> list = new List <OrganizationAssertion>();
            EnumeratedItem eitem         = new EnumeratedItem();
            int            records       = maxRecords * 2;
            Guid           prevTargetUid = new Guid();

            string prevRoleSource = "";
            //string currRoleSource = "";
            int    prevRoleTypeId = 0;
            Entity agentEntity    = EntityManager.GetEntity(2, orgId);

            using (var context = new ViewContext())
            {
                List <Views.Organization_CombinedQAPerformed> agentRoles = context.Organization_CombinedQAPerformed
                                                                           .Where(s => s.OrgUid == agentEntity.EntityUid &&
                                                                                  s.IsQARole == true &&
                                                                                  s.TargetEntityStateId > 1)
                                                                           .OrderBy(s => s.TargetEntityTypeId)
                                                                           .ThenBy(s => s.TargetEntityBaseId)
                                                                           .ThenBy(s => s.TargetEntityName)
                                                                           .ThenBy(s => s.AgentToSourceRelationship)
                                                                           .ThenBy(s => s.roleSource)
                                                                           .Take(records)
                                                                           .ToList();

                foreach (var entity in agentRoles)
                {
                    if (entity.TargetEntityUid == prevTargetUid && entity.RelationshipTypeId == prevRoleTypeId)
                    {
                        continue;
                    }
                    //loop until change in entity type?
                    //if ( prevTargetUid != entity.TargetEntityUid )

                    //handle previous fill
                    //if ( IsGuidValid( prevTargetUid ) && orp.AgentAssertion.Items.Count > 0 )
                    //	list.Add( orp );

                    prevTargetUid  = entity.TargetEntityUid;
                    prevRoleSource = entity.roleSource;
                    prevRoleTypeId = entity.RelationshipTypeId;

                    orp          = new OrganizationAssertion();
                    orp.Id       = 0;
                    orp.ParentId = agentEntity.EntityBaseId;


                    orp.AgentAssertion          = CodesManager.GetEnumeration(CodesManager.PROPERTY_CATEGORY_ENTITY_AGENT_ROLE);
                    orp.AgentAssertion.ParentId = entity.OrgId;

                    orp.AgentAssertion.Items       = new List <EnumeratedItem>();
                    orp.TargetEntityType           = entity.TargetEntityType;
                    orp.TargetEntityBaseId         = ( int )entity.TargetEntityBaseId;
                    orp.TargetEntityName           = entity.TargetEntityName;
                    orp.TargetEntitySubjectWebpage = entity.TargetEntitySubjectWebpage;
                    orp.TargetEntityStateId        = ( int )entity.TargetEntityStateId;
                    orp.AgentToSourceRelationship  = entity.AgentToSourceRelationship;
                    //20-10-10 - targetCTID was not being populated
                    orp.TargetCTID = entity.AgentCTID;
                    if (list.Count() < maxRecords)
                    {
                        list.Add(orp);
                    }


                    //check for a change in roleSource
                    //if ( prevRoleSource != entity.roleSource )
                    //{
                    //    if ( prevRoleTypeId == entity.RelationshipTypeId )
                    //    {
                    //        //add as matched assertion
                    //        //may want to delay addding enumeration item
                    //        continue;
                    //    }
                    //}
                }
                //check for remaining
                //if ( IsGuidValid( prevTargetUid ) && orp.AgentAssertion.Items.Count > 0 )
                //    list.Add( orp );
            }
            return(list);
        }
        /// <summary>
        /// Persist ProcessProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="parentUid"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, Guid parentUid, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            if (!IsValidGuid(parentUid))
            {
                status.AddError("Error: the parent identifier was not provided.");
                return(false);
            }


            int count = 0;

            DBEntity efEntity = new DBEntity();

            Entity parent = EntityManager.GetEntity(parentUid);

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


            //determine type
            int profileTypeId = 0;

            if (entity.ProcessTypeId > 0)
            {
                profileTypeId = entity.ProcessTypeId;
            }
            else
            {
                //
                switch (entity.ProcessProfileType)
                {
                case "AppealProcess":
                    entity.ProcessTypeId = APPEAL_PROCESS_TYPE;
                    break;

                case "ComplaintProcess":
                    entity.ProcessTypeId = COMPLAINT_PROCESS_TYPE;
                    break;
                //case "CriteriaProcess":
                //	entity.ProcessTypeId = CRITERIA_PROCESS_TYPE;
                //	break;

                case "ReviewProcess":
                    entity.ProcessTypeId = REVIEW_PROCESS_TYPE;
                    break;

                case "RevocationProcess":
                    entity.ProcessTypeId = REVOKE_PROCESS_TYPE;
                    break;

                case "ProcessProfile":
                    entity.ProcessTypeId = DEFAULT_PROCESS_TYPE;
                    break;

                case "CredentialProcess":
                    entity.ProcessTypeId = DEFAULT_PROCESS_TYPE;
                    break;

                case "MaintenanceProcess":
                    entity.ProcessTypeId = MTCE_PROCESS_TYPE;
                    break;

                case "AdministrationProcess":
                    entity.ProcessTypeId = ADMIN_PROCESS_TYPE;
                    break;

                case "DevelopmentProcess":
                    entity.ProcessTypeId = DEV_PROCESS_TYPE;
                    break;

                //
                default:
                    entity.ProcessTypeId = 1;
                    status.AddError(string.Format("Error: Unexpected profile type of {0} was encountered.", entity.ProcessProfileType));
                    return(false);
                }
            }
            using (var context = new EntityContext())
            {
                if (ValidateProfile(entity, ref status) == false)
                {
                    status.AddError("Process Profile was invalid. " + SetEntitySummary(entity));
                    return(false);
                }


                if (entity.Id == 0)
                {
                    //add
                    efEntity = new DBEntity();
                    MapToDB(entity, efEntity);
                    efEntity.EntityId = parent.Id;

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

                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }

                    context.Entity_ProcessProfile.Add(efEntity);
                    count = context.SaveChanges();
                    //update profile record so doesn't get deleted
                    entity.Id       = efEntity.Id;
                    entity.ParentId = parent.Id;
                    entity.RowId    = efEntity.RowId;
                    if (count == 0)
                    {
                        status.AddError(string.Format(" Unable to add Profile: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.ProfileName) ? "no description" : entity.ProfileName));
                    }
                    else
                    {
                        //other entity components use a trigger to create the entity Object. If a trigger is not created, then child adds will fail (as typically use entity_summary to get the parent. As the latter is easy, make the direct call?

                        UpdateParts(entity, ref status);
                    }
                }
                else
                {
                    entity.ParentId = parent.Id;

                    efEntity = context.Entity_ProcessProfile.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))
                        {
                            efEntity.LastUpdated = System.DateTime.Now;

                            count = context.SaveChanges();
                        }
                        //always check parts
                        UpdateParts(entity, ref status);
                    }
                }
            }

            return(status.WasSectionValid);
        }
        //


        /// <summary>
        ///
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="childComponentsAction">0-none; 1-summary; 2-deep </param>
        public static void MapFromDB(DBEntity input, ThisEntity output, int childComponentsAction = 1)
        {
            output.Id            = input.Id;
            output.RowId         = input.RowId;
            output.EntityStateId = input.EntityStateId < 1 ? 1 : input.EntityStateId;
            output.CTID          = input.CTID;
            output.Name          = input.Name;
            output.Description   = input.Description;
            output.PathwayCTID   = input.PathwayCTID;
            //if ( input.Entity_HasPathwayComponent != null && input.Entity_HasPathwayComponent.Count > 0 )
            //{
            //	//
            //}

            var relatedEntity = EntityManager.GetEntity(output.RowId, false);

            if (relatedEntity != null && relatedEntity.Id > 0)
            {
                output.EntityLastUpdated = relatedEntity.LastUpdated;
            }

            //need output get parent pathway?
            //output.IsDestinationComponentOf = Entity_PathwayComponentManager.GetPathwayForComponent( output.Id, PathwayComponent.PathwayComponentRelationship_HasDestinationComponent );

            //ispartof. Should be single, but using list for flexibility?
            //actually force one, as we are using pathway identifier an external id for a unique lookup
            //may not want output do this every time?
            //output.IsPartOf = Entity_PathwayComponentManager.GetPathwayForComponent( output.Id, PathwayComponent.PathwayComponentRelationship_HasPart );

            //may want output get all and split out
            if (childComponentsAction == 2)
            {
                output.AllComponents = Entity_PathwayComponentManager.GetAll(output.RowId, componentActionOfSummary);
                foreach (var item in output.AllComponents)
                {
                    if (item.ComponentRelationshipTypeId == PC.PathwayComponentRelationship_HasChild)
                    {
                        output.HasChild.Add(item);
                    }
                    else if (item.ComponentRelationshipTypeId == PC.PathwayComponentRelationship_IsChildOf)
                    {
                        output.IsChildOf.Add(item);
                    }
                    else if (item.ComponentRelationshipTypeId == PC.PathwayComponentRelationship_Preceeds)
                    {
                        output.Preceeds.Add(item);
                    }
                    else if (item.ComponentRelationshipTypeId == PC.PathwayComponentRelationship_Prerequiste)
                    {
                        output.Prerequisite.Add(item);
                    }
                }
                //child components - details of condition, but summary of components
                output.HasCondition = PathwayComponentConditionManager.GetAll(output.Id, true);
            }

            //output.CodedNotation = input.CodedNotation;
            output.ComponentCategory = input.ComponentCategory;
            output.ComponentTypeId   = input.ComponentTypeId;
            if (input.Codes_PathwayComponentType != null && input.Codes_PathwayComponentType.Id > 0)
            {
                output.PathwayComponentType = input.Codes_PathwayComponentType.Title;
            }
            else
            {
                output.PathwayComponentType = GetComponentType(output.ComponentTypeId);
            }
            //will be validated before getting here!
            output.CredentialType = input.CredentialType;
            if (!string.IsNullOrWhiteSpace(output.CredentialType) && output.CredentialType.IndexOf("ctdl/terms") > 0)
            {
                int pos = output.CredentialType.IndexOf("ctdl/terms");
                output.CredentialType = output.CredentialType.Substring(pos + 11);
            }

            //not sure if this will just be a URI, or point output a concept
            //if a concept, would probably need entity.hasConcept
            //output.HasProgressionLevel = input.HasProgressionLevel;
            //if ( !string.IsNullOrWhiteSpace( input.HasProgressionLevel ) )
            //{
            //	output.ProgressionLevel = ConceptSchemeManager.GetByConceptCtid( output.HasProgressionLevel );
            //	output.HasProgressionLevelDisplay = output.ProgressionLevel.PrefLabel;
            //}
            //20-10-28 now storing separated list
            if (!string.IsNullOrWhiteSpace(input.HasProgressionLevel))
            {
                string[] array = input.HasProgressionLevel.Split('|');
                if (array.Count() > 0)
                {
                    foreach (var i in array)
                    {
                        if (!string.IsNullOrWhiteSpace(i))
                        {
                            var pl = ConceptSchemeManager.GetByConceptCtid(i);
                            output.ProgressionLevels.Add(pl);

                            output.HasProgressionLevelDisplay += pl.PrefLabel + ", ";
                        }
                    }
                    output.HasProgressionLevelDisplay.Trim().TrimEnd(',');
                }
            }

            output.ProgramTerm    = input.ProgramTerm;
            output.SubjectWebpage = input.SubjectWebpage;
            output.SourceData     = input.SourceData;

            //where output store ComponentDesignation - textvalue
            //Json
            if (!string.IsNullOrEmpty(input.Properties))
            {
                PathwayComponentProperties pcp = JsonConvert.DeserializeObject <PathwayComponentProperties>(input.Properties);
                if (pcp != null)
                {
                    //unpack ComponentDesignation
                    output.ComponentDesignationList = pcp.ComponentDesignationList;
                    //credit value
                    output.CreditValue = pcp.CreditValue;
                    //this is now QuantitativeValue
                    output.PointValue = pcp.PointValue;

                    output.Identifier = new List <IdentifierValue>();
                    if (pcp.Identifier != null)
                    {
                        output.Identifier = pcp.Identifier;
                    }
                    if (pcp.SourceCredential != null && pcp.SourceCredential.Id > 0)
                    {
                        output.SourceCredential = pcp.SourceCredential;
                        output.SourceData       = "";
                    }
                    if (pcp.SourceAssessment != null && pcp.SourceAssessment.Id > 0)
                    {
                        output.SourceAssessment = pcp.SourceAssessment;
                        output.SourceData       = "";
                    }
                    if (pcp.SourceLearningOpportunity != null && pcp.SourceLearningOpportunity.Id > 0)
                    {
                        output.SourceLearningOpportunity = pcp.SourceLearningOpportunity;
                        output.SourceData = "";
                    }
                }
            }

            //
            if (IsValidDate(input.Created))
            {
                output.Created = ( DateTime )input.Created;
            }
            if (IsValidDate(input.LastUpdated))
            {
                output.LastUpdated = ( DateTime )input.LastUpdated;
            }
        }
Exemplo n.º 22
0
        public bool Save(ThisEntity entity, Guid parentUid, ref SaveStatus status)
        {
            bool isValid = true;

            if (!IsValidGuid(parentUid))
            {
                status.AddError("Error: a valid parent identifier was not provided.");
                return(false);
            }

            int    count  = 0;
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.EntityBaseId == 0)
            {
                status.AddError("Error - the parent entity was not found.");
                return(false);
            }

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

                    if (entity.Id == 0)
                    {
                        //add
                        efEntity          = new DBEntity();
                        efEntity.EntityId = parent.Id;
                        entity.ParentId   = parent.Id;
                        MapToDB(entity, efEntity, ref resetIsPrimaryFlag);

                        //could just have contact points without address
                        if (entity.HasAddress())
                        {
                            efEntity.Created = efEntity.LastUpdated = DateTime.Now;
                            if (IsValidGuid(entity.RowId))
                            {
                                efEntity.RowId = entity.RowId;
                            }
                            else
                            {
                                efEntity.RowId = Guid.NewGuid();
                            }

                            context.Entity_Address.Add(efEntity);
                            count = context.SaveChanges();

                            //update profile record so doesn't get deleted
                            entity.Id       = efEntity.Id;
                            entity.ParentId = parent.Id;
                            entity.RowId    = efEntity.RowId;
                            if (count == 0)
                            {
                                status.AddError(string.Format(" Unable to add address. parentUid: {0}, City: {1}, Region: {2} <br\\> ", parentUid, efEntity.City, efEntity.Region));
                            }
                            else
                            {
                                if (resetIsPrimaryFlag)
                                {
                                    Reset_Prior_ISPrimaryFlags(efEntity.EntityId, entity.Id);
                                }
                            }
                        }
                        //handle contact points
                        //if address present, these need to be closely related
                        if (entity.Id > 0)
                        {
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, entity.RowId, ref status);
                        }
                        else
                        {
                            // put under parent
                            //should log this. If under parent should onlybe an org, and delete all has already been done.
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, parentUid, ref status, false);
                        }
                    }
                    else
                    {
                        entity.ParentId = parent.Id;

                        efEntity = context.Entity_Address.SingleOrDefault(s => s.Id == entity.Id);
                        if (efEntity != null && efEntity.Id > 0)
                        {
                            entity.RowId = efEntity.RowId;
                            //update
                            MapToDB(entity, efEntity, ref resetIsPrimaryFlag);
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;

                                count = context.SaveChanges();
                            }
                            if (resetIsPrimaryFlag)
                            {
                                Reset_Prior_ISPrimaryFlags(entity.ParentId, entity.Id);
                            }

                            //handle contact points - very wierd approach, but shouldn't have updates
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, entity.RowId, ref status);
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                string message = HandleDBValidationError(dbex, thisClassName + ".Save() ", "Address Profile");
                status.AddError("Error - the save was not successful. " + message);
                LoggingHelper.LogError(dbex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                isValid = false;
            }
            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));
                isValid = false;
            }
            return(isValid);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Persist ConditionManifest
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="parentUid"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, ref SaveStatus status)
        {
            bool isValid = true;

            //will not have a parent Guid - should be the entity.OwningAgentUid
            //Guid parentUid = entity.OwningAgentUid;

            if (!IsValidGuid(entity.OwningAgentUid))
            {
                status.AddError("Error: the parent identifier was not provided.");
                return(false);
            }

            int count = 0;

            DBEntity efEntity    = new DBEntity();
            int      parentOrgId = 0;

            Guid   condtionManifestParentUid = new Guid();
            Entity parent = EntityManager.GetEntity(entity.OwningAgentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddError("Error - the entity for the parent organization was not found.");
                return(false);
            }
            if (parent.EntityTypeId == CodesManager.ENTITY_TYPE_ORGANIZATION)
            {
                parentOrgId = parent.EntityBaseId;
                condtionManifestParentUid = parent.EntityUid;
                //no common condition in this context
            }


            using (var context = new EntityContext())
            {
                try
                {
                    bool isEmpty = false;

                    if (ValidateProfile(entity, ref isEmpty, ref status) == false)
                    {
                        return(false);
                    }
                    if (isEmpty)
                    {
                        status.AddWarning("The Condition Manifest Profile is empty. ");
                        return(false);
                    }

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

                        efEntity.OrganizationId = parentOrgId;
                        efEntity.EntityStateId  = 3;
                        efEntity.Created        = efEntity.LastUpdated = DateTime.Now;

                        if (IsValidGuid(entity.RowId))
                        {
                            efEntity.RowId = entity.RowId;
                        }
                        else
                        {
                            efEntity.RowId = Guid.NewGuid();
                        }

                        context.ConditionManifest.Add(efEntity);
                        count = context.SaveChanges();

                        entity.Id    = efEntity.Id;
                        entity.RowId = efEntity.RowId;
                        if (count == 0)
                        {
                            status.AddError(" Unable to add Condition Manifest Profile");
                        }
                        else
                        {
                            //create the Entity.ConditionManifest
                            //ensure to handle this properly when adding a commonCondition CM to a CM
                            Entity_HasConditionManifest_Add(condtionManifestParentUid, efEntity.Id, ref status);

                            if (!UpdateParts(entity, ref status))
                            {
                                isValid = false;
                            }

                            SiteActivity sa = new SiteActivity()
                            {
                                ActivityType     = "ConditionManifest",
                                Activity         = "Import",
                                Event            = "Add",
                                Comment          = string.Format("ConditionManifest was added by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                ActivityObjectId = entity.Id
                            };
                            new ActivityManager().SiteActivityAdd(sa);
                            // a trigger is used to create the entity Object.
                        }
                    }
                    else
                    {
                        efEntity = context.ConditionManifest.SingleOrDefault(s => s.Id == entity.Id);
                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //delete the entity and re-add
                            //Entity e = new Entity()
                            //{
                            //	EntityBaseId = efEntity.Id,
                            //	EntityTypeId = CodesManager.ENTITY_TYPE_CONDITION_MANIFEST,
                            //	EntityType = "ConditionManifest",
                            //	EntityUid = efEntity.RowId,
                            //	EntityBaseName = efEntity.Name
                            //};
                            //if ( entityMgr.ResetEntity( e, ref statusMessage ) )
                            //{

                            //}

                            entity.RowId = efEntity.RowId;
                            //update
                            MapToDB(entity, efEntity);
                            //assume and validate, that if we get here we have a full record
                            if ((efEntity.EntityStateId ?? 1) == 1)
                            {
                                efEntity.EntityStateId = 3;
                            }

                            //has changed?
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;

                                count = context.SaveChanges();
                            }
                            else
                            {
                                //update entity.LastUpdated - assuming there has to have been some change in related data
                                new EntityManager().UpdateModifiedDate(entity.RowId, ref status);
                            }

                            if (!UpdateParts(entity, ref status))
                            {
                                isValid = false;
                            }

                            SiteActivity sa = new SiteActivity()
                            {
                                ActivityType     = "ConditionManifest",
                                Activity         = "Import",
                                Event            = "Update",
                                Comment          = string.Format("ConditionManifest was updated by the import. Name: {0}, SWP: {1}", entity.Name, entity.SubjectWebpage),
                                ActivityObjectId = entity.Id
                            };
                            new ActivityManager().SiteActivityAdd(sa);
                        }
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Save() ", "ConditionManifest");
                    status.AddError("Error - the save was not successful. " + message);
                    LoggingHelper.LogError(dbex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                    isValid = false;
                }
                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));
                    isValid = false;
                }
            }



            return(isValid);
        }
Exemplo n.º 24
0
        } //

        public int Save(int entityId, Guid targetUid, int roleId
                        , ref SaveStatus status)
        {
            int newId = 0;

            //assume if all empty, then ignore
            if (entityId == 0 || !IsValidGuid(targetUid) || roleId < 1)
            {
                status.AddError(thisClassName + string.Format(".Save() Error: invalid request, please provide a valid entityId: {0}, RoleId: {1}, and AgenUtid: {2}.", entityId, roleId, targetUid));
                return(newId);
            }

            //TODO - update this method
            //a role could exist
            if (AgentEntityRoleExists(entityId, targetUid, roleId))
            {
                //status.AddError( "Error: the selected relationship already exists!" );
                return(0);
            }

            EM.Entity_Assertion efEntity = new EM.Entity_Assertion();

            //TODO - need to get entity and type, otherwise set pending
            Entity targetEntity = EntityManager.GetEntity(targetUid);

            if (targetEntity == null || targetEntity.Id == 0)
            {
                //don't show in messages, no action possible
                //status.AddWarning( thisClassName + ".Save() Warning: the selected entity was not found yet. Need to check later. Setting to pending" );
                efEntity.IsPending = true;
                //may want to log an activity - would allow for queries, or the equivalent to the search reindex
                LoggingHelper.DoTrace(5, thisClassName + string.Format(".Save. The target Entity was not found, for entityId: {0}, targetUid:{1}, RoleId: {2}", entityId, targetUid, roleId));
                return(0);
            }
            else
            {
                efEntity.TargetEntityTypeId = targetEntity.EntityTypeId;
                //TODO - definition of IsPending
                efEntity.IsPending = false;
            }

            using (var context = new EntityContext())
            {
                //add


                efEntity.EntityId        = entityId;
                efEntity.TargetEntityUid = targetUid;
                efEntity.AssertionTypeId = roleId;
                efEntity.IsInverseRole   = false; //should remove this, as never inverse

                efEntity.Created = System.DateTime.Now;

                context.Entity_Assertion.Add(efEntity);

                // submit the change to database
                int count = context.SaveChanges();
                newId = efEntity.Id;
                //assertions are by the current org, so a separate request to reindex should not be necessary!
            }

            return(newId);
        }
        /// <summary>
        /// Add an Entity_EarningsProfile
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="EarningsProfileId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public int Add(Guid parentUid,
                       int earningsProfileId,
                       ref SaveStatus status)
        {
            int id    = 0;
            int count = 0;

            if (earningsProfileId == 0)
            {
                status.AddError(string.Format("A valid EarningsProfile identifier was not provided to the {0}.EntityEarnings_Add method.", thisClassName));
                return(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 = context.Entity_EarningsProfile
                               .FirstOrDefault(s => s.EntityId == parent.Id && s.EarningsProfileId == earningsProfileId);

                    if (efEntity != null && efEntity.Id > 0)
                    {
                        return(0);
                    }

                    efEntity                   = new DBEntity();
                    efEntity.EntityId          = parent.Id;
                    efEntity.EarningsProfileId = earningsProfileId;
                    efEntity.Created           = System.DateTime.Now;

                    context.Entity_EarningsProfile.Add(efEntity);

                    // submit the change to database
                    count = context.SaveChanges();
                    if (count > 0)
                    {
                        if (efEntity.Id == 0)
                        {
                            List <string> messages = new List <string>();
                            Delete(efEntity.Id, ref messages);

                            context.Entity_EarningsProfile.Add(efEntity);
                            count = context.SaveChanges();
                            id    = efEntity.Id;
                        }
                        else
                        {
                            id = efEntity.Id;
                        }
                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                        status.AddError(thisClassName + "Error - the add was not successful.");
                        string message = thisClassName + string.Format(".Add Failed", "Attempted to add an Entity_EarningsProfile. The process appeared to not work, but there was no exception, so we have no message, or no clue. Parent Profile: {0}, Type: {1}, EarningsId: {2}", parentUid, parent.EntityType, earningsProfileId);
                        EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "Entity_Earnings");
                    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);
        }
        /// <summary>
        /// Add a jurisdiction profile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="property">Can be blank. Set to a property where additional validation is necessary</param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Add(ThisEntity entity, string property, ref SaveStatus status, int assertedInTypeId = 0)
        {
            bool isValid = true;

            using (var context = new EntityContext())
            {
                if (entity == null || !IsValidGuid(entity.ParentEntityUid))
                {
                    status.AddWarning("Error - missing an identifier for the JurisdictionProfile");
                    return(false);
                }

                //ensure we have a parentId/EntityId
                Entity parent = EntityManager.GetEntity(entity.ParentEntityUid);
                if (parent == null || parent.Id == 0)
                {
                    status.AddWarning("Error - the parent entity was not found.");
                    return(false);
                }

                //check for Empty
                //==> not sure what is the minimum required fields!
                bool isEmpty = false;

                if (ValidateProfile(entity, property, ref isEmpty, ref status) == false)
                {
                    return(false);
                }
                if (isEmpty)
                {
                    //status.AddWarning( "Error - Jurisdiction profile is empty. " );
                    return(false);
                }


                //id = JurisdictionProfile_Add( entity, ref status );
                DBEntity efEntity = new DBEntity();
                MapToDB(entity, efEntity);
                efEntity.EntityId = parent.Id;
                if (IsValidGuid(entity.RowId))
                {
                    efEntity.RowId = entity.RowId;
                }
                else
                {
                    efEntity.RowId = Guid.NewGuid();
                }

                entity.RowId = efEntity.RowId;

                if (efEntity.JProfilePurposeId == null || efEntity.JProfilePurposeId == 0)
                {
                    efEntity.JProfilePurposeId = 1;
                }

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

                context.Entity_JurisdictionProfile.Add(efEntity);

                int count = context.SaveChanges();
                if (count > 0)
                {
                    entity.Id = efEntity.Id;
                    //update parts
                    UpdateParts(entity, true, ref status);
                    //??????? why
                    //UpdateJPRegions( entity,  ref status );
                }
            }

            return(isValid);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Persist ContactPoint
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="parentUid"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, Guid parentUid, ref SaveStatus status)
        {
            bool     isValid  = true;
            int      count    = 0;
            DBEntity efEntity = new DBEntity();

            if (!IsValidGuid(parentUid))
            {
                status.AddWarning("Error: the parent identifier was not provided.");
                return(false);
            }

            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                status.AddWarning("Error - the parent entity was not found.");
                return(false);
            }
            using (var context = new EntityContext())
            {
                if (ValidateProfile(entity, ref status) == false)
                {
                    return(false);
                }


                if (entity.Id == 0)
                {
                    //add
                    efEntity = new DBEntity();
                    MapToDB(entity, efEntity);
                    efEntity.ParentEntityId = parent.Id;

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

                    context.Entity_ContactPoint.Add(efEntity);
                    count = context.SaveChanges();
                    //update profile record so doesn't get deleted
                    entity.Id       = efEntity.Id;
                    entity.ParentId = parent.Id;
                    entity.RowId    = efEntity.RowId;
                    if (count == 0)
                    {
                        status.AddWarning(string.Format(" Unable to add Contact Point: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.ProfileName) ? "no description" : entity.ProfileName));
                    }
                    else
                    {
                        UpdateParts(entity, ref status);
                    }
                }
                else
                {
                    entity.ParentId = parent.Id;

                    efEntity = context.Entity_ContactPoint.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))
                        {
                            efEntity.LastUpdated = System.DateTime.Now;
                            count = context.SaveChanges();
                        }
                        //always check parts
                        UpdateParts(entity, ref status);
                    }
                }
            }

            return(isValid);
        }
        /// <summary>
        /// Get all learning opportunties for the parent
        /// Uses the parent Guid to retrieve the related Entity, then uses the EntityId to retrieve the child objects.
        /// </summary>
        /// <param name="parentUid"></param>
        /// <param name="forProfilesList"></param>
        /// <returns></returns>
        public static List <ThisEntity> LearningOpps_GetAll(Guid parentUid,
                                                            bool forProfilesList,
                                                            bool isForCredentialDetails = false, int relationshipTypeId = 1)
        {
            List <ThisEntity> list   = new List <ThisEntity>();
            ThisEntity        entity = new ThisEntity();

            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.Id == 0)
            {
                return(list);
            }
            //TODO - this was left over from the publisher, needs to be cleaned up
            bool includingProperties = isForCredentialDetails;
            bool includingProfiles   = false;

            if (isForCredentialDetails)
            {
                includingProperties = true;
                includingProfiles   = true;
            }
            LoggingHelper.DoTrace(7, string.Format("Entity_LearningOpps_GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId));
            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_LearningOpportunity
                                              .Where(s => s.EntityId == parent.Id && s.RelationshipTypeId == relationshipTypeId)
                                              .OrderBy(s => s.LearningOpportunity.Name)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new ThisEntity();
                            if (item.LearningOpportunity != null && item.LearningOpportunity.EntityStateId > 1)
                            {
                                if (forProfilesList || isForCredentialDetails)
                                {
                                    LearningOpportunityManager.MapFromDB_Basic(item.LearningOpportunity, entity,
                                                                               true);

                                    if (isForCredentialDetails)
                                    {
                                        entity.EstimatedDuration = DurationProfileManager.GetAll(entity.RowId);
                                        LearningOpportunityManager.MapFromDB_HasPart(entity, false);
                                        LearningOpportunityManager.MapFromDB_Competencies(entity);
                                    }
                                    list.Add(entity);
                                }
                                else
                                {
                                    if (CacheManager.IsLearningOpportunityAvailableFromCache(item.LearningOpportunityId, ref entity))
                                    {
                                        list.Add(entity);
                                    }
                                    else
                                    {
                                        //TODO - is this section used??
                                        //to determine minimum needed for a or detail page
                                        LearningOpportunityManager.MapFromDB(item.LearningOpportunity, entity,
                                                                             includingProperties,
                                                                             includingProfiles,
                                                                             false //includeWhereUsed
                                                                             );
                                        list.Add(entity);
                                        if (entity.HasPart.Count > 0)
                                        {
                                            CacheManager.AddLearningOpportunityToCache(entity);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return(list);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".LearningOpps_GetAll. Guid: {0}, parentType: {1} ({2}), ", parentUid, parent.EntityType, parent.EntityBaseId));
            }
            return(list);
        }
Exemplo n.º 29
0
        }         //

        public static List <OrganizationRoleProfile> GetAllCombinedForOrganization(Guid agentUid, ref int totalRecords, int maxRecords = 25)
        {
            OrganizationRoleProfile        orp  = new OrganizationRoleProfile();
            List <OrganizationRoleProfile> list = new List <OrganizationRoleProfile>();
            EnumeratedItem eitem = new EnumeratedItem();

            Guid   prevTargetUid  = new Guid();
            string prevRoleSource = "";
            int    prevRoleTypeId = 0;
            Entity agentEntity    = EntityManager.GetEntity(agentUid);

            if (UtilityManager.GetAppKeyValue("envType") == "production")
            {
                //show all for now in production
                //maxRecords = 0;
            }
            using (var context = new ViewContext())
            {
                //first check how long this step takes
                DateTime start = DateTime.Now;
                LoggingHelper.DoTrace(4, "GetAllCombinedForOrganization start");
                List <Views.Organization_CombinedQAPerformed> agentRoles = context.Organization_CombinedQAPerformed
                                                                           .Where(s => s.OrgUid == agentUid &&
                                                                                  s.IsQARole == true &&
                                                                                  s.TargetEntityStateId > 1)
                                                                           .OrderBy(s => s.TargetEntityTypeId)
                                                                           .ThenBy(s => s.TargetOwningOrganizationName)
                                                                           .ThenBy(s => s.TargetEntityName)
                                                                           .ThenBy(s => s.AgentToSourceRelationship)
                                                                           .ThenBy(s => s.roleSource)
                                                                           .ToList();

                DateTime end     = DateTime.Now;
                var      elasped = end.Subtract(start).TotalSeconds;
                LoggingHelper.DoTrace(4, string.Format("GetAllCombinedForOrganization retrieve seconds: {0}", elasped));

                if (agentRoles != null && agentRoles.Count() > 0)
                {
                    //
                    totalRecords = agentRoles.Count();
                    //may want a fudge factor?
                }
                int cntr = 0;
                foreach (var entity in agentRoles)
                {
                    cntr++;
                    //loop until change in entity type?
                    if (prevTargetUid != entity.TargetEntityUid)
                    {
                        //handle previous fill
                        if (IsGuidValid(prevTargetUid) && prevRoleTypeId > 0)
                        {
                            orp.AgentRole.Items.Add(eitem);
                            list.Add(orp);
                            if (maxRecords > 0 && cntr >= maxRecords)
                            {
                                break;
                            }
                        }

                        prevTargetUid  = entity.TargetEntityUid;
                        prevRoleSource = entity.roleSource;
                        prevRoleTypeId = entity.RelationshipTypeId;

                        orp = new OrganizationRoleProfile
                        {
                            Id             = 0,
                            ParentId       = agentEntity.EntityBaseId,
                            ParentTypeId   = agentEntity.EntityTypeId,
                            ProfileSummary = entity.TargetEntityName,

                            AgentRole = CodesManager.GetEnumeration(CodesManager.PROPERTY_CATEGORY_ENTITY_AGENT_ROLE)
                        };
                        orp.AgentRole.ParentId = entity.OrgId;

                        orp.AgentRole.Items  = new List <EnumeratedItem>();
                        orp.SourceEntityType = entity.TargetEntityType;

                        if (entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_CREDENTIAL)
                        {
                            //17-08-27 mp - just get the basic for each entity!
                            orp.TargetCredential = CredentialManager.GetBasic(entity.TargetEntityBaseId ?? 0);
                        }
                        else if (entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ORGANIZATION)
                        {
                            //orp.TargetOrganization = OrganizationManager.GetBasics( entity.TargetEntityUid );
                            orp.TargetOrganization.Id    = entity.TargetEntityBaseId ?? 0;
                            orp.TargetOrganization.RowId = entity.TargetEntityUid;
                            orp.TargetOrganization.Name  = entity.TargetEntityName;

                            orp.TargetOrganization.Description    = entity.TargetEntityDescription;
                            orp.TargetOrganization.EntityStateId  = entity.TargetEntityStateId ?? 2;
                            orp.TargetOrganization.SubjectWebpage = entity.TargetEntitySubjectWebpage;
                            orp.TargetOrganization.Image          = entity.TargetEntityImageUrl;
                        }
                        else if (entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE)
                        {
                            orp.TargetAssessment = AssessmentManager.GetBasic(entity.TargetEntityBaseId ?? 0);
                        }
                        else if (entity.TargetEntityTypeId == CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE)
                        {
                            orp.TargetLearningOpportunity = LearningOpportunityManager.GetBasic(entity.TargetEntityBaseId ?? 0);
                        }
                    }

                    /* either first one for new target
                     * or change in relationship
                     * or change in role source
                     */

                    if (prevRoleTypeId == entity.RelationshipTypeId)
                    {
                        if (prevRoleSource != entity.roleSource)
                        {
                            if (entity.roleSource == "DirectAssertion")
                            {
                                eitem.IsDirectAssertion = true;
                            }
                            else
                            {
                                eitem.IsIndirectAssertion = true;
                            }

                            //add previous
                            //could get a dup if there is an immediate chg in target,
                            //orp.AgentRole.Items.Add( eitem );
                            prevRoleSource = entity.roleSource;

                            continue;
                        }
                    }
                    else
                    {
                        //if not equal, add previous, and initialize next one (fall thru)
                        orp.AgentRole.Items.Add(eitem);
                    }

                    //add relationship
                    eitem = new EnumeratedItem
                    {
                        Id         = entity.RelationshipTypeId,
                        Name       = entity.AgentToSourceRelationship,
                        SchemaName = entity.ReverseSchemaTag,
                        IsQAValue  = true
                    };
                    //eitem.CodeId = entity.RelationshipTypeId;

                    prevRoleTypeId = entity.RelationshipTypeId;
                    prevRoleSource = entity.roleSource;
                    if (entity.roleSource == "DirectAssertion")
                    {
                        eitem.IsDirectAssertion = true;
                    }
                    else
                    {
                        eitem.IsIndirectAssertion = true;
                    }

                    //eitem.Name = entity.AgentToSourceRelationship;
                    //               eitem.SchemaName = entity.ReverseSchemaTag;

                    //               orp.AgentRole.Items.Add( eitem );
                } //end
                //check for remaining
                if (IsGuidValid(prevTargetUid) && orp.AgentRole.Items.Count > 0)
                {
                    orp.AgentRole.Items.Add(eitem);
                    list.Add(orp);
                }

                DateTime listEnd = DateTime.Now;
                elasped = listEnd.Subtract(end).TotalSeconds;
                LoggingHelper.DoTrace(4, string.Format("GetAllCombinedForOrganization loaded list seconds: {0}", elasped));
            }
            return(list);
        } //
        public static void MapFromDB(DBEntity input, ThisEntity output,
                                     bool includingParts)
        {
            output.Id            = input.Id;
            output.RowId         = input.RowId;
            output.EntityStateId = input.EntityStateId;
            output.Name          = input.Name == null ? "" : input.Name;
            output.Description   = input.Description == null ? "" : input.Description;
            output.CTID          = input.CTID;
            if (IsValidDate(input.DateEffective))
            {
                output.DateEffective = (( DateTime )input.DateEffective).ToString("yyyy-MM-dd");
            }
            else
            {
                output.DateEffective = "";
            }
            //
            //output.JobsObtained = input.JobsObtained ?? 0;
            if (!string.IsNullOrEmpty(input.JobsObtainedJson))
            {
                var jp = JsonConvert.DeserializeObject <EmploymentOutcomeProfileProperties>(input.JobsObtainedJson);
                if (jp != null)
                {
                    //unpack JobsObtainedList
                    output.JobsObtainedList = jp.JobsObtainedList;
                }
            }

            output.Source = GetUrlData(input.Source);

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

            if (string.IsNullOrWhiteSpace(output.CTID) || output.EntityStateId < 3)
            {
                output.IsReferenceVersion = true;
                return;
            }
            //=====
            var relatedEntity = EntityManager.GetEntity(output.RowId, false);

            if (relatedEntity != null && relatedEntity.Id > 0)
            {
                output.EntityLastUpdated = relatedEntity.LastUpdated;
            }

            //components
            if (includingParts)
            {
                //
                output.Jurisdiction = Entity_JurisdictionProfileManager.Jurisdiction_GetAll(output.RowId);
                //get datasetprofiles
                output.RelevantDataSet = DataSetProfileManager.GetAll(output.RowId, true);
            }
        }         //