Beispiel #1
0
        public bool ValidateProfile(ThisEntity profile, ref bool isEmpty, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            isEmpty = false;

            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                status.AddWarning("A profile description must be entered");
            }

            if (!IsUrlValid(profile.SubjectWebpage, ref commonStatusMessage))
            {
                status.AddWarning("The Subject Webpage Url is invalid. " + commonStatusMessage);
            }
            if (!IsUrlValid(profile.VerificationServiceUrl, ref commonStatusMessage))
            {
                status.AddWarning("The Verification Service Url is invalid. " + commonStatusMessage);
            }
            if (!IsUrlValid(profile.VerificationDirectory, ref commonStatusMessage))
            {
                status.AddWarning("The Verification Directory Url is invalid. " + commonStatusMessage);
            }

            return(!status.HasSectionErrors);
        }
        public bool ValidateProfile(ThisEntity profile, ref bool isEmpty, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            //check if empty
            if (string.IsNullOrWhiteSpace(profile.ProfileName) &&
                string.IsNullOrWhiteSpace(profile.Description) &&
                string.IsNullOrWhiteSpace(profile.RevocationCriteriaUrl) &&
                string.IsNullOrWhiteSpace(profile.RevocationCriteriaDescription) &&
                string.IsNullOrWhiteSpace(profile.DateEffective) &&
                (profile.Jurisdiction == null || profile.Jurisdiction.Count == 0)
                )
            {
                isEmpty = true;
                return(false);
            }

            //date check, can this be in the future?
            if (!string.IsNullOrWhiteSpace(profile.DateEffective) &&
                !IsValidDate(profile.DateEffective))
            {
                status.AddWarning("Please enter a valid effective date");
            }
            if (!IsUrlValid(profile.RevocationCriteriaUrl, ref commonStatusMessage))
            {
                status.AddWarning("The 'Revocation Criteria Url' format is invalid. " + commonStatusMessage);
            }

            return(status.WasSectionValid);
        }
Beispiel #3
0
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            //
            if (string.IsNullOrWhiteSpace(profile.FrameworkName))
            {
                status.AddWarning(thisClassName + " - A Framework name must be entered");
            }

            if (!IsUrlValid(profile.Framework, ref commonStatusMessage))
            {
                status.AddWarning(thisClassName + " - The Framework Url is invalid " + commonStatusMessage);
            }

            if (!IsUrlValid(profile.TargetNode, ref commonStatusMessage))
            {
                status.AddWarning(thisClassName + " - The TargetNode Url is invalid " + commonStatusMessage);
            }
            if (!string.IsNullOrWhiteSpace(profile.AlignmentDate) &&
                IsValidDate(profile.AlignmentDate) == false)
            {
                status.AddWarning(thisClassName + " - The Alignment Date is invalid ");
            }

            return(!status.HasSectionErrors);
        }
Beispiel #4
0
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            if (string.IsNullOrWhiteSpace(profile.Name))
            {
                status.AddError("An Pathway name must be entered");
            }
            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                status.AddWarning("An Pathway Description must be entered");
            }
            if (!IsValidGuid(profile.OwningAgentUid))
            {
                status.AddWarning("An owning organization must be selected");
            }

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

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

            return(status.WasSectionValid);
        }
Beispiel #5
0
        public bool ValidateProfile(ThisEntity profile, ref bool isEmpty, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            isEmpty = false;
            //check if empty

            //&& ( profile.EstimatedCost == null || profile.EstimatedCost.Count == 0 )
            if (string.IsNullOrWhiteSpace(profile.ProfileName))
            {
                status.AddError("A Condition Manifest name must be entered");
            }
            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                status.AddWarning("A Condition Manifest Description must be entered");
            }

            //not sure if this will be selected, or by context
            if (!IsValidGuid(profile.OwningAgentUid))
            {
                status.AddError("An owning organization must be selected");
            }

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

            return(!status.HasSectionErrors);
        }
Beispiel #6
0
        public bool SaveList(List <ThisEntity> list, Guid parentUid, ref SaveStatus status, bool doingDelete = true)
        {
            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);
            }
            if (doingDelete)
            {
                DeleteAll(parent, ref status);
            }

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

            bool isAllValid = true;

            foreach (ThisEntity item in list)
            {
                Save(item, parentUid, ref status);
            }

            return(isAllValid);
        }
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            if (string.IsNullOrWhiteSpace(profile.ProfileName))
            {
                //status.AddError( "A profile name must be entered" );
            }
            //should be something else
            if (!IsUrlValid(profile.ProcessMethod, ref commonStatusMessage))
            {
                status.AddWarning("The Process Method Url is invalid. " + commonStatusMessage);
            }
            if (!IsUrlValid(profile.ProcessStandards, ref commonStatusMessage))
            {
                status.AddWarning("The Process Standards Url is invalid. " + commonStatusMessage);
            }
            if (!IsUrlValid(profile.ScoringMethodExample, ref commonStatusMessage))
            {
                status.AddWarning("The Scoring Method Example Url is invalid. " + commonStatusMessage);
            }
            if (!IsUrlValid(profile.SubjectWebpage, ref commonStatusMessage))
            {
                status.AddWarning("The Subject Webpage is invalid. " + commonStatusMessage);
            }


            return(status.WasSectionValid);
        }
Beispiel #8
0
        /// <summary>
        /// add a ConditionProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, DateTime updateDate, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

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

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

                    context.Entity_AggregateDataProfile.Add(efEntity);

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

                        UpdateParts(entity, updateDate, ref status);

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

            return(efEntity.Id);
        }
Beispiel #9
0
        public bool ValidateDurationProfile(ThisEntity profile, ref bool isEmpty, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            bool hasConditions = false;

            isEmpty = false;
            //string message = "";
            if (string.IsNullOrWhiteSpace(profile.Conditions) == false)
            {
                hasConditions = true;
            }
            bool hasExactDuration = false;
            bool hasRangeDuration = false;

            if (HasDurationItems(profile.ExactDuration))
            {
                hasExactDuration = true;
            }
            if (HasDurationItems(profile.MinimumDuration) || HasDurationItems(profile.MaximumDuration))
            {
                hasRangeDuration = true;
            }

            //validations should be done before here
            if (hasExactDuration)
            {
                if (hasRangeDuration)
                {
                    //inconsistent, take exact for now
                    status.AddWarning("Error - you must either enter an Exact duration or a Minimum/Maximum range duration but not both. For now, the exact duration was used");
                }
            }
            else if (hasRangeDuration == false && hasConditions == false)
            {
                //nothing,
                status.AddWarning("Error - you must enter either an Exact duration or a Minimum/Maximum range duration (but not both). <br/>");
                isEmpty = true;
            }
            //if ( !string.IsNullOrWhiteSpace( profile.ProfileName ) && profile.ProfileName.Length > 200 )
            //{
            //	//nothing,
            //	status.AddError( "Error - the profile name is too long, the maximum length is 200 characters.<br/>" );
            //	isValid = false;
            //	isEmpty = false;
            //}
            if (!string.IsNullOrWhiteSpace(profile.Conditions) && profile.Conditions.Length > 999)
            {
                //nothing,
                status.AddWarning("Error - the description is too long, the maximum length is 1000 characters.<br/>");
                isEmpty = false;
            }
            return(!status.HasSectionErrors);
        }
        }        //

        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            if (!IsUrlValid(profile.CostDetails, ref commonStatusMessage))
            {
                status.AddWarning("The Cost Details Url is invalid" + commonStatusMessage);
            }
            DateTime startDate = DateTime.Now;
            DateTime endDate   = DateTime.Now;

            if (!string.IsNullOrWhiteSpace(profile.DateEffective))
            {
                if (!IsValidDate(profile.DateEffective))
                {
                    status.AddWarning("Please enter a valid start date");
                }
                else
                {
                    DateTime.TryParse(profile.DateEffective, out startDate);
                }
            }
            if (!string.IsNullOrWhiteSpace(profile.ExpirationDate))
            {
                if (!IsValidDate(profile.ExpirationDate))
                {
                    status.AddWarning("Please enter a valid end date");
                }
                else
                {
                    DateTime.TryParse(profile.ExpirationDate, out endDate);
                    if (IsValidDate(profile.DateEffective) &&
                        startDate > endDate)
                    {
                        status.AddWarning("The end date must be greater than the start date.");
                    }
                }
            }
            //currency?
            //if ( string.IsNullOrWhiteSpace( profile.Currency ) == false )
            //{
            //	//length
            //	if ( profile.Currency.Length != 3 || IsInteger( profile.Currency ) )
            //	{
            //		status.AddError( "The currency code must be a three-letter alphabetic code  " );
            //		isValid = false;
            //	}
            //}

            return(!status.HasSectionErrors);
        }
Beispiel #11
0
        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);
        }
Beispiel #12
0
        /// <summary>
        /// Retrieve an resource from the registry by ctid and do import
        /// </summary>
        /// <param name="ctid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool ImportByResourceId(string ctid, SaveStatus status)
        {
            //this is currently specific, assumes envelop contains a credential
            //can use the hack fo GetResourceType to determine the type, and then call the appropriate import method
            string statusMessage = "";
            //EntityServices mgr = new EntityServices();
            string ctdlType = "";

            try
            {
                string payload = RegistryServices.GetResourceByCtid(ctid, ref ctdlType, ref statusMessage);

                if (!string.IsNullOrWhiteSpace(payload))
                {
                    input = JsonConvert.DeserializeObject <InputEntity>(payload.ToString());
                    //ctdlType = RegistryServices.GetResourceType( payload );
                    return(Import(input, "", status));
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".ImportByResourceId()");
                status.AddError(ex.Message);
                if (ex.Message.IndexOf("Path '@context', line 1") > 0)
                {
                    status.AddWarning("The referenced registry document is using an old schema. Please republish it with the latest schema!");
                }
                return(false);
            }
        }
        /// <summary>
        /// Check if the provided framework has already been sync'd.
        /// If not, it will be added.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <param name="messages"></param>
        /// <param name="frameworkId"></param>
        /// <returns></returns>
        //public bool HandleFrameworkRequest( CassFramework request,
        //		int userId,
        //		ref SaveStatus status,
        //		ref int frameworkId )
        //{
        //	bool isValid = true;
        //	if ( request == null || string.IsNullOrWhiteSpace(request._IdAndVersion) )
        //	{
        //		status.AddWarning( "The Cass Request doesn't contain a valid Cass Framework class." );
        //		return false;
        //	}
        //	ThisEntity item = Get( request._IdAndVersion );
        //	if (item != null && item.Id > 0)
        //	{
        //		//TODO - do we want to attempt an update - if changed
        //		//		- if we plan to implement a batch refresh of sync'd content, then not necessary
        //		frameworkId = item.Id;
        //		return true;
        //	}
        //	//add the framework...
        //	ThisEntity entity = new ThisEntity();
        //	entity.Name = request.Name;
        //	entity.Description = request.Description;
        //	entity.FrameworkUrl = request.Url;
        //	entity.RepositoryUri = request._IdAndVersion;

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

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


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

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

        //	return isAllValid;
        //}

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

            DBEntity efEntity = new DBEntity();

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

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

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


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

                    context.Reference_Frameworks.Add(efEntity);

                    count = context.SaveChanges();

                    entity.Id = efEntity.Id;
                    //entity.RowId = efEntity.RowId;
                    if (count == 0)
                    {
                        status.AddWarning(string.Format(" Unable to add Profile: {0} <br\\> ", string.IsNullOrWhiteSpace(entity.Name) ? "no description" : entity.Name));
                    }
                }
                else
                {
                    efEntity = context.Reference_Frameworks.SingleOrDefault(s => s.Id == entity.Id);
                    if (efEntity != null && efEntity.Id > 0)
                    {
                        //entity.RowId = efEntity.RowId;
                        //update
                        MapToDB(entity, efEntity);
                        //has changed?
                        if (HasStateChanged(context))
                        {
                            count = context.SaveChanges();
                        }
                    }
                }
            }
            return(isValid);
        }
Beispiel #14
0
        private bool ValidateProfile(PathwaySet profile, ref SaveStatus status, bool validatingUrls = true)
        {
            status.HasSectionErrors = false;

            if (string.IsNullOrWhiteSpace(profile.Name))
            {
                status.AddError("Error: A PathwaySet Name is required.");
            }
            if (!IsGuidValid(profile.OwningAgentUid))
            {
                //first determine if this is populated in edit mode
                status.AddError("An owning organization must be provided.");
            }

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

            else if (validatingUrls && !IsUrlValid(profile.SubjectWebpage, ref commonStatusMessage))
            {
                status.AddError("The PathwaySet Subject Webpage is invalid. " + commonStatusMessage);
            }


            return(status.WasSectionValid);
        }
        }         //

        #endregion
        #endregion

        #region GeoCoordinate  =======================
        #region GeoCoordinate Core  =======================


        public int GeoCoordinates_Add(MC.GeoCoordinates entity, int jpId, ref SaveStatus status)
        {
            if (entity == null || string.IsNullOrWhiteSpace(entity.GeoURI))
            {
                return(0);
            }
            entity.ParentId = jpId;
            EM.GeoCoordinate  efEntity = new EM.GeoCoordinate();
            MC.GeoCoordinates existing = new MC.GeoCoordinates();
            List <String>     messages = new List <string>();

            //extract from "http://geonames.org/6255149/"
            string geoNamesId = UtilityManager.ExtractNameValue(entity.GeoURI, ".org", "/", "/");

            if (IsInteger(geoNamesId))
            {
                entity.GeoNamesId = Int32.Parse(geoNamesId);
            }

            if (GeoCoordinates_Exists(entity.ParentId, entity.GeoNamesId, entity.IsException))
            {
                status.AddWarning("Error this Region has aleady been selected.");
                return(0);
            }

            else
            {
                MapToDB(entity, efEntity);
                //ensure parent jp Id is present
                return(GeoCoordinate_Add(efEntity, ref status));
            }
        }
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                status.AddWarning("An DataSetTimeFrame Description must be entered");
            }


            return(status.WasSectionValid);
        }
Beispiel #17
0
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            if (string.IsNullOrWhiteSpace(profile.FrameworkName))
            {
                status.AddWarning("An educational framework name must be entered");
            }

            //could check for alignment type, but this is typically set by context, and not entered.
            return(!status.HasSectionErrors);
        }
Beispiel #18
0
        public bool ValidateProfile(ThisEntityItem profile, ref bool isEmpty, ref SaveStatus status)
        {
            bool isValid = true;

            isEmpty = false;
            //check if empty
            if (string.IsNullOrWhiteSpace(profile.Name) &&
                string.IsNullOrWhiteSpace(profile.Description) &&
                string.IsNullOrWhiteSpace(profile.TargetName) &&
                string.IsNullOrWhiteSpace(profile.TargetDescription)
                )
            {
                status.AddWarning("Please enter, at minimum, a competency name.");
                //isEmpty = true;
                return(false);
            }

            if (string.IsNullOrWhiteSpace(profile.Name))
            {
                status.AddWarning("A competency name must be entered");
                isValid = false;
            }

            if (!string.IsNullOrWhiteSpace(profile.AlignmentDate) &&
                !IsValidDate(profile.AlignmentDate))
            {
                status.AddWarning("Please enter a valid alignment date");
                isValid = false;
            }

            //if ( string.IsNullOrWhiteSpace( profile.Description ) )
            //{
            //	status.AddWarning( "A competency Description must be entered" );
            //	isValid = false;
            //}

            return(isValid);
        }
Beispiel #19
0
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            if (string.IsNullOrWhiteSpace(profile.Name))
            {
                status.AddWarning("An competency framework name must be entered");
            }

            //if we don't require url, we can't resolve potentially duplicate framework names


            return(status.WasSectionValid);
        }
Beispiel #20
0
        private bool Save(ThisEntity item, Entity parent, DateTime updateDate, ref SaveStatus status)
        {
            bool isValid = true;

            item.EntityId = parent.Id;

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

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

                        if (HasStateChanged(context))
                        {
                            p.LastUpdated = System.DateTime.Now;
                            context.SaveChanges();
                        }
                        //regardless, check parts
                        isValid = UpdateParts(item, updateDate, ref status);
                    }
                    else
                    {
                        //error should have been found
                        isValid = false;
                        status.AddWarning(string.Format("Error: the requested record was not found: recordId: {0}", item.Id));
                    }
                }
                else
                {
                    int newId = Add(item, updateDate, ref status);
                    if (newId == 0 || status.HasErrors)
                    {
                        isValid = false;
                    }
                }
            }
            return(isValid);
        }
        /// <summary>
        /// Retrieve an envelop from the registry and do import
        /// </summary>
        /// <param name="envelopeId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        //public bool ImportByEnvelopeId( string envelopeId, SaveStatus status )
        //{
        //	//this is currently specific, assumes envelop contains a credential
        //	//can use the hack fo GetResourceType to determine the type, and then call the appropriate import method

        //	if ( string.IsNullOrWhiteSpace( envelopeId ) )
        //	{
        //		status.AddError( thisClassName + ".ImportByEnvelope - a valid envelope id must be provided" );
        //		return false;
        //	}

        //	string statusMessage = "";
        //	//EntityServices mgr = new EntityServices();
        //	string ctdlType = "";
        //	try
        //	{
        //		ReadEnvelope envelope = RegistryServices.GetEnvelope( envelopeId, ref statusMessage, ref ctdlType );
        //		if ( envelope != null && !string.IsNullOrWhiteSpace( envelope.EnvelopeIdentifier ) )
        //		{
        //			return CustomProcessEnvelope( envelope, status );
        //		}
        //		else
        //			return false;
        //	}
        //	catch ( Exception ex )
        //	{
        //		LoggingHelper.LogError( ex, thisClassName + ".ImportByEnvelopeId()" );
        //		status.AddError( ex.Message );
        //		if ( ex.Message.IndexOf( "Path '@context', line 1" ) > 0 )
        //		{
        //			status.AddWarning( "The referenced registry document is using an old schema. Please republish it with the latest schema!" );
        //		}
        //		return false;
        //	}
        //}

        public bool ImportByResourceUrl(string resourceUrl, SaveStatus status)
        {
            if (string.IsNullOrWhiteSpace(resourceUrl))
            {
                status.AddError(thisClassName + ".ImportByResourceUrl - a valid resourceUrl must be provided");
                return(false);
            }
            //this is currently specific, assumes envelop contains an organization
            //can use the hack for GetResourceType to determine the type, and then call the appropriate import method
            string statusMessage = "";
            //EntityServices mgr = new EntityServices();
            string ctdlType = "";

            try
            {
                string payload = RegistryServices.GetResourceByUrl(resourceUrl, ref ctdlType, ref statusMessage);

                if (!string.IsNullOrWhiteSpace(payload))
                {
                    if (ImportServiceHelpers.IsAGraphResource(payload))
                    {
                        //if ( payload.IndexOf( "\"en\":" ) > 0 )
                        return(ImportV3(payload, "", status));
                        //else
                        //    return ImportV2( payload, "", status );
                    }
                    else
                    {
                        status.AddError(thisClassName + ".ImportByResourceUrl - 2019-05-01 ONLY GRAPH BASED IMPORTS ARE HANDLED");
                        return(false);
                        //input = JsonConvert.DeserializeObject<InputEntity>( payload.ToString() );
                        //                  return Import( input, "", status );
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".ImportByResourceUrl()");
                status.AddError(ex.Message);
                if (ex.Message.IndexOf("Path '@context', line 1") > 0)
                {
                    status.AddWarning("The referenced registry document is using an old schema. Please republish it with the latest schema!");
                }
                return(false);
            }
        }
Beispiel #22
0
        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;


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


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

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


            return(status.WasSectionValid);
        }
Beispiel #23
0
        /// <summary>
        /// Retrieve an resource from the registry by ctid and do import
        /// </summary>
        /// <param name="ctid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool ImportByCtid(string ctid, SaveStatus status)
        {
            if (string.IsNullOrWhiteSpace(ctid))
            {
                status.AddError(thisClassName + ".ImportByCtid - a valid ctid must be provided");
                return(false);
            }

            //this is currently specific, assumes envelop contains a credential
            //can use the hack for GetResourceType to determine the type, and then call the appropriate import method
            string         statusMessage = "";
            EntityServices mgr           = new EntityServices();
            string         ctdlType      = "";

            try
            {
                //probably always want to get by envelope
                ReadEnvelope envelope = RegistryServices.GetEnvelopeByCtid(ctid, ref statusMessage, ref ctdlType);
                if (envelope != null && !string.IsNullOrWhiteSpace(envelope.EnvelopeIdentifier))
                {
                    return(CustomProcessEnvelope(envelope, status));
                }
                else
                {
                    return(false);
                }
                //string payload = RegistryServices.GetResourceByCtid( ctid, ref ctdlType, ref statusMessage );

                //if ( !string.IsNullOrWhiteSpace( payload ) )
                //{
                //	input = JsonConvert.DeserializeObject<InputEntity>( payload.ToString() );
                //	//ctdlType = RegistryServices.GetResourceType( payload );
                //	return Import( mgr, input, "", status );
                //}
                //else
                //	return false;
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".ImportByCtid(). CTID: {0}", ctid));
                status.AddError(ex.Message);
                if (ex.Message.IndexOf("Path '@context', line 1") > 0)
                {
                    status.AddWarning("The referenced registry document is using an old schema. Please republish it with the latest schema!");
                }
                return(false);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Parts:
        /// - Jurisdiction
        /// - DataSetProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        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);
            }

            //ProcessProfile
            Entity_ProcessProfileManager ppm = new Factories.Entity_ProcessProfileManager();

            ppm.DeleteAll(relatedEntity, ref status);
            try
            {
                ppm.SaveList(entity.AdministrationProcess, Entity_ProcessProfileManager.ADMIN_PROCESS_TYPE, entity.RowId, ref status);
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".AddProfiles() - ProcessProfiles. id: {0}", entity.Id));
                status.AddWarning(thisClassName + ".AddProfiles(). Exceptions encountered handling ProcessProfiles. " + message);
            }
            //
            Entity_ReferenceFrameworkManager erfm = new Entity_ReferenceFrameworkManager();

            erfm.DeleteAll(relatedEntity, ref status);
            if (erfm.SaveList(relatedEntity.Id, CodesManager.PROPERTY_CATEGORY_CIP, entity.InstructionalProgramTypes, ref status) == false)
            {
                isAllValid = false;
            }

            //JurisdictionProfile
            Entity_JurisdictionProfileManager jpm = new Entity_JurisdictionProfileManager();

            //do deletes - NOTE: other jurisdictions are added in: UpdateAssertedIns
            jpm.DeleteAll(relatedEntity, ref status);
            jpm.SaveList(entity.Jurisdiction, entity.RowId, Entity_JurisdictionProfileManager.JURISDICTION_PURPOSE_SCOPE, ref status);
            //datasetProfiles
            new DataSetTimeFrameManager().SaveList(entity.DataSetTimePeriod, entity.Id, ref status);


            return(isAllValid);
        }
        /// <summary>
        /// Probably want to combine with region to have access to keys
        /// </summary>
        /// <param name="efEntity"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public int GeoCoordinate_Add(EM.GeoCoordinate efEntity, ref SaveStatus status)
        {
            using (var context = new EntityContext())
            {
                try
                {
                    if (efEntity.JurisdictionId < 1)
                    {
                        status.AddWarning("Error - missing a parent identifier");
                        return(0);
                    }

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

                    context.GeoCoordinate.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".GeoCoordinate_Add() ", "GeoCoordinate");
                    status.AddError("Error - the save was not successful. " + message);
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".RelatedRegion_Add(), Name: {0}, ParentId: {1)", efEntity.Name, efEntity.JurisdictionId));
                }
            }

            return(0);
        }
Beispiel #26
0
        /// <summary>
        /// Retrieve an envelop from the registry and do import
        /// </summary>
        /// <param name="envelopeId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool ImportByEnvelopeId(string envelopeId, SaveStatus status)
        {
            //this is currently specific, assumes envelop contains a credential
            //can use the hack fo GetResourceType to determine the type, and then call the appropriate import method

            if (string.IsNullOrWhiteSpace(envelopeId))
            {
                status.AddError(thisClassName + ".ImportByEnvelope - a valid envelope id must be provided");
                return(false);
            }

            string statusMessage = "";
            //EntityServices mgr = new EntityServices();
            string ctdlType = "";

            try
            {
                ReadEnvelope envelope = RegistryServices.GetEnvelope(envelopeId, ref statusMessage, ref ctdlType);
                if (envelope != null && !string.IsNullOrWhiteSpace(envelope.EnvelopeIdentifier))
                {
                    return(CustomProcessEnvelope(envelope, status));
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".ImportByEnvelopeId()");
                status.AddError(ex.Message);
                if (ex.Message.IndexOf("Path '@context', line 1") > 0)
                {
                    status.AddWarning("The referenced registry document is using an old schema. Please republish it with the latest schema!");
                }
                return(false);
            }
        }
Beispiel #27
0
        }        //

        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;

            //if ( profile.CostTypeId == 0 && profile.DirectCostType.HasItems() )
            //	profile.CostTypeId = CodesManager.GetEnumerationSelection( profile.DirectCostType );

            profile.CostTypeId = GetCodeItemId(profile.DirectCostType, ref status);

            //&& string.IsNullOrWhiteSpace( profile.CostTypeOther )
            if (profile.CostTypeId == 0)
            {
                status.AddError(thisClassName + ".A cost type must be selected ");
            }
            //

            if (profile.Price < 1)
            {
                status.AddWarning(thisClassName + ". Error - A cost must be entered");
            }


            return(!status.HasSectionErrors);
        }
        } //

        public bool AddTextValue(string textValue,
                                 int entityId,
                                 ref SaveStatus status,
                                 int categoryId)
        {
            if (string.IsNullOrWhiteSpace(textValue))
            {
                return(true);
            }
            using (var context = new EntityContext())
            {
                //add
                DBEntity efEntity = new DBEntity();
                efEntity.CategoryId = categoryId;
                efEntity.EntityId   = entityId;
                efEntity.TextValue  = textValue;
                efEntity.Created    = efEntity.LastUpdated = DateTime.Now;

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

                if (count == 0)
                {
                    status.AddWarning(string.Format(" Unable to add Entity_Reference. EntityId: {0}, categoryId: {1}, textValue: {2}  ", entityId, categoryId, textValue));
                    return(false);
                }
                else
                {
                    if (categoryId == CodesManager.PROPERTY_CATEGORY_SUBJECT)
                    {
                        AddConnections(efEntity.Id);
                    }
                }
            }
            return(true);
        }
        public bool ImportV3(string payload, string envelopeIdentifier, SaveStatus status)
        {
            LoggingHelper.DoTrace(6, "ImportV3 Assessment- entered.");
            List <string> messages = new List <string>();

            bool           importSuccessfull = false;
            EntityServices mgr        = new EntityServices();
            InputEntityV3  input      = new InputEntityV3();
            var            bnodes     = new List <BNode>();
            var            mainEntity = new Dictionary <string, object>();

            //status.AddWarning( "The resource uses @graph and is not handled yet" );

            Dictionary <string, object> dictionary = RegistryServices.JsonToDictionary(payload);
            object graph = dictionary["@graph"];
            //serialize the graph object
            var glist = JsonConvert.SerializeObject(graph);

            //parse graph in to list of objects
            JArray graphList = JArray.Parse(glist);
            int    cntr      = 0;

            foreach (var item in graphList)
            {
                cntr++;
                if (cntr == 1)
                {
                    var main = item.ToString();
                    //may not use this. Could add a trace method
                    mainEntity = RegistryServices.JsonToDictionary(main);
                    input      = JsonConvert.DeserializeObject <InputEntityV3>(main);
                }
                else
                {
                    var bn = item.ToString();
                    bnodes.Add(JsonConvert.DeserializeObject <BNode>(bn));
                }
            }
            ///============= process =============================


            MappingHelperV3 helper = new MappingHelperV3(3);

            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();

            string ctid = input.CTID;

            status.Ctid = ctid;
            string referencedAtId = input.CtdlId;

            LoggingHelper.DoTrace(5, "		name: "+ input.Name.ToString());
            LoggingHelper.DoTrace(6, "		url: "+ input.SubjectWebpage);
            LoggingHelper.DoTrace(5, "		ctid: "+ input.CTID);
            LoggingHelper.DoTrace(5, "		@Id: "+ input.CtdlId);


            if (status.DoingDownloadOnly)
            {
                return(true);
            }

            if (!DoesEntityExist(input.CTID, ref output))
            {
                //set the rowid now, so that can be referenced as needed
                output.RowId = Guid.NewGuid();
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".ImportV3(). Record was NOT found using CTID: '{0}'", input.CTID));
            }
            else
            {
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".ImportV3(). Found record: '{0}' using CTID: '{1}'", input.Name, input.CTID));
            }
            helper.currentBaseObject = output;

            //start with language and may use with language maps
            helper.MapInLanguageToTextValueProfile(input.InLanguage, "Assessment.InLanguage.CTID: " + ctid);
            //foreach ( var l in input.InLanguage )
            //{
            //	if ( !string.IsNullOrWhiteSpace( l ) )
            //	{
            //		var language = CodesManager.GetLanguage( l );
            //		output.InLanguageCodeList.Add( new TextValueProfile()
            //		{
            //			CodeId = language.CodeId,
            //			TextTitle = language.Name,
            //			TextValue = language.Value
            //		} );
            //	}
            //}

            if (input.InLanguage.Count > 0)
            {
                //could use to alter helper.DefaultLanguage
            }
            output.Name        = helper.HandleLanguageMap(input.Name, output, "Name");
            output.Description = helper.HandleLanguageMap(input.Description, output, "Description");
            output.CTID        = input.CTID;
            //TBD handling of referencing third party publisher
            if (!string.IsNullOrWhiteSpace(status.DocumentPublishedBy))
            {
                //output.PublishedByOrganizationCTID = status.DocumentPublishedBy;
                var porg = OrganizationManager.GetSummaryByCtid(status.DocumentPublishedBy);
                if (porg != null && porg.Id > 0)
                {
                    //TODO - store this in a json blob??????????
                    //this will result in being added to Entity.AgentRelationship
                    output.PublishedBy = new List <Guid>()
                    {
                        porg.RowId
                    };
                }
                else
                {
                    //if publisher not imported yet, all publishee stuff will be orphaned
                    var entityUid = Guid.NewGuid();
                    var statusMsg = "";
                    var resPos    = referencedAtId.IndexOf("/resources/");
                    var swp       = referencedAtId.Substring(0, (resPos + "/resources/".Length)) + status.DocumentPublishedBy;
                    int orgId     = new OrganizationManager().AddPendingRecord(entityUid, status.DocumentPublishedBy, swp, ref statusMsg);
                }
            }
            else
            {
                //may need a check for existing published by to ensure not lost
                if (output.Id > 0)
                {
                    if (output.OrganizationRole != null && output.OrganizationRole.Any())
                    {
                        var publishedByList = output.OrganizationRole.Where(s => s.RoleTypeId == 30).ToList();
                        if (publishedByList != null && publishedByList.Any())
                        {
                            var pby = publishedByList[0].ActingAgentUid;
                            output.PublishedBy = new List <Guid>()
                            {
                                publishedByList[0].ActingAgentUid
                            };
                        }
                    }
                }
            }
            output.CredentialRegistryId = envelopeIdentifier;
            output.DateEffective        = input.DateEffective;
            output.ExpirationDate       = input.ExpirationDate;

            output.SubjectWebpage = input.SubjectWebpage;
            //
            //BYs - do owned and offered first

            output.OfferedBy = helper.MapOrganizationReferenceGuids("Assessment.OfferedBy", input.OfferedBy, ref status);
            output.OwnedBy   = helper.MapOrganizationReferenceGuids("Assessment.OwnedBy", input.OwnedBy, ref status);
            if (output.OwnedBy != null && output.OwnedBy.Count > 0)
            {
                output.OwningAgentUid        = output.OwnedBy[0];
                helper.CurrentOwningAgentUid = output.OwnedBy[0];
            }
            else
            {
                //add warning?
                if (output.OfferedBy == null && output.OfferedBy.Count == 0)
                {
                    status.AddWarning("document doesn't have an owning or offering organization.");
                }
            }
            output.AccreditedBy = helper.MapOrganizationReferenceGuids("Assessment.AccreditedBy", input.AccreditedBy, ref status);
            output.ApprovedBy   = helper.MapOrganizationReferenceGuids("Assessment.ApprovedBy", input.ApprovedBy, ref status);
            output.RecognizedBy = helper.MapOrganizationReferenceGuids("Assessment.RecognizedBy", input.RecognizedBy, ref status);
            output.RegulatedBy  = helper.MapOrganizationReferenceGuids("Assessment.RegulatedBy", input.RegulatedBy, ref status);


            //
            output.Subject             = helper.MapCAOListToTextValueProfile(input.Subject, CodesManager.PROPERTY_CATEGORY_SUBJECT);
            output.Keyword             = helper.MapToTextValueProfile(input.Keyword, output, "Keyword");
            output.AvailabilityListing = helper.MapListToString(input.AvailabilityListing);
            output.AvailableOnlineAt   = helper.MapListToString(input.AvailableOnlineAt);
            output.AssessmentExample   = input.AssessmentExample;
            output.ExternalResearch    = helper.MapListToString(input.ExternalResearch);

            output.AssessmentExampleDescription = helper.HandleLanguageMap(input.AssessmentExampleDescription, output, "AssessmentExampleDescription");
            output.AssessmentMethodType         = helper.MapCAOListToEnumermation(input.AssessmentMethodType);
            output.AssessmentMethodDescription  = helper.HandleLanguageMap(input.AssessmentMethodDescription, output, "AssessmentMethodDescription");
            //
            output.LearningMethodDescription = helper.HandleLanguageMap(input.LearningMethodDescription, output, "LearningMethodDescription");


            output.AudienceType = helper.MapCAOListToEnumermation(input.AudienceType);
            //CAO
            output.AudienceLevelType = helper.MapCAOListToEnumermation(input.AudienceLevelType);

            output.VersionIdentifier     = helper.MapIdentifierValueListToString(input.VersionIdentifier);
            output.VersionIdentifierList = helper.MapIdentifierValueList(input.VersionIdentifier);

            //To be looked
            output.CodedNotation = input.CodedNotation;
            output.Identifier    = helper.MapIdentifierValueList(input.Identifier);
            if (output.Identifier != null && output.Identifier.Count() > 0)
            {
                output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
            }

            output.AssessmentOutput        = helper.HandleLanguageMap(input.AssessmentOutput, output, "AssessmentOutput");
            output.AssessmentUseType       = helper.MapCAOListToEnumermation(input.AssessmentUseType);
            output.DeliveryType            = helper.MapCAOListToEnumermation(input.DeliveryType);
            output.DeliveryTypeDescription = helper.HandleLanguageMap(input.DeliveryTypeDescription, output, "DeliveryTypeDescription");

            output.IsProctored           = input.IsProctored;
            output.HasGroupEvaluation    = input.HasGroupEvaluation;
            output.HasGroupParticipation = input.HasGroupParticipation;

            output.ProcessStandards            = input.ProcessStandards;
            output.ProcessStandardsDescription = helper.HandleLanguageMap(input.ProcessStandardsDescription, output, "ProcessStandardsDescription");
            output.ScoringMethodDescription    = helper.HandleLanguageMap(input.ScoringMethodDescription, output, "ScoringMethodDescription");

            output.ScoringMethodExample            = input.ScoringMethodExample;
            output.ScoringMethodExampleDescription = helper.HandleLanguageMap(input.ScoringMethodExampleDescription, output, "ScoringMethodExampleDescription");
            output.ScoringMethodType = helper.MapCAOListToEnumermation(input.ScoringMethodType);

            //TBD - a custom version
            //output.InstructionalProgramType = helper.MapCAOListToEnumermation( input.InstructionalProgramType );
            //occupations
            output.Occupations = helper.MapCAOListToCAOProfileList(input.OccupationType);
            //just append alternative items. Ensure empty lists are ignored
            //output.Occupations.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeOccupationType ) );

            //skip if no occupations
            if (output.Occupations.Count() == 0 &&
                UtilityManager.GetAppKeyValue("skipCredImportIfNoOccupations", false))
            {
                //LoggingHelper.DoTrace( 2, string.Format( "		***Skipping Credential# {0}, {1} as it has no occupations and this is a special run.", output.Id, output.Name ) );
                //return true;
            }
            //Industries
            output.Industries = helper.MapCAOListToCAOProfileList(input.IndustryType);
            //output.Industries.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeIndustryType ) );
            //naics
            //output.Naics = input.Naics;

            output.InstructionalProgramTypes = helper.MapCAOListToCAOProfileList(input.InstructionalProgramType);
            //output.InstructionalProgramTypes.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeInstructionalProgramType ) );
            if (output.InstructionalProgramTypes.Count() == 0 && UtilityManager.GetAppKeyValue("skipAsmtImportIfNoCIP", false))
            {
                //skip
                LoggingHelper.DoTrace(2, string.Format("		***Skipping asmt# {0}, {1} as it has no InstructionalProgramTypes and this is a special run.", output.Id, output.Name));
                return(true);
            }
            //============================================================
            //handle QuantitativeValue
            //21-03-23 making the move to ValueProfile
            //output.CreditValue = helper.HandleQuantitiveValue( input.CreditValue, "Assessment.CreditValue" );
            //output.QVCreditValueList = helper.HandleValueProfileListToQVList( input.CreditValue, "Assessment.CreditValue" );
            //don't initially need CreditValueList if using CreditValueJson here
            output.CreditValue = helper.HandleValueProfileList(input.CreditValue, "Assessment.CreditValue");
            //however, CreditValueJson must include resolved concepts
            //TODO - take the opportunity to move away from Enumerations
            output.CreditValueJson = JsonConvert.SerializeObject(output.CreditValue, MappingHelperV3.GetJsonSettings());
            //note can still have CreditUnitTypeDescription by itself. What to do if both?
            output.CreditUnitTypeDescription = helper.HandleLanguageMap(input.CreditUnitTypeDescription, output, "Assessment.CreditUnitTypeDescription");
            //if ( output.CreditValueList != null && output.CreditValueList.Any() )
            //	output.CreditValue = output.CreditValueList[ 0 ];
            //


            output.Jurisdiction = helper.MapToJurisdiction(input.Jurisdiction, ref status);

            //EstimatedCost
            //will need to format, all populate Entity.RelatedCosts (for bubble up) - actually this would be for asmts, and lopps
            output.EstimatedCost = helper.FormatCosts(input.EstimatedCost, ref status);

            //assesses compentencies
            output.AssessesCompetencies = helper.MapCAOListToCAOProfileList(input.Assesses);
            if (output.AssessesCompetencies.Count() == 0 && UtilityManager.GetAppKeyValue("skipAsmtImportIfNoCompetencies", false))
            {
                //skip
                LoggingHelper.DoTrace(2, string.Format("		***Skipping asmt# {0}, {1} as it has no competencies and this is a special run.", output.Id, output.Name));
                return(true);
            }

            //common conditions
            output.ConditionManifestIds = helper.MapEntityReferences(input.CommonConditions, CodesManager.ENTITY_TYPE_CONDITION_MANIFEST, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);
            //common costs
            output.CostManifestIds = helper.MapEntityReferences(input.CommonCosts, CodesManager.ENTITY_TYPE_COST_MANIFEST, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);

            //connections
            output.AdvancedStandingFrom  = helper.FormatConditionProfile(input.AdvancedStandingFrom, ref status);
            output.IsAdvancedStandingFor = helper.FormatConditionProfile(input.IsAdvancedStandingFor, ref status);

            output.PreparationFrom  = helper.FormatConditionProfile(input.PreparationFrom, ref status);
            output.IsPreparationFor = helper.FormatConditionProfile(input.IsPreparationFor, ref status);

            output.IsRequiredFor    = helper.FormatConditionProfile(input.IsRequiredFor, ref status);
            output.IsRecommendedFor = helper.FormatConditionProfile(input.IsRecommendedFor, ref status);

            //EstimatedDuration ==============================
            output.EstimatedDuration = helper.FormatDuration(input.EstimatedDuration, ref status);

            //conditions ======================================
            output.Requires       = helper.FormatConditionProfile(input.Requires, ref status);
            output.Recommends     = helper.FormatConditionProfile(input.Recommends, ref status);
            output.EntryCondition = helper.FormatConditionProfile(input.EntryCondition, ref status);
            output.Corequisite    = helper.FormatConditionProfile(input.Corequisite, ref status);

            //Process profiles ==============================
            output.AdministrationProcess = helper.FormatProcessProfile(input.AdministrationProcess, ref status);
            output.DevelopmentProcess    = helper.FormatProcessProfile(input.DevelopmentProcess, ref status);
            output.MaintenanceProcess    = helper.FormatProcessProfile(input.MaintenanceProcess, ref status);

            //

            output.Addresses = helper.FormatAvailableAtAddresses(input.AvailableAt, ref status);
            //targets
            if (input.TargetAssessment != null && input.TargetAssessment.Count > 0)
            {
                output.TargetAssessmentIds = helper.MapEntityReferences("Assessment.TargetAssessment", input.TargetAssessment, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);
            }
            //21-04-13 mp - TargetLearningResource will be URLs not registry resources
            if (input.TargetLearningResource != null && input.TargetLearningResource.Count > 0)
            {
                output.TargetLearningResource = input.TargetLearningResource;
                //output.TargetLearningOpportunityIds = helper.MapEntityReferences( "Assessment.TargetLearningOpportunity", input.TargetLearningResource, CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE, ref status );
            }
            //
            if (input.TargetPathway != null && input.TargetPathway.Count > 0)
            {
                output.TargetPathwayIds = helper.MapEntityReferences("Assessment.TargetPathway", input.TargetPathway, CodesManager.ENTITY_TYPE_PATHWAY, ref status);
            }

            //INs
            output.AccreditedIn = helper.MapToJurisdiction(input.AccreditedIn, ref status);
            output.ApprovedIn   = helper.MapToJurisdiction(input.ApprovedIn, ref status);
            output.OfferedIn    = helper.MapToJurisdiction(input.OfferedIn, ref status);
            output.RecognizedIn = helper.MapToJurisdiction(input.RecognizedIn, ref status);
            output.RegulatedIn  = helper.MapToJurisdiction(input.RegulatedIn, ref status);

            //SameAs URI
            output.SameAs = helper.MapToTextValueProfile(input.SameAs);
            //FinancialAssistance ============================
            //output.FinancialAssistanceOLD = helper.FormatFinancialAssistance( input.FinancialAssistance, ref status );
            output.FinancialAssistance = helper.FormatFinancialAssistance(input.FinancialAssistance, ref status);
            if (output.FinancialAssistance != null && output.FinancialAssistance.Any())
            {
                output.FinancialAssistanceJson = JsonConvert.SerializeObject(output.FinancialAssistance, MappingHelperV3.GetJsonSettings());
            }

            //=== if any messages were encountered treat as warnings for now
            if (messages.Count > 0)
            {
                status.SetMessages(messages, true);
            }
            //just in case check if entity added since start
            if (output.Id == 0)
            {
                ThisEntity entity = EntityServices.GetByCtid(ctid);
                if (entity != null && entity.Id > 0)
                {
                    output.Id    = entity.Id;
                    output.RowId = entity.RowId;
                }
            }
            importSuccessfull = mgr.Import(output, ref status);

            status.DocumentId    = output.Id;
            status.DetailPageUrl = string.Format("~/assessment/{0}", output.Id);
            status.DocumentRowId = output.RowId;

            //just in case
            if (status.HasErrors)
            {
                importSuccessfull = false;
            }

            //if record was added to db, add to/or set EntityResolution as resolved
            int ierId = new ImportManager().Import_EntityResolutionAdd(referencedAtId,
                                                                       ctid,
                                                                       CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE,
                                                                       output.RowId,
                                                                       output.Id,
                                                                       (output.Id > 0),
                                                                       ref messages,
                                                                       output.Id > 0);

            return(importSuccessfull);
        }
Beispiel #30
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);
        }