private int HandlePathwayComponent(PathwayComponent input, Pathway pathway, ref PathwayComponent output, ref bool recordExists, ref SaveStatus status)
        {
            List <string> messages = new List <string>();

            //the record may be ready to save??
            //
            if (DoesComponentExist(input, pathway.CTID, ref output))
            {
                input.Id     = output.Id;
                recordExists = true;
                //delete any existing conditions
                new PathwayComponentConditionManager().DeleteAll(input.Id, status);
            }
            else
            {
                output.PathwayCTID = pathway.CTID;
                //if ( BaseFactory.IsGuidValid( input.RowId ) )
                //	output.RowId = input.RowId;
            }

            new PathwayComponentManager().Save(input, ref status);


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

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

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

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

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

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

            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".AddPendingRecord. entityUid:  {0}, ctid: {1}", entityUid, ctid));
                status = thisClassName + " Error - the save was not successful. " + message;
            }
            return(0);
        }
        //
        #endregion

        #region ComponentRetrievals
        public static PathwayComponent GetComponentByCtid(string ctid)
        {
            PathwayComponent entity = new PathwayComponent();

            if (string.IsNullOrWhiteSpace(ctid))
            {
                return(entity);
            }

            return(PathwayComponentManager.GetByCtid(ctid));
        }
Exemple #4
0
        public bool DoesComponentExist(string ctid, ref OutputComponent entity)
        {
            bool exists = false;

            entity = EntityServices.GetComponentByCtid(ctid);
            if (entity != null && entity.Id > 0)
            {
                return(true);
            }

            return(exists);
        }
        public static void MapToDB(ThisEntity input, DBEntity output)
        {
            output.Id = input.Id;
            if (output.Id < 1)
            {
                //will need output be carefull here, will this exist in the input??
                //there could be a case where an external Id was added output bulk upload for an existing record
                output.PathwayCTID = input.PathwayCTID;
            }
            else
            {
                //don't map rowId, CTID, or dates as not on form
                //output.RowId = input.RowId;
                output.Name        = input.Name;
                output.Description = input.Description;
                //output.CodedNotation = input.CodedNotation;
                output.EntityStateId     = 3;
                output.ComponentCategory = input.ComponentCategory;
                output.ComponentTypeId   = GetComponentTypeId(input.PathwayComponentType);
                if (string.IsNullOrWhiteSpace(output.PathwayCTID))
                {
                    output.PathwayCTID = input.PathwayCTID;
                }
                //output.ComponentTypeId = input.ComponentTypeId;
                //will be validated before getting here!
                output.CredentialType = input.CredentialType;

                //output.ExternalIdentifier = input.ExternalIdentifier;
                //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.HasProgressionLevels;
                if (input.HasProgressionLevels.Any())
                {
                    output.HasProgressionLevel = string.Join("|", input.HasProgressionLevels.ToArray());
                }
                else
                {
                    output.HasProgressionLevel = null;
                }

                //need output change ??
                //output.IsDestinationComponentOf = input.IsDestinationComponentOf;
                //this is now in JsonProperties
                //output.PointValue = input.PointValueOld;
                output.ProgramTerm    = input.ProgramTerm;
                output.SubjectWebpage = input.SubjectWebpage;
                output.SourceData     = input.SourceData;

                output.Properties = JsonConvert.SerializeObject(input.JsonProperties);
            }
        }
        private bool DoesComponentExist(PathwayComponent input, string pathwayCTID, ref PathwayComponent record)
        {
            bool isFound = false;

            var exists = PathwayComponentManager.GetByCtid(input.CTID);

            if (exists != null && exists.Id > 0)
            {
                record  = exists;
                isFound = true;
            }

            return(isFound);
        }
        /// <summary>
        /// Get component by Guid
        /// </summary>
        /// <param name="id"></param>
        /// <param name="childComponentsAction">1-default of summary</param>
        /// <returns></returns>
        public static ThisEntity Get(Guid id, int childComponentsAction = 1)
        {
            ThisEntity entity = new ThisEntity();

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

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

            return(entity);
        }
        public bool UpdateParts(ThisEntity entity, ref SaveStatus status)
        {
            bool   isValid       = true;
            Entity relatedEntity = EntityManager.GetEntity(entity.RowId);

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

            //21-01-07 mparsons - Identifier will now be saved in the Json properties, not in Entity_IdentifierValue
            //new Entity_IdentifierValueManager().SaveList( entity.Identifier, entity.RowId, Entity_IdentifierValueManager.CREDENTIAL_Identifier, ref status, false );
            Entity_CredentialManager ecm = new Entity_CredentialManager();

            ecm.DeleteAll(relatedEntity, ref status);
            //
            var eam = new Entity_AssessmentManager();

            eam.DeleteAll(relatedEntity, ref status);
            //
            var elom = new Entity_LearningOpportunityManager();

            elom.DeleteAll(relatedEntity, ref status);
            int newId = 0;

            if (entity.JsonProperties != null)
            {
                if (entity.JsonProperties.SourceCredential != null && entity.JsonProperties.SourceCredential.Id > 0)
                {
                    ecm.Add(entity.RowId, entity.JsonProperties.SourceCredential.Id, BaseFactory.RELATIONSHIP_TYPE_IS_PART_OF, ref newId, ref status);
                }
                if (entity.JsonProperties.SourceAssessment != null && entity.JsonProperties.SourceAssessment.Id > 0)
                {
                    eam.Add(entity.RowId, entity.JsonProperties.SourceAssessment.Id, BaseFactory.RELATIONSHIP_TYPE_IS_PART_OF, false, ref status);
                }
                if (entity.JsonProperties.SourceLearningOpportunity != null && entity.JsonProperties.SourceLearningOpportunity.Id > 0)
                {
                    elom.Add(entity.RowId, entity.JsonProperties.SourceLearningOpportunity.Id, BaseFactory.RELATIONSHIP_TYPE_IS_PART_OF, false, ref status);
                }
            }
            return(isValid);
        }
        //
        public static List <ThisEntity> GetAllForPathway(string pathwayCTID, int childComponentsAction = 2)
        {
            var output = new List <ThisEntity>();
            var entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                var list = context.PathwayComponent
                           .Where(s => s.PathwayCTID == pathwayCTID)
                           .ToList();
                foreach (var item in list)
                {
                    entity = new ThisEntity();
                    //when called via a pathway getAll, the subcomponents will be useally lists, and the detailed component will be in the hasPart
                    MapFromDB(item, entity, childComponentsAction);
                    output.Add(entity);
                }
            }

            return(output);
        }
Exemple #10
0
        //
        /// <summary>
        /// Handle component import
        /// TODO - should a save be done for each component or wait until the end
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pathway"></param>
        /// <param name="bnodes"></param>
        /// <param name="status">TODO - do we want to continue using the pathway SaveStatus?</param>
        /// <returns></returns>
        public OutputComponent ImportComponent(InputComponent input, ThisEntity pathway, List <BNode> bnodes, SaveStatus status)
        {
            MappingHelperV3 helper = new MappingHelperV3(CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT);

            //do we need to reference blank nodes here? - if so pass to this method
            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();
            OutputComponent output = new OutputComponent();

            //
            LoggingHelper.DoTrace(5, "======== Component ======== ");
            LoggingHelper.DoTrace(5, "		type: "+ input.PathwayComponentType.ToString());
            LoggingHelper.DoTrace(5, "		name: "+ (input.Name ?? new JInput.LanguageMap("componentNameMissing")).ToString());
            LoggingHelper.DoTrace(5, "		ctid: "+ input.CTID);
            LoggingHelper.DoTrace(6, "		@Id: "+ input.CtdlId);

            try
            {
                //add/updating Pathway
                if (!DoesComponentExist(input.CTID, ref output))
                {
                    //set the rowid now, so that can be referenced as needed
                    //no, the guid comes from the resolving of entity references
                    //actually OK, as earlier references would result in a pending record
                    output.RowId = Guid.NewGuid();
                }
                helper.currentBaseObject = output;
                if (input.CTID == "ce-fa6c139f-0615-401f-9920-6ec8c445baca")
                {
                }
                //initialize json properties
                output.JsonProperties = new PathwayComponentProperties();
                //
                output.PathwayComponentType = input.PathwayComponentType;
                output.Name           = helper.HandleLanguageMap(input.Name, output, "Name");
                output.Description    = helper.HandleLanguageMap(input.Description, output, "Description");
                output.SubjectWebpage = input.SubjectWebpage;
                output.SourceData     = input.SourceData;

                if (!string.IsNullOrWhiteSpace(output.SourceData) && output.SourceData.IndexOf("/resources/") > 0)
                {
                    var ctid = ResolutionServices.ExtractCtid(output.SourceData);
                    if (!string.IsNullOrWhiteSpace(ctid))
                    {
                        if (output.PathwayComponentType.ToLower().IndexOf("credential") > -1)
                        {
                            var target = CredentialManager.GetMinimumByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //this approach 'buries' the cred from external references like credential in pathway
                                output.SourceCredential = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceCredential = output.SourceCredential;
                            }
                        }
                        else if (output.PathwayComponentType.ToLower().IndexOf("assessmentcomp") > -1)
                        {
                            var target = AssessmentManager.GetSummaryByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //may not really need this, just the json
                                output.SourceAssessment = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceAssessment = output.SourceAssessment;
                            }
                        }
                        else if (output.PathwayComponentType.ToLower().IndexOf("coursecomp") > -1)
                        {
                            var target = LearningOpportunityManager.GetByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //may not really need this, just the json
                                output.SourceLearningOpportunity = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceLearningOpportunity = output.SourceLearningOpportunity;
                            }
                        }
                    }
                }

                output.CTID        = input.CTID;
                output.PathwayCTID = pathway.CTID;


                //output.CodedNotation = input.CodedNotation;
                output.Identifier = helper.MapIdentifierValueListInternal(input.Identifier);
                if (output.Identifier != null && output.Identifier.Count() > 0)
                {
                    output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
                }
                //
                output.ComponentDesignationList = helper.MapCAOListToList(input.ComponentDesignation);

                //
                output.CredentialType = input.CredentialType;
                output.CreditValue    = helper.HandleValueProfileList(input.CreditValue, output.PathwayComponentType + ".CreditValue");

                //TBD - how to handle. Will need to have imported the concept scheme/concept
                if (input.HasProgressionLevel != null && input.HasProgressionLevel.Any())
                {
                    foreach (var item in input.HasProgressionLevel)
                    {
                        output.HasProgressionLevels.Add(ResolutionServices.ExtractCtid(item));
                    }
                }

                output.PointValue = helper.HandleQuantitiveValue(input.PointValue, output.PathwayComponentType + ".PointValue");

                //
                output.ProgramTerm = helper.HandleLanguageMap(input.ProgramTerm, output, "ProgramTerm");
                //need to get relationshiptype to store-> this can be done by manager
                //3
                output.HasChildList = helper.MapEntityReferenceGuids("PathwayComponent.HasChild", input.HasChild, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);
                //2
                output.HasIsChildOfList = helper.MapEntityReferenceGuids("PathwayComponent.IsChildOf", input.IsChildOf, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                output.HasPrerequisiteList = helper.MapEntityReferenceGuids("PathwayComponent.Prerequisite", input.Prerequisite, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);
                output.HasPreceedsList     = helper.MapEntityReferenceGuids("PathwayComponent.Preceeds", input.Preceeds, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                //populate JSON properties
                output.JsonProperties.ComponentDesignationList = output.ComponentDesignationList;
                output.JsonProperties.CreditValue = output.CreditValue;
                output.JsonProperties.Identifier  = output.Identifier;
                output.JsonProperties.PointValue  = output.PointValue;

                //
                if (input.HasCondition != null && input.HasCondition.Count() > 0)
                {
                    output.HasCondition = new List <PathwayComponentCondition>();
                    foreach (var item in input.HasCondition)
                    {
                        //var jcc = JsonConvert.DeserializeObject<JInput.ComponentCondition>( item.ToString() );
                        var cc = new PathwayComponentCondition();
                        cc.Name                   = helper.HandleLanguageMap(item.Name, cc, "ComponentCondition.Name");
                        cc.Description            = helper.HandleLanguageMap(item.Description, cc, "ComponentCondition.Description");
                        cc.RequiredNumber         = item.RequiredNumber;
                        cc.PathwayCTID            = pathway.CTID;
                        cc.HasTargetComponentList = helper.MapEntityReferenceGuids("ComponentCondition.TargetComponent", item.TargetComponent, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                        output.HasCondition.Add(cc);
                    }
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, "ImportPathways.ImportComponent");
                //status.AddError( string.Format( "ImportPathways.ImportComponent. ComponentType: {0}, Name: {1}, Message: {2}", output.ComponentTypeId, output.Name, ex.Message ) );
            }
            //then save
            return(output);
        }
        //


        /// <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;
            }
        }
        /// <summary>
        /// add a PathwayComponent
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public bool Save(ThisEntity entity, ref SaveStatus status)
        {
            bool isValid  = true;
            var  efEntity = new DBEntity();

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

                    if (entity.Id == 0)
                    {
                        MapToDB(entity, efEntity);

                        if (entity.RowId == null || entity.RowId == Guid.Empty)
                        {
                            efEntity.RowId = entity.RowId = Guid.NewGuid();
                        }
                        else
                        {
                            efEntity.RowId = entity.RowId;
                        }

                        efEntity.CTID    = "ce-" + efEntity.RowId.ToString().ToLower();
                        efEntity.Created = efEntity.LastUpdated = System.DateTime.Now;

                        context.PathwayComponent.Add(efEntity);

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

                            UpdateParts(entity, ref status);

                            return(true);
                        }
                        else
                        {
                            //?no info on error
                            status.AddError("Error - the profile was not saved. ");
                            string message = string.Format("PathwayComponentManager.Add Failed", "Attempted to add a PathwayComponent. The process appeared to not work, but was not an exception, so we have no message, or no clue.PathwayComponent. PathwayComponent: {0}, createdById: {1}", entity.Name, entity.CreatedById);
                            EmailManager.NotifyAdmin(thisClassName + ".Add Failed", message);
                        }
                    }
                    else
                    {
                        efEntity = context.PathwayComponent
                                   .SingleOrDefault(s => s.Id == entity.Id);

                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //for updates, chances are some fields will not be in interface, don't map these (ie created stuff)
                            MapToDB(entity, efEntity);
                            efEntity.EntityStateId = 3;
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;
                                int count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error
                                    status.AddError("Error - the update was not successful. ");
                                    string message = string.Format(thisClassName + ".Save Failed", "Attempted to update a PathwayComponent. The process appeared to not work, but was not an exception, so we have no message, or no clue. PathwayComponentId: {0}, Id: {1}, updatedById: {2}", entity.Id, entity.Id, entity.LastUpdatedById);
                                    EmailManager.NotifyAdmin(thisClassName + ". PathwayComponent_Update Failed", message);
                                }
                            }
                            //continue with parts regardless
                            UpdateParts(entity, ref status);
                        }
                        else
                        {
                            status.AddError("Error - update failed, as record was not found.");
                        }
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    //LoggingHelper.LogError( dbex, thisClassName + string.Format( ".ContentAdd() DBEntityValidationException, Type:{0}", entity.TypeId ) );
                    string message = thisClassName + string.Format(".Save() DBEntityValidationException, PathwayComponentId: {0}", entity.Id);
                    foreach (var eve in dbex.EntityValidationErrors)
                    {
                        message += string.Format("\rEntity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                 eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            message += string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                     ve.PropertyName, ve.ErrorMessage);
                        }

                        LoggingHelper.LogError(message, true);
                    }
                }
                catch (Exception ex)
                {
                    var message = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".PathwayComponent_Add(), PathwayComponentId: {0}", entity.ParentId));
                    status.AddError(string.Format("Error encountered saving component. Type: {0}, Name: {1}, Error: {2}. ", entity.PathwayComponentType, entity.Name, message));
                    isValid = false;
                }
            }

            return(isValid);
        }
        public void HandleComponents(ThisEntity pathway, ref SaveStatus status)
        {
            try
            {
                //components
                //delete all not in current list
                new Entity_PathwayComponentManager().DeleteNotInList(pathway.CTID, pathway.HasPart, ref status);
                //

                //TBD - should we do a fresh get of the pathway with components - or clear all?
                //handle components
                foreach (var item in pathway.HasPart)
                {
                    var component = new PathwayComponent();
                    //handle each component
                    //add to pathway HasParts on conclusion (with existance checking
                    var recordExists = false;
                    if (HandlePathwayComponent(item, pathway, ref component, ref recordExists, ref status) < 1)
                    {
                        status.RecordsFailed++;
                        continue;
                    }
                    else
                    {
                        if (recordExists)
                        {
                            status.RecordsUpdated++;
                        }
                        else
                        {
                            status.RecordsAdded++;
                        }
                    }

                    //add pathway HasPart for component
                    //?do we need has part in the finder?
                    //will be useful to retrieve data for the detail page
                    epcmgr.Add(pathway.RowId, component.Id, PathwayComponent.PathwayComponentRelationship_HasPart, ref status);
                }

                //handle conditions
                var candidates = pathway.HasPart.Where(s => s.HasCondition != null && s.HasCondition.Count() > 0).ToList();
                foreach (var pc in candidates)
                {
                    foreach (var item in pc.HasCondition)
                    {
                        //get parent component
                        var component = PathwayComponentManager.GetByCtid(pc.CTID);
                        if (component == null || component.Id == 0)
                        {
                            //shouldn't happen here - although the add attempt could have failed?
                            status.AddError(string.Format("The parent pathway component: {0} for ConditionComponent: {1} was not found. This could have been due the an issue adding the component - which should have resulted in an earlier error message.", pc.Name, item.Name));
                            continue;
                        }
                        var condition = new PathwayComponentCondition();
                        //add to pathway component Entity.HasPathwayComponent on conclusion

                        if (HandleComponentCondition(item, pathway, component, ref status) < 1)
                        {
                            status.RecordsFailed++;
                            //could continue if have an id (i.e. failed after saved)?
                            continue;
                        }
                    }
                }

                //now handle relationships
                int cntr = 0;
                foreach (var item in pathway.HasPart)
                {
                    cntr++;
                    var component = PathwayComponentManager.GetByCtid(item.CTID, PathwayComponentManager.componentActionOfNone);
                    //handle each component
                    //add to pathway HasParts on conclusion (with existance checking
                    ReplacePathwayComponentRelationships(cntr, component.RowId, item.HasChildList, pathway, PathwayComponent.PathwayComponentRelationship_HasChild, "PathwayComponent.HasChild", ref status);

                    ReplacePathwayComponentRelationships(cntr, component.RowId, item.HasPrerequisiteList, pathway, PathwayComponent.PathwayComponentRelationship_Prerequiste, "PathwayComponent.Prerequisite", ref status);
                    //
                    ReplacePathwayComponentRelationships(cntr, component.RowId, item.HasPreceedsList, pathway, PathwayComponent.PathwayComponentRelationship_Preceeds, "PathwayComponent.Preceeds", ref status);
                }

                //these may have to been done after processing components
                //================ destination component
                ReplacePathwayToPathwayComponentRelationships(pathway.HasDestinationList, pathway, PathwayComponent.PathwayComponentRelationship_HasDestinationComponent, "Pathway.HasDestinationComponent", ref status);
                //
                ReplacePathwayToPathwayComponentRelationships(pathway.HasChildList, pathway, PathwayComponent.PathwayComponentRelationship_HasChild, "Pathway.HasChild", ref status);
            }
            catch (Exception ex)
            {
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".HandleComponents. Pathway: {0} ({1}) Exception encountered: {2}", pathway.Name, pathway.Id, ex.Message));
                //only fail current, and allow to continue
                status.AddError(string.Format("Exception encountered. Pathway: {0}, Message: {1}", pathway.Name, ex.Message));

                LoggingHelper.LogError(ex, string.Format(thisClassName + ".HandleComponents. Pathway: {0} ({1}) Exception encountered", pathway.Name, pathway.Id));
            }
        }
        public static PathwayComponent GetComponentBasic(int id)
        {
            PathwayComponent entity = PathwayComponentManager.Get(id);

            return(entity);
        }
        private int HandleComponentCondition(PathwayComponentCondition input, Pathway pathway, PathwayComponent component, ref SaveStatus status)
        {
            int           newId         = 0;
            List <string> messages      = new List <string>();
            string        statusMessage = "";

            input.ParentComponentId = component.Id;
            if (pccm.Save(input, ref messages))
            {
                newId = input.Id;
                activityMgr.SiteActivityAdd(new SiteActivity()
                {
                    ActivityType     = "PathwayComponent",
                    Activity         = "Import",
                    Event            = "Add",
                    Comment          = string.Format("Added PathwayComponentCondition via Import: '{0}' for Component: '{1}'", input.Name, component.Name),
                    ActivityObjectId = newId,
                });
            }
            else
            {
                status.AddErrorRange(messages);
            }

            if (newId == 0 || (!string.IsNullOrWhiteSpace(statusMessage) && statusMessage != "successful"))
            {
                status.AddError(string.Format("Row: Issue encountered updating pathway ComponentCondition: {0} for Component: '{1}': {2}", input.Name, component.Name, statusMessage));
                return(0);
            }
            //==================================================


            //handle target components - better organization to move this to HandleComponentCondition since all components should now exist
            List <PathwayComponent> profiles = new List <PathwayComponent>();

            messages = new List <string>();
            foreach (var tc in input.HasTargetComponentList)
            {
                var targetComponent = PathwayComponentManager.Get(tc);
                if (targetComponent == null || targetComponent.Id == 0)
                {
                    //shouldn't happen here - although the add attempt could have failed?
                    status.AddError(string.Format("The target pathway component: {0} for ConditionComponent: {1} was not found. This could have been due the an issue adding the component - which should have resulted in an earlier error message.", tc, input.Name));
                    continue;
                }
                profiles.Add(targetComponent);
            }
            //now replace relationships
            if (!epcmgr.Replace(input.RowId, PathwayComponent.PathwayComponentRelationship_TargetComponent, profiles, ref status))
            {
                //status.AddErrorRange( messages );
            }

            return(newId);
        }