/// <summary>
        /// Executes the specified workflow action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            Guid? personAliasGuid = GetAttributeValue( action, "Person" ).AsGuidOrNull();
            if ( personAliasGuid.HasValue )
            {
                var personAlias = new PersonAliasService( rockContext ).Queryable( "Person" )
                    .Where( a => a.Guid.Equals( personAliasGuid.Value ) )
                    .FirstOrDefault();

                if (personAlias != null)
                {
                    action.Activity.AssignedPersonAlias = personAlias;
                    action.Activity.AssignedPersonAliasId = personAlias.Id;
                    action.Activity.AssignedGroup = null;
                    action.Activity.AssignedGroupId = null;
                    action.AddLogEntry( string.Format( "Assigned activity to '{0}' ({1})",  personAlias.Person.FullName, personAlias.Person.Id ) );
                    return true;
                }

            }

            return false;
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            if (HttpContext.Current != null)
            {
                var referrer = HttpContext.Current.Request.UrlReferrer.ToString();
                if (! String.IsNullOrEmpty(referrer))
                {
                    var urlAttrGuid = GetAttributeValue( action,"URLField" ).AsGuid();
                    var attribute = AttributeCache.Read( urlAttrGuid, rockContext );
                    if (attribute != null)
                    {
                        if (attribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                        {
                            action.Activity.Workflow.SetAttributeValue( attribute.Key, referrer );
                        }
                        else
                        {
                            action.Activity.SetAttributeValue( attribute.Key, referrer );
                        }
                    }
                }
                else
                {
                    action.AddLogEntry( "No HTTP Referrer detected" );
                }
            }
            else
            {
                action.AddLogEntry( "SetAttributeFromHTTPReferrer triggered outside an http context");
            }
            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            Guid guid = GetAttributeValue( action, "Activity" ).AsGuid();
            if ( guid.IsEmpty() )
            {
                action.AddLogEntry( "Invalid Activity Property", true );
                return false;
            }

            var workflow = action.Activity.Workflow;

            var activityType = new WorkflowActivityTypeService( rockContext ).Queryable()
                .Where( a => a.Guid.Equals( guid ) ).FirstOrDefault();

            if ( activityType == null )
            {
                action.AddLogEntry( "Invalid Activity Property", true );
                return false;
            }

            WorkflowActivity.Activate( activityType, workflow );
            action.AddLogEntry( string.Format( "Activated new '{0}' activity", activityType.ToString() ) );

            return true;
        }
Beispiel #4
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string activityTypeId = GetAttributeValue( action, "ActivityType" );
            if ( String.IsNullOrWhiteSpace( activityTypeId ) )
            {
                action.AddLogEntry( "Invalid Activity Type Property" );
                return false;
            }

            var workflow = action.Activity.Workflow;

            var activityType = workflow.WorkflowType.ActivityTypes
                .Where( a => a.Id.ToString() == activityTypeId).FirstOrDefault();

            if (activityType != null)
            {
                WorkflowActivity.Activate( activityType, workflow );
                action.AddLogEntry( string.Format( "Activated new '{0}' activity", activityType.ToString() ) );
                return true;
            }

            action.AddLogEntry( string.Format( "Could Not activate new '{0}' activity!", activityType.ToString() ) );
            return false;
        }
Beispiel #5
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            Guid guid = GetAttributeValue( action, "Attribute" ).AsGuid();
            if ( !guid.IsEmpty() )
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string value = GetAttributeValue( action, "Value" );

                    value = value.ResolveMergeFields( GetMergeFields( action ) );

                    if ( attribute.EntityTypeId == new Rock.Model.Workflow().TypeId )
                    {
                        action.Activity.Workflow.SetAttributeValue( attribute.Key, value );
                        action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, value ) );
                    }
                    else if ( attribute.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId )
                    {
                        action.Activity.SetAttributeValue( attribute.Key, value );
                        action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, value ) );
                    }
                }
            }

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            var guid = GetAttributeValue( action, "Workflow" ).AsGuid();
            if (guid.IsEmpty())
            {
                action.AddLogEntry( "Invalid Workflow Property", true );
                return false;
            }

            var currentActivity = action.Activity;
            var newWorkflowType = new WorkflowTypeService( rockContext ).Get( guid );
            var newWorkflowName = GetAttributeValue(action, "WorkflowName" );

            if (newWorkflowType == null)
            {
                action.AddLogEntry( "Invalid Workflow Property", true );
                return false;
            }
            
            var newWorkflow = Rock.Model.Workflow.Activate( newWorkflowType, newWorkflowName );
            if (newWorkflow == null)
            {
                action.AddLogEntry( "The Workflow could not be activated", true );
                return false;
            }

            CopyAttributes( newWorkflow, currentActivity, rockContext );

            SaveForProcessingLater( newWorkflow, rockContext );

            return true;
            // Kick off processing of new Workflow
            /*if(newWorkflow.Process( rockContext, entity, out errorMessages )) 
            {
                if (newWorkflow.IsPersisted || newWorkflowType.IsPersisted)
                {
                    var workflowService = new Rock.Model.WorkflowService( rockContext );
                    workflowService.Add( newWorkflow );

                    rockContext.WrapTransaction( () =>
                    {
                        rockContext.SaveChanges();
                        newWorkflow.SaveAttributeValues( rockContext );
                        foreach (var activity in newWorkflow.Activities)
                        {
                            activity.SaveAttributeValues( rockContext );
                        }
                    } );
                }

                return true;
            }
            else
            {
                return false;
            }*/
        }
Beispiel #7
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var query = GetAttributeValue( action, "SQLQuery" );

            var mergeFields = GetMergeFields( action );
            query = query.ResolveMergeFields( mergeFields );

            try
            {
                object sqlResult = DbService.ExecuteScaler( query );
                action.AddLogEntry( "SQL query has been run" );

                if ( sqlResult != null )
                {
                    Guid? attributeGuid = GetAttributeValue( action, "ResultAttribute" ).AsGuidOrNull();
                    if ( attributeGuid.HasValue )
                    {
                        var attribute = AttributeCache.Read( attributeGuid.Value, rockContext );
                        if ( attribute != null )
                        {
                            string resultValue = sqlResult.ToString();

                            if ( attribute.EntityTypeId == new Rock.Model.Workflow().TypeId )
                            {
                                action.Activity.Workflow.SetAttributeValue( attribute.Key, resultValue );
                                action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, resultValue ) );
                            }
                            else if ( attribute.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId )
                            {
                                action.Activity.SetAttributeValue( attribute.Key, resultValue );
                                action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, resultValue ) );
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                action.AddLogEntry( ex.Message, true );

                if ( !GetAttributeValue( action, "ContinueOnError" ).AsBoolean() )
                {
                    errorMessages.Add( ex.Message );
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            Guid guid = GetAttributeValue( action, "Attribute" ).AsGuid();
            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string existingValue = action.GetWorklowAttributeValue( guid );
                    string value = GetAttributeValue( action, "Value" );
                    string separator;

                    if (String.IsNullOrEmpty( existingValue ))
                    {
                        separator = "";
                    }
                    else
                    {
                        separator = GetAttributeValue( action, "Separator" );
                    }

                    var mergeFields = GetMergeFields( action );
                    
                    value = value.ResolveMergeFields( mergeFields );
                    
                    string valueAction;
                    string newValue;

                    if (GetAttributeValue(action,"Prepend").AsBoolean()) 
                    {
                        valueAction = "Prepended";
                        newValue = string.Format("{1}{2}{0}", existingValue, value, separator);
                    } else {
                        valueAction = "Appended";
                        newValue = string.Format("{0}{2}{1}", existingValue, value, separator);
                    }

                    if ( attribute.EntityTypeId == new Rock.Model.Workflow().TypeId )
                    {
                        action.Activity.Workflow.SetAttributeValue( attribute.Key, newValue );
                        action.AddLogEntry( string.Format( "{2} '{0}' attribute to '{1}'.", attribute.Name, newValue, valueAction ) );
                    }
                    else if ( attribute.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId )
                    {
                        action.Activity.SetAttributeValue( attribute.Key, newValue );
                        action.AddLogEntry( string.Format( "{2} '{0}' attribute to '{1}'.", attribute.Name, newValue, valueAction ) );
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var workflowActivityGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "Activity" ).AsGuid() ).AsGuid();
            if ( workflowActivityGuid.IsEmpty() )
            {
                action.AddLogEntry( "Invalid Activity Property", true );
                return false;
            }

            var attributeKey = GetAttributeValue( action, "WorkflowAttributeKey", true );
            var attributeValue = GetAttributeValue( action, "WorkflowAttributeValue", true );
            if ( string.IsNullOrWhiteSpace( attributeKey) || string.IsNullOrWhiteSpace(attributeValue) )
            {
                action.AddLogEntry( "Invalid Workflow Property", true );
                return false;
            }

            var activityType = new WorkflowActivityTypeService( rockContext ).Queryable()
                .Where( a => a.Guid.Equals( workflowActivityGuid ) ).FirstOrDefault();

            if ( activityType == null )
            {
                action.AddLogEntry( "Invalid Activity Property", true );
                return false;
            }

            var entityType = EntityTypeCache.Read( typeof( Rock.Model.Workflow ) );

            var workflowIds = new AttributeValueService( rockContext )
                .Queryable()
                .AsNoTracking()
                .Where( a => a.Attribute.Key == attributeKey && a.Value == attributeValue && a.Attribute.EntityTypeId == entityType.Id )
                .Select(a => a.EntityId);

            var workflows = new WorkflowService( rockContext )
                .Queryable()
                //.AsNoTracking()
                .Where( w => w.WorkflowType.ActivityTypes.Any( a => a.Guid == activityType.Guid ) && workflowIds.Contains(w.Id) )
                .ToList();

            foreach (var workflow in workflows )
            {
                WorkflowActivity.Activate( activityType, workflow );
                action.AddLogEntry( string.Format( "Activated new '{0}' activity in {1} {2}", activityType.ToString(), workflow.TypeName, workflow.WorkflowId ) );
            }

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            var groupAttribute =  GetAttributeValue( action, "GroupAttribute" );
            Guid groupAttrGuid = groupAttribute.AsGuid();

            if (!groupAttrGuid.IsEmpty())
            {
                
                string attributeGroupValue = action.GetWorklowAttributeValue( groupAttrGuid );
                Guid groupGuid = attributeGroupValue.AsGuid();

                var groupRoleAttr = GetAttributeValue( action, "Group Role" );
                Guid groupRoleGuid = groupRoleAttr.AsGuid();

                if (!groupRoleGuid.IsEmpty())
                {  
                    var groupM = (new GroupService( rockContext )).Get( groupGuid );
                    if (groupM != null)
                    {
                        var groupRole = (new GroupTypeRoleService( rockContext )).Get( groupRoleGuid );
                        var person = (from m in groupM.Members 
                                        where m.GroupRoleId == groupRole.Id 
                                        select m.Person).FirstOrDefault();

                        if (person != null)
                        {
                            action.Activity.AssignedPersonAlias = person.PrimaryAlias;
                            action.Activity.AssignedPersonAliasId = person.PrimaryAliasId;
                            action.Activity.AssignedGroup = null;
                            action.Activity.AssignedGroupId = null;

                            action.AddLogEntry( string.Format( "Assigned activity to '{0}' ({1})", person.FullName, person.Id ) );
                            return true;
                        }
                        else
                        {
                            action.AddLogEntry( string.Format( "Nobody assigned to Role ({0}) for Group ({1})", groupRole.Name, groupM.Name ) );
                        }

                    }
                   
                }
            }

            errorMessages.Add( "An assignment to person could not be completed." );
            return false;
        
        }
Beispiel #11
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string attributeValue = GetAttributeValue( action, "Attribute" );
            Guid guid = attributeValue.AsGuid();
            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string value = GetAttributeValue( action, "Person" );
                    guid = value.AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        var personAlias = new PersonAliasService( rockContext ).Get( guid );
                        if ( personAlias != null && personAlias.Person != null )
                        {
                            action.Activity.Workflow.SetAttributeValue( attribute.Key, value );
                            action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, personAlias.Person.FullName ) );
                            return true;
                        }
                        else
                        {
                            errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guid.ToString() ) );
                        }
                    }
                    else
                    {
                        action.Activity.Workflow.SetAttributeValue( attribute.Key, string.Empty );
                        action.AddLogEntry( string.Format( "Set '{0}' attribute to nobody.", attribute.Name ) );
                        return true;
                    }
                }
                else
                {
                    errorMessages.Add( string.Format( "Attribute could not be found for selected attribute value ('{0}')!", guid.ToString() ) );
                }
            }
            else
            {
                errorMessages.Add( string.Format( "Selected attribute value ('{0}') was not a valid Guid!", attributeValue ) );
            }

            errorMessages.ForEach( m => action.AddLogEntry( m, true ) );

            return true;
        }
Beispiel #12
0
        /// <summary>
        /// Executes the specified workflow action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var parts = ( GetAttributeValue( action, "Group" ) ?? string.Empty ).Split( '|' );
            Guid? groupTypeGuid = null;
            Guid? groupGuid = null;
            if ( parts.Length >= 1 )
            {
                groupTypeGuid = parts[0].AsGuidOrNull();
                if ( parts.Length >= 2 )
                {
                    groupGuid = parts[1].AsGuidOrNull();
                }
            }

            if ( groupGuid.HasValue )
            {
                var group = new GroupService( rockContext ).Get( groupGuid.Value );
                if ( group != null )
                {
                    action.Activity.AssignedPersonAlias = null;
                    action.Activity.AssignedPersonAliasId = null;
                    action.Activity.AssignedGroup = group;
                    action.Activity.AssignedGroupId = group.Id;
                    action.AddLogEntry( string.Format( "Assigned activity to '{0}' group ({1})", group.Name, group.Id ) );
                    return true;
                }
            }

            return false;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string nameValue = GetAttributeValue( action, "NameValue" );
            Guid guid = nameValue.AsGuid();
            if (guid.IsEmpty())
            {
                nameValue = nameValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            else
            {
                nameValue = action.GetWorklowAttributeValue( guid, true, true );

                // HtmlDecode the name since we are storing it in the database and it might be formatted to be shown in HTML
                nameValue = System.Web.HttpUtility.HtmlDecode( nameValue );
            }

            if ( !string.IsNullOrWhiteSpace( nameValue ) )
            {
                action.Activity.Workflow.Name = nameValue;
                action.AddLogEntry( string.Format( "Set Workflow Name to '{0}'", nameValue ) );
            }

            return true;
        }
        /// <summary>
        /// Executes the specified workflow action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // Get the attribute's guid
            Guid guid = GetAttributeValue( action, "PersonAttribute" ).AsGuid();
            if ( !guid.IsEmpty() )
            {
                // Get the attribute
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    if ( attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id )
                    {
                        // If attribute type is a person, value should be person alias id
                        Guid? personAliasGuid = action.GetWorklowAttributeValue( guid ).AsGuidOrNull();
                        if ( personAliasGuid.HasValue )
                        {
                            var personAlias = new PersonAliasService( rockContext ).Queryable( "Person" )
                                .Where( a => a.Guid.Equals( personAliasGuid.Value ) )
                                .FirstOrDefault();
                            if ( personAlias != null )
                            {
                                action.Activity.Workflow.InitiatorPersonAlias = personAlias;
                                action.Activity.Workflow.InitiatorPersonAliasId = personAlias.Id;
                                action.AddLogEntry( string.Format( "Assigned initiator to '{0}' ({1})", personAlias.Person.FullName, personAlias.Person.Id ) );
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            if ( entity is Model.BinaryFile )
            {
               var binaryFile = (Model.BinaryFile) entity;
                if ( binaryFile.BinaryFileType.Guid != new Guid( SystemGuid.BinaryFiletype.CHECKIN_LABEL ) )
                {
                    errorMessages.Add( "Binary file is not a check-in label" );
                    action.AddLogEntry( "Binary file is not a check-in label", true );
                    return false;
                }

                StringBuilder sb = new StringBuilder();

                var contentString = binaryFile.ContentsToString();
                foreach ( Match match in Regex.Matches(
                    contentString,
                    @"(?<=\^FD)[^\^FS]*(?=\^FS)" ) )
                {
                    sb.AppendFormat( "{0}^|", match.Value );
                }

                binaryFile.LoadAttributes();

                var attributeValue = new AttributeValue();
                attributeValue.Value = sb.ToString();

                binaryFile.AttributeValues["MergeCodes"] = attributeValue;
                binaryFile.SaveAttributeValues( rockContext );
            }

            return true;
        }
Beispiel #16
0
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var JobGuid = GetAttributeValue( action, "Job" ).AsGuid();

            if ( !JobGuid.IsEmpty() )
            {
                ServiceJob Job = new ServiceJobService( rockContext ).Get( JobGuid );
                if ( Job != null )
                {
                    var transaction = new Rock.Transactions.RunJobNowTransaction( Job.Id );

                    // Process the transaction on another thread
                    System.Threading.Tasks.Task.Run( () => transaction.Execute() );

                    action.AddLogEntry( string.Format( "The '{0}' job has been started.", Job.Name ) );

                    return true;
                }

            }

            errorMessages.Add("The specified Job could not be found");

            return false;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var workflow = action.Activity.Workflow;
            workflow.IsPersisted = true;

            if ( GetAttributeValue( action, "PersistImmediately" ).AsBoolean( false ) )
            {
                var service = new WorkflowService( rockContext );
                if ( workflow.Id == 0 )
                {
                    service.Add( workflow );
                }

                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();
                    workflow.SaveAttributeValues( rockContext );
                    foreach ( var activity in workflow.Activities )
                    {
                        activity.SaveAttributeValues( rockContext );
                    }
                } );
            }

            action.AddLogEntry( "Updated workflow to be persisted!" );

            return true;
        }
Beispiel #18
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="dto">The dto.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( WorkflowAction action, IDto dto, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            action.Activity.Workflow.MarkComplete();
            action.AddLogEntry( "Marked workflow complete" );

            return true;
        }
Beispiel #19
0
        /// <summary>
        /// Executes the specified workflow action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            action.Activity.MarkComplete();
            action.AddLogEntry( "Marked activity complete" );

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            Guid? workflowGuid = GetAttributeValue( action, "Workflow", true ).AsGuidOrNull();
            if ( workflowGuid.HasValue )
            {
                using ( var newRockContext = new RockContext() )
                {
                    var workflowService = new WorkflowService( newRockContext );
                    var workflow = workflowService.Get( workflowGuid.Value );
                    if ( workflow != null )
                    {
                        string status = GetAttributeValue( action, "Status" ).ResolveMergeFields( GetMergeFields( action ) );
                        workflow.Status = status;
                        workflow.AddLogEntry( string.Format( "Status set to '{0}' by another workflow: {1}", status, action.Activity.Workflow ) );
                        newRockContext.SaveChanges();

                        action.AddLogEntry( string.Format( "Set Status to '{0}' on another workflow: {1}", status, workflow ) );

                        bool processNow = GetAttributeValue( action, "ProcessNow" ).AsBoolean();
                        if ( processNow )
                        {
                            var processErrors = new List<string>();
                            if ( !workflowService.Process( workflow, out processErrors ) )
                            {
                                action.AddLogEntry( "Error(s) occurred processing target workflow: " + processErrors.AsDelimited( ", " ) );
                            }
                        }

                        return true;
                    }
                }

                action.AddLogEntry( "Could not find selected workflow." );
            }
            else
            {
                action.AddLogEntry( "Workflow attribute was not set." );
                return true;    // Continue processing in this case
            }

            return false;
        }
Beispiel #21
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string status = GetAttributeValue( action, "Status" );
            action.Activity.Workflow.Status = status;
            action.AddLogEntry( string.Format( "Set Status to '{0}'", status ) );
            
            return true;
        }
Beispiel #22
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var workflow = action.Activity.Workflow;
            workflow.IsPersisted = true;

            action.AddLogEntry( "Updated workflow to be persisted!" );

            return true;
        }
Beispiel #23
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var query = GetAttributeValue( action, "SQLQuery" );
            int rows = new Service().ExecuteCommand( query, new object[] { } );

            action.AddLogEntry( "SQL query has been run" );

            return true;
        }
Beispiel #24
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string status = GetAttributeValue( action, "Status", true ).ResolveMergeFields( GetMergeFields( action ) );
            action.Activity.Workflow.MarkComplete( status );

            action.AddLogEntry( "Marked workflow complete" );

            return true;
        }
Beispiel #25
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            foreach ( var a in action.Activity.Actions )
            {
                a.CompletedDateTime = null;
            }

            action.AddLogEntry( string.Format( "Activated all actions for '{0}' activity.", action.ActionType.Name ) );

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var mergeFields = GetMergeFields( action );

            var benevolenceRequest = new BenevolenceRequestService( rockContext ).Get( GetAttributeValue( action, "BenevolenceRequest", true ).AsGuid() );

            if ( benevolenceRequest == null )
            {
                var errorMessage = "Benevolence request could not be found.";
                errorMessages.Add( errorMessage );
                action.AddLogEntry( errorMessage, true );
                return false;
            }

            var attribute = AttributeCache.Read( GetAttributeValue( action, "BenevolenceRequestAttribute" ).AsGuid() );

            if ( attribute == null )
            {
                var errorMessage = "Could not find a benevolence attribute matching the one provided.";
                errorMessages.Add( errorMessage );
                action.AddLogEntry( errorMessage, true );
                return false;
            }

            var attributeValue = GetAttributeValue( action, "Value", true ).ResolveMergeFields( mergeFields );
            bool useBlankValues = GetActionAttributeValue( action, "UseBlankValue" ).AsBoolean();

            if ( !string.IsNullOrWhiteSpace( attributeValue ) ||  useBlankValues)
            {
                benevolenceRequest.LoadAttributes();

                Rock.Attribute.Helper.SaveAttributeValue( benevolenceRequest, attribute, attributeValue, rockContext );
                action.AddLogEntry( $"Updated benevolence attribute '{attribute.Name}' to '{attributeValue}'." );
            }

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var adultRoleGuid = SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();

            var person = GetPersonAliasFromActionAttribute( "Person", rockContext, action, errorMessages );
            if ( person != null )
            {
                string HeadOfHouseholdAttributeValue = GetAttributeValue( action, "HeadOfHouseholdAttribute" );
                Guid? headOfHouseholdGuid = HeadOfHouseholdAttributeValue.AsGuidOrNull();
                if ( headOfHouseholdGuid.HasValue )
                {
                    var headofHouseholdAttribute = AttributeCache.Read( headOfHouseholdGuid.Value, rockContext );
                    if ( headofHouseholdAttribute != null )
                    {
                        var headOfHousehold = person.GetHeadOfHousehold( rockContext );
                        if ( headOfHousehold != null )
                        {
                            action.Activity.Workflow.SetAttributeValue( headofHouseholdAttribute.Key, headOfHousehold.PrimaryAlias.Guid.ToString() );
                            action.AddLogEntry( string.Format( "Set Head Of Household attribute '{0}' attribute to '{1}'.", headofHouseholdAttribute.Name, headOfHousehold.FullName ) );
                            return true;
                        }
                        else
                        {
                            action.AddLogEntry( string.Format( "No head of Household found for {0}.", person.FullName ) );
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add( "No person was provided." );
                return false;
            }
            errorMessages.ForEach( m => action.AddLogEntry( m, true ) );

            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var mergeFields = GetMergeFields( action );

            BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService( rockContext );

            var benevolenceRequest = benevolenceRequestService.Get( GetAttributeValue( action, "BenevolenceRequest", true ).AsGuid() );

            if (benevolenceRequest == null )
            {
                var errorMessage = "Benevolence request could not be found.";
                errorMessages.Add( errorMessage );
                action.AddLogEntry( errorMessage, true );
                return false;
            }

            var binaryFile = new BinaryFileService(rockContext).Get(GetAttributeValue( action, "Document", true ).AsGuid());

            if ( binaryFile == null )
            {
                action.AddLogEntry( "The document to add to the benevolence request was not be found.", true );
                return true; // returning true here to allow the action to run 'successfully' without a document. This allows the action to be easily used when the document is optional without a bunch of action filter tests.
            }

            BenevolenceRequestDocument requestDocument = new BenevolenceRequestDocument();
            benevolenceRequest.Documents.Add( requestDocument );

            requestDocument.BinaryFileId = binaryFile.Id;

            rockContext.SaveChanges();

            action.AddLogEntry( "Added document to the benevolence request." );
            return true;
        }
Beispiel #29
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            var adultRoleGuid = SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();

            var maritalStatusMarried = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid() );
            var familyGroupType = GroupTypeCache.Read( SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() );
            var adultRole = familyGroupType.Roles.Where( r => r.Guid == adultRoleGuid ).FirstOrDefault();

            var person = GetPersonAliasFromActionAttribute("Person", rockContext, action, errorMessages);
            if (person != null)
            {
                string spouseAttributeValue = GetAttributeValue( action, "SpouseAttribute" );
                Guid? spouseGuid = spouseAttributeValue.AsGuidOrNull();
                if ( spouseGuid.HasValue )
                {
                    var spouseAttribute = AttributeCache.Read( spouseGuid.Value, rockContext );
                    if ( spouseAttribute != null )
                    {

                        var spouse = person.GetSpouse( rockContext );

                        if ( spouse != null )
                        {
                            action.Activity.Workflow.SetAttributeValue( spouseAttribute.Key, spouse.PrimaryAlias.Guid.ToString() );
                            action.AddLogEntry( string.Format( "Set spouse attribute '{0}' attribute to '{1}'.", spouseAttribute.Name, spouse.FullName ) );
                            return true;
                        }
                        else
                        {
                            action.AddLogEntry( string.Format( "No spouse found for {0}.", person.FullName ) );
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add("No person was provided.");
                return false;
            }

            errorMessages.ForEach( m => action.AddLogEntry( m, true ) );

            return true;
        }
Beispiel #30
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            if ( entity is Model.BinaryFile )
            {
               var binaryFile = (Model.BinaryFile) entity;
                if ( binaryFile.BinaryFileType.Guid != new Guid( SystemGuid.BinaryFiletype.CHECKIN_LABEL ) )
                {
                    errorMessages.Add( "Binary file is not a check-in label" );
                    action.AddLogEntry( "Binary file is not a check-in label", true );
                    return false;
                }

                binaryFile.LoadAttributes();

                // Get the existing merge fields
                var existingMergeFields = new Dictionary<string, string>();
                foreach ( var keyAndVal in binaryFile.GetAttributeValue( "MergeCodes" ).Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ) )
                {
                    var keyVal = keyAndVal.Split( new char[] { '^' } );
                    if ( keyVal.Length == 2 )
                    {
                        existingMergeFields.AddOrIgnore( keyVal[0], keyVal[1] );
                    }
                }

                // Build new merge fields
                var newMergeFields = new List<string>();
                foreach ( Match match in Regex.Matches( binaryFile.ContentsToString(), @"(?<=\^FD)((?!\^FS).)*(?=\^FS)" ) )
                {
                    string value = existingMergeFields.ContainsKey( match.Value ) ? existingMergeFields[match.Value] : "";
                    newMergeFields.Add( string.Format( "{0}^{1}", match.Value, value ) );
                }

                // Save attribute value
                var attributeValue = new AttributeValueCache();
                attributeValue.Value = newMergeFields.AsDelimited( "|" );

                binaryFile.AttributeValues["MergeCodes"] = attributeValue;
                binaryFile.SaveAttributeValues( rockContext );
            }

            return true;
        }
Beispiel #31
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // Get the entity type
            EntityTypeCache entityType = null;
            var entityTypeGuid = GetAttributeValue( action, AttributeKey.EntityType ).AsGuidOrNull();
            if ( entityTypeGuid.HasValue )
            {
                entityType = EntityTypeCache.Get( entityTypeGuid.Value );
            }

            if ( entityType == null )
            {
                var message = $"Entity Type could not be found for selected value ('{entityTypeGuid.ToString()}')!";
                errorMessages.Add( message );
                action.AddLogEntry( message, true );
                return false;
            }

            var mergeFields = GetMergeFields( action );
            var _rockContext = new RockContext();

            // Get the entity
            var entityTypeService = new EntityTypeService( _rockContext );
            IEntity entityObject = null;
            var entityIdGuidString = GetAttributeValue( action, AttributeKey.EntityIdOrGuid, true ).ResolveMergeFields( mergeFields ).Trim();
            var entityId = entityIdGuidString.AsIntegerOrNull();
            if ( entityId.HasValue )
            {
                entityObject = entityTypeService.GetEntity( entityType.Id, entityId.Value );
            }
            else
            {
                var entityGuid = entityIdGuidString.AsGuidOrNull();
                if ( entityGuid.HasValue )
                {
                    entityObject = entityTypeService.GetEntity( entityType.Id, entityGuid.Value );
                }
            }

            if ( entityObject == null )
            {
                var value = GetActionAttributeValue( action, AttributeKey.EntityIdOrGuid );
                entityObject = action.GetEntityFromAttributeValue( value, rockContext );
            }

            if ( entityObject == null )
            {
                var message = $"Entity could not be found for selected value ('{entityIdGuidString}')!";
                errorMessages.Add( message );
                action.AddLogEntry( message, true );
                return false;
            }

            var attributeFilteredDocumentType = GetAttributeValue( action, AttributeKey.DocumentType ).Split( ',' ).Select( int.Parse ).FirstOrDefault();
            var documentType = DocumentTypeCache.Get( attributeFilteredDocumentType );
            if ( documentType == null )
            {
                var message = $"Document Type could not be found for selected value ('{attributeFilteredDocumentType}')!";
                errorMessages.Add( message );
                action.AddLogEntry( message, true );
                return false;
            }

            var documentypesForContextEntityType = DocumentTypeCache.GetByEntity( entityType.Id, true );
            if ( !documentypesForContextEntityType.Any( d => attributeFilteredDocumentType == d.Id ) )
            {
                var message = "The Document Type does not match the selected entity type.";
                errorMessages.Add( message );
                action.AddLogEntry( message, true );
                return false;
            }

            var binaryFile = new BinaryFileService( rockContext ).Get( GetAttributeValue( action, AttributeKey.DocumentAttribute, true ).AsGuid() );

            if ( binaryFile == null )
            {
                action.AddLogEntry( "The document to add to the entity was not found.", true );

                // returning true here to allow the action to run 'successfully' without a document.
                // This allows the action to be easily used when the document is optional without a bunch of action filter tests.
                return true;
            }

            var documentName = GetAttributeValue( action, AttributeKey.DocumentName ).ResolveMergeFields( mergeFields );
            if ( documentName.IsNullOrWhiteSpace() )
            {
                documentName = Path.GetFileNameWithoutExtension( binaryFile.FileName );
            }

            var document = new Document();
            document.Name = documentName;
            document.Description = GetAttributeValue( action, AttributeKey.DocumentDescription ).ResolveMergeFields( mergeFields );
            document.EntityId = entityObject.Id;
            document.DocumentTypeId = documentType.Id;
            document.SetBinaryFile( binaryFile.Id, rockContext );

            var documentService = new DocumentService( rockContext );
            documentService.Add( document );
            rockContext.SaveChanges();

            action.AddLogEntry( "Added document to the Entity." );
            return true;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid   = null;
            string filterValue = string.Empty;
            string filterKey   = string.Empty;

            // get the group attribute
            groupGuid = GetAttributeValue(action, "SelectionGroup").AsGuid();

            if (!groupGuid.HasValue)
            {
                errorMessages.Add("The selection group could not be found!");
            }

            // get filter key
            filterKey = GetAttributeValue(action, "GroupMemberAttributeKey");

            // get the filter value
            filterValue = GetAttributeValue(action, "FilterValue");
            Guid?filterValueGuid = filterValue.AsGuidOrNull();

            if (filterValueGuid.HasValue)
            {
                filterValue = action.GetWorklowAttributeValue(filterValueGuid.Value);
            }
            else
            {
                filterValue = filterValue.ResolveMergeFields(GetMergeFields(action));
            }

            // get group members
            var qry = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                      .Where(g => g.Group.Guid == groupGuid);

            if (!string.IsNullOrWhiteSpace(filterKey))
            {
                qry = qry.WhereAttributeValue(rockContext, filterKey, filterValue);
            }

            var groupMembers = qry.Select(g => new {
                g.Person.NickName,
                g.Person.LastName,
                g.Person.SuffixValueId,
                PrimaryAliasGuid = g.Person.Aliases.FirstOrDefault().Guid
            })
                               .ToList();

            if (groupMembers.Count() > 0)
            {
                // get random group member from options
                Random rnd = new Random();
                int    r   = rnd.Next(groupMembers.Count);

                var selectedGroupMember = groupMembers[r];

                // set value
                Guid selectPersonGuid = GetAttributeValue(action, "SelectedPerson").AsGuid();
                if (!selectPersonGuid.IsEmpty())
                {
                    var selectedPersonAttribute = AttributeCache.Read(selectPersonGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        // If this is a person type attribute
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, selectedGroupMember.PrimaryAliasGuid.ToString());
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, Person.FormatFullName(selectedGroupMember.NickName, selectedGroupMember.LastName, selectedGroupMember.SuffixValueId));
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add("No group member for the selected campus could be found.");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Beispiel #33
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var person = GetPersonAliasFromActionAttribute(AttributeKey.Person, rockContext, action, errorMessages);

            if (person != null)
            {
                var mergeFields = GetMergeFields(action);

                NoteService noteService = new NoteService(rockContext);

                Note note = new Note();
                note.EntityId       = person.Id;
                note.Caption        = GetAttributeValue(action, AttributeKey.Caption).ResolveMergeFields(mergeFields);
                note.IsAlert        = GetAttributeValue(action, AttributeKey.Alert).AsBoolean();
                note.IsPrivateNote  = false;
                note.Text           = GetAttributeValue(action, AttributeKey.Text).ResolveMergeFields(mergeFields);
                note.EditedDateTime = RockDateTime.Now;

                // Add a NoteUrl for a person based on the existing Person Profile page, routes, and parameters.
                var personPageService = new PageService(rockContext);
                var personPage        = personPageService.Get(SystemGuid.Page.PERSON_PROFILE_PERSON_PAGES.AsGuid());

                // If the Person Profile Page has at least one route and at least one Page Context, use those to build the Note URL.
                if (personPage.PageRoutes.Count > 0 && personPage.PageContexts.Count > 0)
                {
                    var personPageRoute   = personPage.PageRoutes.First();
                    var personPageContext = personPage.PageContexts.First();
                    var personIdParameter = personPageContext.IdParameter;

                    var personPageParameter = new Dictionary <string, string> {
                        { personIdParameter, person.Id.ToString() }
                    };
                    var personPageReference = new Web.PageReference(personPage.Id, personPageRoute.Id);
                    note.NoteUrl = personPageReference.BuildRouteURL(personPageParameter);
                }

                var noteType = NoteTypeCache.Get(GetAttributeValue(action, AttributeKey.NoteType).AsGuid());
                if (noteType != null)
                {
                    note.NoteTypeId = noteType.Id;
                }

                // get author
                var author = GetPersonAliasFromActionAttribute(AttributeKey.Author, rockContext, action, errorMessages);
                if (author != null)
                {
                    note.CreatedByPersonAliasId = author.PrimaryAlias.Id;
                }

                noteService.Add(note);
                rockContext.SaveChanges();

                return(true);
            }
            else
            {
                errorMessages.Add("No person was provided for the note.");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Beispiel #34
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid      = null;
            string attributeValue = string.Empty;
            string attributeKey   = string.Empty;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorkflowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (!groupGuid.HasValue)
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

            // get group attribute value
            attributeValue = GetAttributeValue(action, "AttributeValue");
            Guid guid = attributeValue.AsGuid();

            if (guid.IsEmpty())
            {
                attributeValue = attributeValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorkflowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    attributeValue = workflowAttributeValue;
                }
            }

            // get attribute key
            attributeKey = GetAttributeValue(action, "GroupAttributeKey").Replace(" ", "");

            // set attribute
            if (groupGuid.HasValue)
            {
                var qry = new GroupService(rockContext).Queryable()
                          .Where(m => m.Guid == groupGuid);

                foreach (var group in qry.ToList())
                {
                    group.LoadAttributes(rockContext);
                    if (group.Attributes.ContainsKey(attributeKey))
                    {
                        var attribute = group.Attributes[attributeKey];
                        Rock.Attribute.Helper.SaveAttributeValue(group, attribute, attributeValue, rockContext);
                    }
                    else
                    {
                        action.AddLogEntry(string.Format("The group attribute {0} does not exist!", attributeKey));
                        break;
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid = null;
            Person person    = null;
            Group  group     = null;
            string noteValue = string.Empty;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (group == null)
                    {
                        errorMessages.Add("The group provided does not exist.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid group provided.");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();

                    if (person == null)
                    {
                        errorMessages.Add("The person could not be found.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid person provided.");
                }
            }

            // get group member note
            noteValue = GetAttributeValue(action, "Note");
            guid      = noteValue.AsGuid();
            if (guid.IsEmpty())
            {
                noteValue = noteValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    noteValue = workflowAttributeValue;
                }
            }

            // set note
            if (group != null && person != null)
            {
                var groupMembers = new GroupMemberService(rockContext).Queryable()
                                   .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id).ToList();

                if (groupMembers.Count() > 0)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        groupMember.Note = noteValue;
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var    documentTemplateId = GetAttributeValue(action, AttributeKeys.DocumentTemplate).AsIntegerOrNull();
            Person person             = null;

            // get person
            Guid?personAttributeGuid = GetAttributeValue(action, AttributeKeys.Person).AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorkflowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        person = personAlias.Person;
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("There is no person set on the attribute. Please try again.");
                return(false);
            }

            if (documentTemplateId.HasValue)
            {
                var signatureDocument = new SignatureDocumentService(rockContext)
                                        .Queryable().AsNoTracking()
                                        .Where(d =>
                                               d.SignatureDocumentTemplateId == documentTemplateId.Value &&
                                               d.AppliesToPersonAlias != null &&
                                               d.AppliesToPersonAlias.PersonId == person.Id &&
                                               d.LastStatusDate.HasValue &&
                                               d.Status == SignatureDocumentStatus.Signed &&
                                               d.BinaryFile != null)
                                        .OrderByDescending(d => d.LastStatusDate.Value)
                                        .FirstOrDefault();

                if (signatureDocument != null)
                {
                    // get the attribute to store the document/file guid
                    var signatureDocumentAttributeGuid = GetAttributeValue(action, AttributeKeys.SignatureDocument).AsGuidOrNull();
                    if (signatureDocumentAttributeGuid.HasValue)
                    {
                        var signatureDocumentAttribute = AttributeCache.Get(signatureDocumentAttributeGuid.Value, rockContext);
                        if (signatureDocumentAttribute != null)
                        {
                            if (signatureDocumentAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.FILE.AsGuid(), rockContext).Id)
                            {
                                SetWorkflowAttributeValue(action, signatureDocumentAttributeGuid.Value, signatureDocument.BinaryFile.Guid.ToString());
                                return(true);
                            }
                            else
                            {
                                errorMessages.Add("Invalid field type for signature document attribute set.");
                                return(false);
                            }
                        }
                        else
                        {
                            errorMessages.Add("Invalid signature document attribute set.");
                            return(false);
                        }
                    }
                    else
                    {
                        errorMessages.Add("Signature document attribute must be set.");
                        return(false);
                    }
                }
                else
                {
                    var now = RockDateTime.Now;
                    var activatedDateTime = GetDateTimeActivated(action);

                    int?minutes = GetAttributeValue(action, AttributeKeys.MinutesToTimeout).AsIntegerOrNull();
                    if (minutes.HasValue)
                    {
                        if (activatedDateTime.AddMinutes(minutes.Value).CompareTo(now) <= 0)
                        {
                            action.AddLogEntry(string.Format("{0:N0} minutes have passed. Process timed out.", minutes.Value), true);
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    return(false);
                }
            }
            else
            {
                errorMessages.Add("There was no valid document template id set on this action.");
                return(false);
            }
        }
Beispiel #37
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            var recipients  = new List <RecipientData>();

            string to = GetAttributeValue(action, "Recipient");

            Guid?guid = to.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Get(guid.Value, rockContext);
                if (attribute != null)
                {
                    string toValue = action.GetWorklowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.EmailFieldType":
                        {
                            var recipientList = toValue.SplitDelimitedValues().ToList();
                            foreach (string recipient in recipientList)
                            {
                                recipients.Add(new RecipientData(recipient, mergeFields));
                            }
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!(person.IsEmailActive))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields);
                                    personDict.Add("Person", person);
                                    recipients.Add(new RecipientData(person.Email, personDict));
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toValue.AsIntegerOrNull();
                            Guid?groupGuid = toValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    if (person.IsEmailActive &&
                                        person.EmailPreference != EmailPreference.DoNotEmail &&
                                        !string.IsNullOrWhiteSpace(person.Email))
                                    {
                                        var personDict = new Dictionary <string, object>(mergeFields);
                                        personDict.Add("Person", person);
                                        recipients.Add(new RecipientData(person.Email, personDict));
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                var recipientList = to.SplitDelimitedValues().ToList();
                foreach (string recipient in recipientList)
                {
                    recipients.Add(new RecipientData(recipient, mergeFields));
                }
            }

            if (recipients.Any())
            {
                var emailMessage = new RockEmailMessage(GetAttributeValue(action, "SystemEmail").AsGuid());
                emailMessage.SetRecipients(recipients);
                emailMessage.CreateCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();
                emailMessage.Send();
            }

            return(true);
        }
Beispiel #38
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }

                    if (!groupRoleId.HasValue && group != null)
                    {
                        // use the group's grouptype's default group role if a group role wasn't specified
                        groupRoleId = group.GroupType.DefaultGroupRoleId;
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("No group role was provided and group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var status = this.GetAttributeValue(action, "GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active);

                var  groupMemberService = new GroupMemberService(rockContext);
                var  groupMember        = groupMemberService.GetByGroupIdAndPersonIdAndPreferredGroupRoleId(group.Id, person.Id, groupRoleId.Value);
                bool isNew = false;
                if (groupMember == null)
                {
                    groupMember                   = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupId           = group.Id;
                    groupMember.GroupRoleId       = groupRoleId.Value;
                    groupMember.GroupMemberStatus = status;
                    isNew = true;
                }
                else
                {
                    if (GetAttributeValue(action, "UpdateExisting").AsBoolean())
                    {
                        groupMember.GroupRoleId       = groupRoleId.Value;
                        groupMember.GroupMemberStatus = status;
                    }
                    action.AddLogEntry($"{person.FullName} was already a member of the selected group.", true);
                }

                if (groupMember.IsValidGroupMember(rockContext))
                {
                    if (isNew)
                    {
                        groupMemberService.Add(groupMember);
                    }
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
        private void CompleteFormAction(string formAction)
        {
            if (!string.IsNullOrWhiteSpace(formAction) &&
                _workflow != null &&
                _actionType != null &&
                _actionType.WorkflowForm != null &&
                _activity != null &&
                _action != null)
            {
                var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(null);
                mergeFields.Add("Action", _action);
                mergeFields.Add("Activity", _activity);
                mergeFields.Add("Workflow", _workflow);
                if (CurrentPerson != null)
                {
                    mergeFields.Add("CurrentPerson", CurrentPerson);
                }

                Guid   activityTypeGuid = Guid.Empty;
                string responseText     = "Your information has been submitted succesfully.";

                foreach (var action in _actionType.WorkflowForm.Actions.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var actionDetails = action.Split(new char[] { '^' });
                    if (actionDetails.Length > 0 && actionDetails[0] == formAction)
                    {
                        if (actionDetails.Length > 2)
                        {
                            activityTypeGuid = actionDetails[2].AsGuid();
                        }

                        if (actionDetails.Length > 3 && !string.IsNullOrWhiteSpace(actionDetails[3]))
                        {
                            responseText = actionDetails[3].ResolveMergeFields(mergeFields);
                        }
                        break;
                    }
                }

                _action.MarkComplete();
                _action.FormAction = formAction;
                _action.AddLogEntry("Form Action Selected: " + _action.FormAction);

                if (_action.ActionType.IsActivityCompletedOnSuccess)
                {
                    _action.Activity.MarkComplete();
                }

                if (_actionType.WorkflowForm.ActionAttributeGuid.HasValue)
                {
                    var attribute = AttributeCache.Read(_actionType.WorkflowForm.ActionAttributeGuid.Value);
                    if (attribute != null)
                    {
                        IHasAttributes item = null;
                        if (attribute.EntityTypeId == _workflow.TypeId)
                        {
                            item = _workflow;
                        }
                        else if (attribute.EntityTypeId == _activity.TypeId)
                        {
                            item = _activity;
                        }

                        if (item != null)
                        {
                            item.SetAttributeValue(attribute.Key, formAction);
                        }
                    }
                }

                if (!activityTypeGuid.IsEmpty())
                {
                    var activityType = _workflowType.ActivityTypes.Where(a => a.Guid.Equals(activityTypeGuid)).FirstOrDefault();
                    if (activityType != null)
                    {
                        WorkflowActivity.Activate(activityType, _workflow);
                    }
                }

                List <string> errorMessages;
                if (_workflowService.Process(_workflow, out errorMessages))
                {
                    int?previousActionId = null;

                    if (_action != null)
                    {
                        previousActionId = _action.Id;
                    }

                    ActionTypeId = null;
                    _action      = null;
                    _actionType  = null;
                    _activity    = null;

                    if (HydrateObjects() && _action != null && _action.Id != previousActionId)
                    {
                        BuildForm(true);
                    }
                    else
                    {
                        ShowMessage(NotificationBoxType.Success, string.Empty, responseText, (_action == null || _action.Id != previousActionId));
                    }
                }
                else
                {
                    ShowMessage(NotificationBoxType.Danger, "Workflow Processing Error(s):",
                                "<ul><li>" + errorMessages.AsDelimited("</li><li>") + "</li></ul>");
                }
                if (_workflow.Id != 0)
                {
                    WorkflowId = _workflow.Id;
                }
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group = null;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Get(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            //
            // Check if person is in the group.
            //
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMembers       = groupMemberService.Queryable().Where(m => m.GroupId == group.Id && m.PersonId == person.Id).ToList();
                var statuses           = this.GetAttributeValue(action, "GroupMemberStatus")
                                         .SplitDelimitedValues()
                                         .Select(s => ( GroupMemberStatus )Enum.Parse(typeof(GroupMemberStatus), s))
                                         .ToList();

                groupMembers = groupMembers.Where(m => statuses.Contains(m.GroupMemberStatus)).ToList();

                if (!string.IsNullOrWhiteSpace(GetAttributeValue(action, "GroupRole")))
                {
                    var groupRole = new GroupTypeRoleService(rockContext).Get(GetAttributeValue(action, "GroupRole").AsGuid());

                    groupMembers = groupMembers.Where(m => m.GroupRoleId == groupRole.Id).ToList();
                }

                //
                // Set value of the selected attribute.
                //
                Guid selectAttributeGuid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!selectAttributeGuid.IsEmpty())
                {
                    var selectedPersonAttribute = AttributeCache.Get(selectAttributeGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.BOOLEAN.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectAttributeGuid, groupMembers.Any() ? "True" : "False");
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.INTEGER.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectAttributeGuid, groupMembers.Any() ? "1" : "0");
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            if (GetAttributeValue(action, "StoreAsId").AsBoolean(false) == true)
                            {
                                SetWorkflowAttributeValue(action, selectAttributeGuid, string.Join(",", groupMembers.Select(m => m.GroupRoleId.ToString())));
                            }
                            else
                            {
                                SetWorkflowAttributeValue(action, selectAttributeGuid, string.Join(",", groupMembers.Select(m => m.GroupRole.Name)));
                            }
                        }
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Beispiel #41
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            string to                  = GetAttributeValue(action, AttributeKey.To);
            string fromValue           = GetAttributeValue(action, AttributeKey.From);
            string replyTo             = GetAttributeValue(action, AttributeKey.ReplyTo);
            string subject             = GetAttributeValue(action, AttributeKey.Subject);
            string body                = GetAttributeValue(action, AttributeKey.Body);
            string cc                  = GetActionAttributeValue(action, AttributeKey.Cc);
            string bcc                 = GetActionAttributeValue(action, AttributeKey.Bcc);
            var    attachmentOneGuid   = GetAttributeValue(action, AttributeKey.AttachmentOne, true).AsGuid();
            var    attachmentTwoGuid   = GetAttributeValue(action, AttributeKey.AttachmentTwo, true).AsGuid();
            var    attachmentThreeGuid = GetAttributeValue(action, AttributeKey.AttachmentThree, true).AsGuid();

            var attachmentList = new List <BinaryFile>();

            if (!attachmentOneGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentOneGuid));
            }

            if (!attachmentTwoGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentTwoGuid));
            }

            if (!attachmentThreeGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentThreeGuid));
            }

            var attachments = attachmentList.ToArray();

            bool createCommunicationRecord = GetAttributeValue(action, AttributeKey.SaveCommunicationHistory).AsBoolean();

            string fromEmailAddress = string.Empty;
            string fromName         = string.Empty;
            Guid?  fromGuid         = fromValue.AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var attribute = AttributeCache.Get(fromGuid.Value, rockContext);
                if (attribute != null)
                {
                    string fromAttributeValue = action.GetWorkflowAttributeValue(fromGuid.Value);
                    if (!string.IsNullOrWhiteSpace(fromAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = fromAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                                {
                                    fromEmailAddress = person.Email;
                                    fromName         = person.FullName;
                                }
                            }
                        }
                        else
                        {
                            fromEmailAddress = fromAttributeValue;
                        }
                    }
                }
            }
            else
            {
                fromEmailAddress = fromValue.ResolveMergeFields(mergeFields);
            }

            string replyToEmailAddress = string.Empty;
            Guid?  replyToGuid         = replyTo.AsGuidOrNull();

            // If there is a "Reply To" value for the attribute, use that to get the "Reply To" email.
            if (replyToGuid.HasValue)
            {
                var attribute = AttributeCache.Get(replyToGuid.Value, rockContext);
                if (attribute != null)
                {
                    string replyToAttributeValue = action.GetWorkflowAttributeValue(replyToGuid.Value);
                    if (!string.IsNullOrWhiteSpace(replyToAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = replyToAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var personEmail = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .Select(a => a.Person.Email)
                                                  .FirstOrDefault();
                                if (personEmail.IsNotNullOrWhiteSpace())
                                {
                                    replyToEmailAddress = personEmail;
                                }
                            }
                        }
                        else
                        {
                            replyToEmailAddress = replyToAttributeValue;
                        }
                    }
                }
            }
            else
            {
                replyToEmailAddress = replyTo.ResolveMergeFields(mergeFields);
            }

            // To Email recipients list.
            if (GetEmailsFromAttributeValue(RecipientType.SendTo, to, action, mergeFields, rockContext, out string toDelimitedEmails, out List <RockEmailMessageRecipient> toRecipients))
            {
                // CC emails recipients list.
                GetEmailsFromAttributeValue(RecipientType.CC, cc, action, mergeFields, rockContext, out string ccDelimitedEmails, out List <RockEmailMessageRecipient> ccRecipients);
                List <string> ccEmails = BuildEmailList(ccDelimitedEmails, mergeFields, ccRecipients);

                // BCC emails recipients list.
                GetEmailsFromAttributeValue(RecipientType.BCC, bcc, action, mergeFields, rockContext, out string bccDelimitedEmails, out List <RockEmailMessageRecipient> bccRecipients);
                List <string> bccEmails = BuildEmailList(bccDelimitedEmails, mergeFields, bccRecipients);

                if (!string.IsNullOrWhiteSpace(toDelimitedEmails))
                {
                    Send(toDelimitedEmails, fromEmailAddress, fromName, replyToEmailAddress, subject, body, ccEmails, bccEmails, mergeFields, createCommunicationRecord, attachments, out errorMessages);
                }
                else if (toRecipients != null)
                {
                    Send(toRecipients, fromEmailAddress, fromName, replyToEmailAddress, subject, body, ccEmails, bccEmails, createCommunicationRecord, attachments, out errorMessages);
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(true);
        }
Beispiel #42
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // get person
            int?personId = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null && attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            personId = new PersonAliasService(rockContext).Queryable()
                                       .Where(a => a.Guid.Equals(personAliasGuid))
                                       .Select(a => a.PersonId)
                                       .FirstOrDefault();
                            if (personId == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (personId == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the phone type to edit
            DefinedValueCache phoneType = null;
            var phoneTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "PhoneTypeAttribute").AsGuid());

            if (phoneTypeAttributeValue != null)
            {
                phoneType = DefinedValueCache.Get(phoneTypeAttributeValue.AsGuid());
            }
            if (phoneType == null)
            {
                phoneType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneType").AsGuid());
            }
            if (phoneType == null)
            {
                errorMessages.Add("The phone type to be updated was not selected.");
                return(false);
            }

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean(true);

            // get the new phone number value
            string phoneNumberValue     = GetAttributeValue(action, "PhoneNumber");
            Guid?  phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull();

            if (phoneNumberValueGuid.HasValue)
            {
                phoneNumberValue = action.GetWorklowAttributeValue(phoneNumberValueGuid.Value);
            }
            else
            {
                phoneNumberValue = phoneNumberValue.ResolveMergeFields(GetMergeFields(action));
            }
            phoneNumberValue = PhoneNumber.CleanNumber(phoneNumberValue);

            // gets value indicating if phone number is unlisted
            string unlistedValue     = GetAttributeValue(action, "Unlisted");
            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();

            if (unlistedValueGuid.HasValue)
            {
                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
            }
            else
            {
                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?unlisted = unlistedValue.AsBooleanOrNull();

            // gets value indicating if messaging should be enabled for phone number
            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();

            if (smsEnabledValueGuid.HasValue)
            {
                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
            }
            else
            {
                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?smsEnabled = smsEnabledValue.AsBooleanOrNull();

            bool updated            = false;
            bool newPhoneNumber     = false;
            var  phoneNumberService = new PhoneNumberService(rockContext);
            var  phoneNumber        = phoneNumberService.Queryable()
                                      .Where(n =>
                                             n.PersonId == personId.Value &&
                                             n.NumberTypeValueId == phoneType.Id)
                                      .FirstOrDefault();
            string oldValue = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id, PersonId = personId.Value
                };
                newPhoneNumber = true;
                updated        = true;
            }
            else
            {
                oldValue = phoneNumber.NumberFormattedWithCountryCode;
            }

            if (!string.IsNullOrWhiteSpace(phoneNumberValue) || !ignoreBlanks)
            {
                updated            = updated || phoneNumber.Number != phoneNumberValue;
                phoneNumber.Number = phoneNumberValue;
            }
            if (unlisted.HasValue)
            {
                updated = updated || phoneNumber.IsUnlisted != unlisted.Value;
                phoneNumber.IsUnlisted = unlisted.Value;
            }
            if (smsEnabled.HasValue)
            {
                updated = updated || phoneNumber.IsMessagingEnabled != smsEnabled.Value;
                phoneNumber.IsMessagingEnabled = smsEnabled.Value;
            }

            if (updated)
            {
                if (oldValue != phoneNumber.NumberFormattedWithCountryCode)
                {
                    var changes = new History.HistoryChangeList();
                    changes.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Phone").SetSourceOfChange($"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow");
                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId.Value, changes, false);
                }

                if (phoneNumber.Number.IsNullOrWhiteSpace())
                {
                    if (!newPhoneNumber)
                    {
                        phoneNumberService.Delete(phoneNumber);
                    }
                }
                else
                {
                    if (newPhoneNumber)
                    {
                        phoneNumberService.Add(phoneNumber);
                    }
                }

                rockContext.SaveChanges();

                if (action.Activity != null && action.Activity.Workflow != null)
                {
                    var workflowType = action.Activity.Workflow.WorkflowTypeCache;
                    if (workflowType != null && workflowType.LoggingLevel == WorkflowLoggingLevel.Action)
                    {
                        var person = new PersonService(rockContext).Get(personId.Value);
                        action.AddLogEntry(string.Format("Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode));
                    }
                }
            }

            return(true);
        }
Beispiel #43
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            string providerGuid = GetAttributeValue(action, "Provider");

            if (!string.IsNullOrWhiteSpace(providerGuid))
            {
                var provider = BackgroundCheckContainer.GetComponent(providerGuid);
                if (provider != null)
                {
                    BackgroundCheckService backgroundCheckService = new BackgroundCheckService(rockContext);
                    var backgroundCheck = backgroundCheckService.Queryable().Where(b => b.WorkflowId == action.Activity.Workflow.Id).FirstOrDefault();
                    if (backgroundCheck == null)
                    {
                        //If for some reason a background check entity isn't available
                        //Add a log and set the report Status To Error.
                        //This allows the workflow to handle issues gracefully
                        action.AddLogEntry("No valid background check exists for this workflow", true);
                        SetWorkflowAttributeValue(action, GetAttributeValue(action, "ReportStatus").AsGuid(), "Error");
                        return(true);
                    }
                    var transactionId = backgroundCheck.RequestId;

                    var statusURL      = provider.GetAttributeValue("StatusURL");
                    var subscriberCode = Encryption.DecryptString(provider.GetAttributeValue("SubscriberCode"));
                    var companyCode    = Encryption.DecryptString(provider.GetAttributeValue("CompanyCode"));

                    Trak1ReportStatus status = null;
                    var resource             = string.Format("/{0}/{1}/{2}", subscriberCode, companyCode, transactionId);

                    using (var client = new HttpClient(new HttpClientHandler()))
                    {
                        client.BaseAddress = new Uri(statusURL + resource);
                        var clientResponse = client.GetAsync("").Result.Content.ReadAsStringAsync().Result;
                        status = JsonConvert.DeserializeObject <Trak1ReportStatus>(clientResponse);
                    }

                    SetWorkflowAttributeValue(action, GetAttributeValue(action, "ReportStatus").AsGuid(), status.ReportStatus);
                    backgroundCheck.Status = status.ReportStatus;

                    SetWorkflowAttributeValue(action, GetAttributeValue(action, "HitColor").AsGuid(), status.HitColor);
                    backgroundCheck.RecordFound = status.HitColor == "Green";

                    var         reportURL = provider.GetAttributeValue("ReportURL");
                    Trak1Report response  = null;
                    using (var client = new HttpClient(new HttpClientHandler()))
                    {
                        client.BaseAddress = new Uri(reportURL + resource);
                        var clientResponse = client.GetAsync("").Result.Content.ReadAsStringAsync().Result;
                        response = JsonConvert.DeserializeObject <Trak1Report>(clientResponse);
                    }

                    SetWorkflowAttributeValue(action, GetAttributeValue(action, "ReportUrl").AsGuid(), response.ReportUrl);
                    backgroundCheck.ResponseDate = Rock.RockDateTime.Now;
                    backgroundCheck.ResponseData = response.ReportUrl;

                    return(true);
                }
                else
                {
                    errorMessages.Add("Invalid Background Check Provider!");
                }
            }
            else
            {
                errorMessages.Add("Invalid Background Check Provider Guid!");
            }

            return(false);
        }
Beispiel #44
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (entity != null && entity is IEntity)
            {
                Guid guid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!guid.IsEmpty())
                {
                    var attribute = AttributeCache.Get(guid, rockContext);
                    if (attribute != null)
                    {
                        // If a lava template was specified, use that to set the attribute value
                        string lavaTemplate = GetAttributeValue(action, "LavaTemplate");
                        if (!string.IsNullOrWhiteSpace(lavaTemplate))
                        {
                            var mergeFields = GetMergeFields(action);
                            mergeFields.Add("Entity", entity);
                            string parsedValue = lavaTemplate.ResolveMergeFields(mergeFields);
                            SetWorkflowAttributeValue(action, guid, parsedValue);
                        }
                        else
                        {
                            // Person + PersonFieldType is handled differently since it needs to be stored as PersonAlias.Guid
                            if (entity is Person && attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                            {
                                var primaryAlias = GetPrimaryPersonAlias(( Person )entity, rockContext, errorMessages);
                                if (primaryAlias != null)
                                {
                                    SetWorkflowAttributeValue(action, guid, primaryAlias.Guid.ToString());
                                    return(true);
                                }
                            }
                            // If the attribute is an Entity FieldType, store the value as EntityType.Guid|Entity.Id
                            else if (attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.ENTITY.AsGuid(), rockContext).Id)
                            {
                                // Person + EntityFieldType is handled differently since it needs to be stored as PersonAlias's EntityType.Guid
                                EntityTypeCache entityType = entity is Person
                                    ? EntityTypeCache.Get(SystemGuid.EntityType.PERSON_ALIAS)
                                    : EntityTypeCache.Get(entity.GetType(), rockContext: rockContext);

                                if (entityType == null)
                                {
                                    errorMessages.Add("Unable to find the entity type. Type=" + entity.GetType().FullName);
                                }
                                else
                                {
                                    // Person + EntityFieldType is handled differently since it needs to be stored as PersonAlias.Id
                                    int?entityId = entity is Person
                                        ? GetPrimaryPersonAlias(( Person )entity, rockContext, errorMessages)?.Id
                                        : (( IEntity )entity).Id;

                                    if (entityId.HasValue)
                                    {
                                        var value = $"{entityType.Guid}|{entityId.ToStringSafe()}";
                                        SetWorkflowAttributeValue(action, guid, value);
                                    }
                                }
                            }
                            else
                            {
                                if (GetAttributeValue(action, "UseId").AsBoolean())
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Id.ToString());
                                }
                                else
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Guid.ToString());
                                }
                            }
                        }

                        return(true);
                    }
                    else
                    {
                        errorMessages.Add("Unable to find the attribute from the attribute GUID=" + guid.ToStringSafe());
                    }
                }
                else
                {
                    errorMessages.Add("Unable to find the attribute GUID.");
                }
            }
            else
            {
                if (!GetAttributeValue(action, "EntityIsRequired").AsBoolean(true))
                {
                    return(true);
                }

                errorMessages.Add("No entity was specified or the entity is not a Rock Entity.");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(false);
        }
Beispiel #45
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            string to        = GetAttributeValue(action, "To");
            string fromValue = GetAttributeValue(action, "From");
            string subject   = GetAttributeValue(action, "Subject");
            string body      = GetAttributeValue(action, "Body");

            BinaryFile[] attachments = { new BinaryFileService(rockContext).Get(GetAttributeValue(action, "AttachmentOne",   true).AsGuid()),
                                         new BinaryFileService(rockContext).Get(GetAttributeValue(action, "AttachmentTwo",   true).AsGuid()),
                                         new BinaryFileService(rockContext).Get(GetAttributeValue(action, "AttachmentThree", true).AsGuid()) };

            bool createCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();

            string fromEmail = string.Empty;
            string fromName  = string.Empty;
            Guid?  fromGuid  = fromValue.AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var attribute = AttributeCache.Get(fromGuid.Value, rockContext);
                if (attribute != null)
                {
                    string fromAttributeValue = action.GetWorklowAttributeValue(fromGuid.Value);
                    if (!string.IsNullOrWhiteSpace(fromAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = fromAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                                {
                                    fromEmail = person.Email;
                                    fromName  = person.FullName;
                                }
                            }
                        }
                        else
                        {
                            fromEmail = fromAttributeValue;
                        }
                    }
                }
            }
            else
            {
                fromEmail = fromValue;
            }

            Guid?guid = to.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Get(guid.Value, rockContext);
                if (attribute != null)
                {
                    string toValue = action.GetWorklowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.EmailFieldType":
                        {
                            Send(toValue, fromEmail, fromName, subject, body, mergeFields, rockContext, createCommunicationRecord, attachments);
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!person.IsEmailActive)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields);
                                    personDict.Add("Person", person);
                                    Send(person.Email, fromEmail, fromName, subject, body, personDict, rockContext, createCommunicationRecord, attachments);
                                }
                            }

                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toValue.AsIntegerOrNull();
                            Guid?groupGuid = toValue.AsGuidOrNull();

                            // Get the Group Role attribute value
                            Guid?groupRoleValueGuid = GetGroupRoleValue(action);

                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }
                            else if (groupGuid.HasValue)
                            {
                                // Handle situations where the attribute value stored is the Guid
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (groupRoleValueGuid.HasValue)
                            {
                                qry = qry.Where(m => m.GroupRole != null && m.GroupRole.Guid.Equals(groupRoleValueGuid.Value));
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    if (person.IsEmailActive &&
                                        person.EmailPreference != EmailPreference.DoNotEmail &&
                                        !string.IsNullOrWhiteSpace(person.Email))
                                    {
                                        var personDict = new Dictionary <string, object>(mergeFields);
                                        personDict.Add("Person", person);
                                        Send(person.Email, fromEmail, fromName, subject, body, personDict, rockContext, createCommunicationRecord, attachments);
                                    }
                                }
                            }

                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                Send(to.ResolveMergeFields(mergeFields), fromEmail, fromName, subject, body, mergeFields, rockContext, createCommunicationRecord, attachments);
            }

            return(true);
        }
Beispiel #46
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var attribute = AttributeCache.Get(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }
                    }

                    // Save/update the phone number
                    if (!string.IsNullOrWhiteSpace(phone))
                    {
                        List <string> changes    = new List <string>();
                        var           numberType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneNumberType").AsGuid());
                        if (numberType != null)
                        {
                            // gets value indicating if phone number is unlisted
                            string unlistedValue     = GetAttributeValue(action, "Unlisted");
                            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                            if (unlistedValueGuid.HasValue)
                            {
                                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
                            }
                            else
                            {
                                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool unlisted = unlistedValue.AsBoolean();

                            // gets value indicating if messaging should be enabled for phone number
                            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                            if (smsEnabledValueGuid.HasValue)
                            {
                                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
                            }
                            else
                            {
                                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool smsEnabled = smsEnabledValue.AsBoolean();


                            var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                            string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                            string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                            if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                            {
                                if (phoneModel == null)
                                {
                                    phoneModel = new PhoneNumber();
                                    person.PhoneNumbers.Add(phoneModel);
                                    phoneModel.NumberTypeValueId = numberType.Id;
                                }
                                else
                                {
                                    oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                }
                                phoneModel.Number             = newPhoneNumber;
                                phoneModel.IsUnlisted         = unlisted;
                                phoneModel.IsMessagingEnabled = smsEnabled;
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                if (GetAttributeValue(action, "ContinueOnError").AsBoolean())
                {
                    errorMessages.Clear();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #47
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var service = new PageShortLinkService(rockContext);

            // Get the merge fields
            var mergeFields = GetMergeFields(action);

            // Get the site
            int       siteId = GetAttributeValue(action, "Site", true).AsInteger();
            SiteCache site   = SiteCache.Get(siteId);

            if (site == null)
            {
                errorMessages.Add(string.Format("Invalid Site Value"));
                return(false);
            }

            // Get the token
            string token = GetAttributeValue(action, "Token", true).ResolveMergeFields(mergeFields);

            if (token.IsNullOrWhiteSpace())
            {
                int tokenLen = GetAttributeValue(action, "RandomTokenLength").AsIntegerOrNull() ?? 7;
                token = service.GetUniqueToken(site.Id, tokenLen);
            }

            // Get the target url
            string url = GetAttributeValue(action, "Url", true).ResolveMergeFields(mergeFields).RemoveCrLf().Trim();

            if (url.IsNullOrWhiteSpace())
            {
                errorMessages.Add("A valid Target URL was not specified.");
                return(false);
            }

            // Save the short link
            var link = service.GetByToken(token, site.Id);

            if (link != null)
            {
                if (!GetAttributeValue(action, "Overwrite").AsBoolean())
                {
                    errorMessages.Add(string.Format("The selected token ('{0}') already exists. Please specify a unique token, or configure action to allow token re-use.", token));
                    return(false);
                }
                else
                {
                    link.Url = url;
                }
            }
            else
            {
                link        = new PageShortLink();
                link.SiteId = site.Id;
                link.Token  = token;
                link.Url    = url;
                service.Add(link);
            }
            rockContext.SaveChanges();

            // Save the resulting short link url
            var attribute = AttributeCache.Get(GetAttributeValue(action, "Attribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                string shortLink = link.ShortLinkUrl;

                SetWorkflowAttributeValue(action, attribute.Guid, shortLink);
                action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, shortLink));
            }

            return(true);
        }
Beispiel #48
0
        private void SendEmail(RockContext rockContext, WorkflowAction action)
        {
            var mergeFields = GetMergeFields(action);

            string to        = GetAttributeValue(action, "To");
            string fromValue = GetAttributeValue(action, "From");
            string subject   = GetAttributeValue(action, "Subject");
            string body      = GetAttributeValue(action, "Body");
            bool   createCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();

            string fromEmailAddress = string.Empty;
            string fromName         = string.Empty;
            Guid?  fromGuid         = fromValue.AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var attribute = AttributeCache.Get(fromGuid.Value, rockContext);
                if (attribute != null)
                {
                    string fromAttributeValue = action.GetWorklowAttributeValue(fromGuid.Value);
                    if (!string.IsNullOrWhiteSpace(fromAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = fromAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                                {
                                    fromEmailAddress = person.Email;
                                    fromName         = person.FullName;
                                }
                            }
                        }
                        else
                        {
                            fromEmailAddress = fromAttributeValue;
                        }
                    }
                }
            }
            else
            {
                fromEmailAddress = fromValue;
            }

            var metaData = new Dictionary <string, string>();

            metaData.Add("workflow_action_guid", action.Guid.ToString());

            Guid?guid = to.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Get(guid.Value, rockContext);
                if (attribute != null)
                {
                    string toValue = action.GetWorklowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            var recipientEmails = toValue.ResolveMergeFields(mergeFields);
                            Send(recipientEmails, fromEmailAddress, fromName, subject, body, mergeFields, createCommunicationRecord, metaData);
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!person.IsEmailActive)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields);
                                    personDict.Add("Person", person);
                                    var recipients = new RockEmailMessageRecipient[1] {
                                        new RockEmailMessageRecipient(person, personDict)
                                    }.ToList();
                                    Send(recipients, fromEmailAddress, fromName, subject, body, createCommunicationRecord, metaData);
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                var recipientEmails = to.ResolveMergeFields(mergeFields);
                Send(recipientEmails, fromEmailAddress, fromName, subject, body, mergeFields, createCommunicationRecord, metaData);
            }
        }
Beispiel #49
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get Group Type
            var groupTypeGuid = GetAttributeValue(action, "GroupType", true).AsGuid();
            var groupType     = GroupTypeCache.Read(groupTypeGuid);

            if (groupType == null)
            {
                // Appears Group type cache by gui is not always working.  Try to read from db.
                var groupTypeModel = new GroupTypeService(rockContext).Get(groupTypeGuid);
                if (groupTypeModel != null)
                {
                    groupType = GroupTypeCache.Read(groupTypeModel.Id);
                }
            }
            if (groupType == null)
            {
                errorMessages.Add("The Group Type could not be determined or found!");
            }

            // Group Name
            var groupName = GetAttributeValue(action, "GroupName", true);

            if (groupName.IsNullOrWhiteSpace())
            {
                errorMessages.Add("The Group Type could not be determined or found!");
            }

            // Parent Group
            Group parentGroup     = null;
            var   parentGroupGuid = GetAttributeValue(action, "ParentGroup", true).AsGuidOrNull();

            if (parentGroupGuid.HasValue)
            {
                parentGroup = new GroupService(rockContext).Get(parentGroupGuid.Value);
            }

            // Add request
            if (!errorMessages.Any())
            {
                var groupService = new GroupService(rockContext);

                Group group = null;

                int?parentGroupId = parentGroup != null ? parentGroup.Id : (int?)null;
                if (GetAttributeValue(action, "CheckExisting", true).AsBoolean())
                {
                    group = groupService.Queryable()
                            .Where(g =>
                                   g.GroupTypeId == groupType.Id &&
                                   g.Name == groupName &&
                                   ((!parentGroupId.HasValue && !g.ParentGroupId.HasValue) || (parentGroupId.HasValue && g.ParentGroupId.HasValue && g.ParentGroupId.Value == parentGroupId.Value)))
                            .FirstOrDefault();
                }

                if (group == null)
                {
                    group = new Group();
                    groupService.Add(group);
                    group.GroupTypeId = groupType.Id;
                    group.Name        = groupName;

                    if (parentGroup != null)
                    {
                        group.ParentGroupId = parentGroup.Id;
                    }

                    rockContext.SaveChanges();
                }

                if (group.Id > 0)
                {
                    string resultValue = group.Guid.ToString();
                    var    attribute   = SetWorkflowAttributeValue(action, "ResultAttribute", resultValue);
                    if (attribute != null)
                    {
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, resultValue));
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(!errorMessages.Any());
        }
Beispiel #50
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            double hoursElapsed = HoursElapsed(action);
            string emailStatus  = EmailStatus(action);

            if (hoursElapsed <= 0)
            {
                SendEmail(rockContext, action);
            }
            else
            {
                var timedOut = false;

                WorkflowActivityTypeCache unopenedActivityType = null;
                int? unopenedTimeout = null;
                Guid?guid            = GetAttributeValue(action, "UnopenedTimeoutActivity").AsGuidOrNull();
                if (guid.HasValue)
                {
                    unopenedActivityType = WorkflowActivityTypeCache.Get(guid.Value);
                    unopenedTimeout      = GetAttributeValue(action, "UnopenedTimeoutLength").AsIntegerOrNull();

                    if (emailStatus != OPENED_STATUS &&
                        emailStatus != CLICKED_STATUS &&
                        unopenedActivityType != null &&
                        unopenedTimeout.HasValue &&
                        unopenedTimeout.Value < hoursElapsed)
                    {
                        action.AddLogEntry("Unopened Timeout Occurred", true);
                        WorkflowActivity.Activate(unopenedActivityType, action.Activity.Workflow, rockContext);
                        timedOut = true;
                    }
                }

                WorkflowActivityTypeCache noActionActivityType = null;
                int?noActionTimeout = null;
                guid = GetAttributeValue(action, "NoActionTimeoutActivity").AsGuidOrNull();
                if (guid.HasValue)
                {
                    noActionActivityType = WorkflowActivityTypeCache.Get(guid.Value);
                    noActionTimeout      = GetAttributeValue(action, "NoActionTimeoutLength").AsIntegerOrNull();

                    if (emailStatus != CLICKED_STATUS &&
                        noActionActivityType != null &&
                        noActionTimeout.HasValue &&
                        noActionTimeout.Value < hoursElapsed)
                    {
                        action.AddLogEntry("No Action Timeout Occurred", true);
                        WorkflowActivity.Activate(noActionActivityType, action.Activity.Workflow, rockContext);
                        timedOut = true;
                    }
                }

                if (timedOut)
                {
                    UpdateEmailStatus(action.Guid, TIMEOUT_STATUS, string.Empty, rockContext, false);
                    return(true);
                }
            }

            return(false);
        }
Beispiel #51
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (entity != null && entity is IEntity)
            {
                Guid guid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!guid.IsEmpty())
                {
                    var attribute = AttributeCache.Get(guid, rockContext);
                    if (attribute != null)
                    {
                        // If a lava template was specified, use that to set the attribute value
                        string lavaTemplate = GetAttributeValue(action, "LavaTemplate");
                        if (!string.IsNullOrWhiteSpace(lavaTemplate))
                        {
                            var mergeFields = GetMergeFields(action);
                            mergeFields.Add("Entity", entity);
                            string parsedValue = lavaTemplate.ResolveMergeFields(mergeFields);
                            SetWorkflowAttributeValue(action, guid, parsedValue);
                        }
                        else
                        {
                            // Person is handled special since it needs the person alias id
                            if (entity is Person && attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                            {
                                var person = (Person)entity;

                                var primaryAlias = new PersonAliasService(rockContext).Queryable().FirstOrDefault(a => a.AliasPersonId == person.Id);
                                if (primaryAlias != null)
                                {
                                    SetWorkflowAttributeValue(action, guid, primaryAlias.Guid.ToString());
                                    return(true);
                                }
                                else
                                {
                                    errorMessages.Add("Person Entity: Could not determine person's primary alias. PersonId=" + person.Id);
                                }
                            }
                            else
                            {
                                if (GetAttributeValue(action, "UseId").AsBoolean())
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Id.ToString());
                                }
                                else
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Guid.ToString());
                                }
                            }
                        }

                        return(true);
                    }
                    else
                    {
                        errorMessages.Add("Unable to find the attribute from the attribute GUID=" + guid.ToStringSafe());
                    }
                }
                else
                {
                    errorMessages.Add("Unable to find the attribute GUID.");
                }
            }
            else
            {
                if (!GetAttributeValue(action, "EntityIsRequired").AsBoolean(true))
                {
                    return(true);
                }

                errorMessages.Add("No entity was specified or the entity is not a Rock Entity.");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(false);
        }
Beispiel #52
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            var recipients = new List <RecipientData>();

            string toValue = GetAttributeValue(action, "To");
            Guid   guid    = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            recipients.Add(new RecipientData(toAttributeValue));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var recipient = new RecipientData(smsNumber);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipient = new RecipientData(smsNumber);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields)));
                }
            }

            string message     = GetAttributeValue(action, "Message");
            Guid   messageGuid = message.AsGuid();

            if (!messageGuid.IsEmpty())
            {
                var attribute = AttributeCache.Read(messageGuid, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid(), rockContext);
                if (mediumEntity != null)
                {
                    var medium = MediumContainer.GetComponent(mediumEntity.Name);
                    if (medium != null && medium.IsActive)
                    {
                        var transport = medium.Transport;
                        if (transport != null && transport.IsActive)
                        {
                            var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot");

                            foreach (var recipient in recipients)
                            {
                                var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                foreach (var mergeField in recipient.MergeFields)
                                {
                                    recipientMergeFields.Add(mergeField.Key, mergeField.Value);
                                }
                                var mediumData = new Dictionary <string, string>();
                                mediumData.Add("FromValue", fromId.Value.ToString());
                                mediumData.Add("Message", message.ResolveMergeFields(recipientMergeFields));

                                var number = new List <string> {
                                    recipient.To
                                };

                                transport.Send(mediumData, number, appRoot, string.Empty);
                            }
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var actionType = action.ActionTypeCache;

            if (!action.LastProcessedDateTime.HasValue &&
                actionType != null &&
                actionType.WorkflowForm != null &&
                actionType.WorkflowForm.NotificationSystemEmailId.HasValue)
            {
                if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue))
                {
                    var recipients          = new List <RecipientData>();
                    var workflowMergeFields = GetMergeFields(action);

                    if (action.Activity.AssignedPersonAliasId.HasValue)
                    {
                        var person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Id == action.Activity.AssignedPersonAliasId.Value)
                                     .Select(a => a.Person)
                                     .FirstOrDefault();

                        if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (action.Activity.AssignedGroupId.HasValue)
                    {
                        var personList = new GroupMemberService(rockContext).GetByGroupId(action.Activity.AssignedGroupId.Value)
                                         .Where(m =>
                                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                m.Person.Email != "")
                                         .Select(m => m.Person)
                                         .ToList();

                        foreach (var person in personList)
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (recipients.Count > 0)
                    {
                        // The email may need to reference activity Id, so we need to save here.
                        WorkflowService workflowService = new WorkflowService(rockContext);
                        workflowService.PersistImmediately(action);

                        var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value);
                        if (systemEmail != null)
                        {
                            var emailMessage = new RockEmailMessage(systemEmail);
                            emailMessage.SetRecipients(recipients);
                            emailMessage.CreateCommunicationRecord = false;
                            emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty;
                            emailMessage.Send();
                        }
                        else
                        {
                            action.AddLogEntry("Could not find the selected notification system email", true);
                        }
                    }
                    else
                    {
                        action.AddLogEntry("Could not send form notification due to no assigned person or group member not having email address", true);
                    }
                }
                else
                {
                    action.AddLogEntry("Could not send form notification due to no assigned person or group", true);
                }
            }

            return(false);
        }
Beispiel #54
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Dictionary <string, object> mergeFields = GetMergeFields(action);

            List <Metric> metricList = GetFromAttribute(action, "Metric", "MetricAttribute", MetricListConverter, new MetricListConverterData {
                MergeFields = mergeFields, MetricService = new MetricService(rockContext)
            });
            MetricValueType?metricValueType = GetFromAttribute(action, "ValueType", "ValueTypeAttribute", EnumConverter <MetricValueType>, mergeFields);
            DateTime?       metricValueDate = GetFromAttribute(action, "ValueDate", "ValueDateAttribute", DateConverter, mergeFields);
            string          metricValueNote = GetFromAttribute(action, "ValueNote", "ValueNoteAttribute", StringConverter, mergeFields);

            var partitionsConfig = GetAttributeValue(action, "PartitionConfig")
                                   .ResolveMergeFields(mergeFields)
                                   .Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Select(s => s.Split(':'))
                                   .Where(s => s.Length == 2)
                                   .Select(c => new
            {
                Label = c[0],
                Value = c[1].AsIntegerOrNull()
            })
                                   .Where(c => c.Value != null)
                                   .ToList();

            string mValStr = GetAttributeValue(action, "MetricValue");

            if (Guid.TryParse(mValStr, out Guid mValGuid))
            {
                mValStr = action.GetWorkflowAttributeValue(mValGuid);
            }
            decimal?metricValueValue = mValStr.ResolveMergeFields(mergeFields).AsDecimalOrNull();


            if (metricList == null)
            {
                errorMessages.Add("No Metric(s) selected.");
            }

            if (metricValueType == null)
            {
                errorMessages.Add("No Value Type selected.");
            }

            if (metricValueDate == null)
            {
                errorMessages.Add("No Value Date selected.");
            }

            if (metricValueValue == null)
            {
                errorMessages.Add("No Value set.");
            }

            if (metricList == null || metricValueType == null || metricValueDate == null || metricValueValue == null || errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }


            new MetricValueService(rockContext).AddRange(metricList.Select(m =>
                                                                           new MetricValue
            {
                Metric = m,
                MetricValueDateTime = metricValueDate,
                MetricValueType     = metricValueType.Value,
                Note   = metricValueNote,
                YValue = metricValueValue,
                MetricValuePartitions = partitionsConfig
                                        .Select(p => new MetricValuePartition
                {
                    EntityId        = p.Value,
                    MetricPartition = m.MetricPartitions.FirstOrDefault(mp => mp.Label == p.Label)
                })
                                        .Where(mvp => mvp.MetricPartition != null).ToList()
            }

                                                                           ));

            rockContext.SaveChanges();

            return(true);
        }
Beispiel #55
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            // get benevolence request id
            var requestGuid = GetAttributeValue(action, "BenevolenceRequest", true).AsGuidOrNull();

            if (!requestGuid.HasValue)
            {
                var errorMessage = "A valid benevolence request ID was not provided.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // get result summary
            var resultSummary = GetAttributeValue(action, "ResultSummary", true).ResolveMergeFields(mergeFields);

            // get next steps
            var nextSteps = GetAttributeValue(action, "NextSteps", true).ResolveMergeFields(mergeFields);

            // get result type
            var resultType = DefinedValueCache.Get(GetAttributeValue(action, "ResultType", true).AsGuid());

            if (resultType == null)
            {
                var errorMessage = "A valid result type was not provided.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // get result details
            var resultDetails = GetAttributeValue(action, "ResultDetails", true).ResolveMergeFields(mergeFields);

            // get amount
            var amount = GetAttributeValue(action, "ResultAmount", true).AsDecimalOrNull();

            if (!amount.HasValue)
            {
                var errorMessage = "A valid result amount was not provided.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // create benevolence request
            BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService(rockContext);

            BenevolenceRequest request = benevolenceRequestService.Get(requestGuid.Value);

            if (request == null)
            {
                var errorMessage = "The benevolence request provided could not be found.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            if (nextSteps.IsNotNullOrWhiteSpace())
            {
                request.ProvidedNextSteps = nextSteps;
            }

            if (resultSummary.IsNotNullOrWhiteSpace())
            {
                request.ResultSummary = resultSummary;
            }

            BenevolenceResult result = new BenevolenceResult();

            request.BenevolenceResults.Add(result);

            result.Amount            = amount;
            result.ResultTypeValueId = resultType.Id;
            result.ResultSummary     = resultDetails;

            rockContext.SaveChanges();

            return(true);
        }
Beispiel #56
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var now = RockDateTime.Now;

            // Save/Get the datetime this action was first activated
            var activatedDateTime = GetDateTimeActivated(action);

            // First check if number of minutes to delay
            int?minutes = GetAttributeValue(action, "MinutesToDelay").AsIntegerOrNull();

            if (minutes.HasValue)
            {
                if (activatedDateTime.AddMinutes(minutes.Value).CompareTo(now) <= 0)
                {
                    action.AddLogEntry(string.Format("{0:N0} Minute Delay Completed.", minutes.Value), true);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            // Then check for specific date/time
            Guid dateAttributeGuid = GetAttributeValue(action, "DateInAttribute").AsGuid();

            if (!dateAttributeGuid.IsEmpty())
            {
                var attribute = AttributeCache.Read(dateAttributeGuid, rockContext);
                if (attribute != null)
                {
                    DateTime?attributeDate = action.GetWorklowAttributeValue(dateAttributeGuid).AsDateTime();
                    if (attributeDate.HasValue)
                    {
                        if (attributeDate.Value.CompareTo(now) <= 0)
                        {
                            action.AddLogEntry(string.Format("Delay until {0} Completed.", attributeDate.Value), true);
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
            }

            // Finally check weekday
            int?dayOfTheWeek = GetAttributeValue(action, "NextWeekday").AsIntegerOrNull();

            if (dayOfTheWeek.HasValue)
            {
                if ((int)now.DayOfWeek == dayOfTheWeek.Value)
                {
                    action.AddLogEntry(string.Format("Delay until {0} Completed.", now.DayOfWeek.ConvertToString()), true);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            // If delay has not elapsed, return false so that processing of activity stops
            return(false);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the Person, Group and GroupRole from the attributes
            Person        person    = GetEntityFromWorkflowAttributes(action, "Person", "PersonAttribute", new PersonAliasService(rockContext))?.Person;
            Group         group     = GetEntityFromWorkflowAttributes(action, "Group", "GroupAttribute", new GroupService(rockContext));
            GroupTypeRole groupRole = GetEntityFromWorkflowAttributes(action, "GroupRole", "GroupRoleAttribute", new GroupTypeRoleService(rockContext)) ?? group?.GroupType?.DefaultGroupRole;


            GroupMemberStatus?groupMemberStatus = null;

            Guid?groupMemberWorkflowAttributeAttribute = GetAttributeValue(action, "GroupMemberStatusAttribute").AsGuidOrNull();

            if (groupMemberWorkflowAttributeAttribute.HasValue)
            {
                string groupMemberWorkflowAttribute = action.GetWorklowAttributeValue(groupMemberWorkflowAttributeAttribute.Value);
                if (!string.IsNullOrWhiteSpace(groupMemberWorkflowAttribute))
                {
                    if (Enum.TryParse(groupMemberWorkflowAttribute, true, out GroupMemberStatus groupMemberStatusOut))
                    {
                        groupMemberStatus = groupMemberStatusOut;
                    }
                }
            }

            if (groupMemberStatus == null)
            {
                string groupMemberAttribute = GetAttributeValue(action, "GroupMemberStatus");
                if (!string.IsNullOrWhiteSpace(groupMemberAttribute))
                {
                    if (Enum.TryParse(groupMemberAttribute, true, out GroupMemberStatus groupMemberStatusOut))
                    {
                        groupMemberStatus = groupMemberStatusOut;
                    }
                }
            }


            if (person == null)
            {
                errorMessages.Add("Invalid Person.");
            }

            if (group == null)
            {
                errorMessages.Add("Invalid Group.");
            }

            if (groupRole == null)
            {
                errorMessages.Add("Invalid Group Role.");
            }

            if (person == null || group == null || groupRole == null || errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }


            if (group.Members.Any(m => m.PersonId == person.Id && m.GroupRoleId == groupRole.Id))
            {
                action.AddLogEntry("Skipping adding duplicate Group Member.");
            }
            else
            {
                var groupMember = new GroupMember
                {
                    PersonId          = person.Id,
                    GroupId           = group.Id,
                    GroupRoleId       = groupRole.Id,
                    GroupMemberStatus = groupMemberStatus ?? GroupMemberStatus.Pending
                };

                if (groupMember.IsValid)
                {
                    new GroupMemberService(rockContext).Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    // If the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(true);
        }
Beispiel #58
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var guidGroupAttribute = GetAttributeValue(action, AttributeKey.GroupKey).AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Get(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorkflowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);

                        if (group != null)
                        {
                            // use the group's grouptype's default group role if a group role wasn't specified
                            groupRoleId = GroupTypeCache.Get(group.GroupTypeId).DefaultGroupRoleId;
                        }
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }
            else
            {
                // Check if this is a security group and show an error if that functionality has been disabled.
                var disableSecurityGroups = GetAttributeValue(action, AttributeKey.DisableSecurityGroups).AsBooleanOrNull() ?? false;
                if (group.IsSecurityRoleOrSecurityGroupType() && disableSecurityGroups)
                {
                    errorMessages.Add($"\"{group.Name}\" is a Security group. The settings for this workflow action do not allow it to add a person to a security group.");
                }

                // If LimitToGroupsOfType has any values check if this Group's GroupType is in that list
                var limitToGroupsOfTypeGuid = GetAttributeValue(action, AttributeKey.LimitToGroupsOfType).AsGuidOrNull();
                if (limitToGroupsOfTypeGuid.HasValue)
                {
                    var limitToGroupType    = GroupTypeCache.Get(limitToGroupsOfTypeGuid.Value);
                    var limitToGroupTypeIds = new GroupTypeService(rockContext).GetChildGroupTypes(limitToGroupType.Id).Select(a => a.Id).ToList();
                    limitToGroupTypeIds.Add(limitToGroupType.Id);

                    if (!limitToGroupTypeIds.Contains(group.GroupTypeId))
                    {
                        errorMessages.Add($"The group type for group \"{group.Name} is \"{group.GroupType.Name}\". This action is configured to only add persons to groups of type \"{limitToGroupType.Name}\" and its child types.");
                    }
                }

                // If LimitToGroupsUnderSpecificParentGroup has any values check if this Group is a child of that group
                var limitToChildGroupsOfGroupGuid = GetAttributeValue(action, AttributeKey.LimitToGroupsUnderSpecificParentGroup).AsGuidOrNull();
                if (limitToChildGroupsOfGroupGuid.HasValue)
                {
                    var groupService = new GroupService(rockContext);
                    var limitToChildGroupsOfGroup = groupService.Get(limitToChildGroupsOfGroupGuid.Value);
                    var limitToGroupIds           = groupService.GetAllDescendentGroupIds(limitToChildGroupsOfGroup.Id, true);
                    limitToGroupIds.Add(limitToChildGroupsOfGroup.Id);

                    if (!limitToGroupIds.Contains(group.Id))
                    {
                        errorMessages.Add($"Cannot add the person to group \"{group.Name}\". This workflow action is configured to only add persons to groups that are a descendant of Group {limitToChildGroupsOfGroup.Name}.");
                    }
                }
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("Provided group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, AttributeKey.PersonKey).AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var  groupMemberService = new GroupMemberService(rockContext);
                var  groupMember        = groupMemberService.GetByGroupIdAndPersonIdAndPreferredGroupRoleId(group.Id, person.Id, groupRoleId.Value);
                bool isNew = false;
                if (groupMember == null)
                {
                    groupMember          = new GroupMember();
                    groupMember.PersonId = person.Id;
                    groupMember.GroupId  = group.Id;
                    isNew = true;
                }
                else
                {
                    action.AddLogEntry($"{person.FullName} was already a member of the selected group.", true);
                }

                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                if (groupMember.IsValidGroupMember(rockContext))
                {
                    if (isNew)
                    {
                        groupMemberService.Add(groupMember);
                    }

                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Beispiel #59
0
        /// <summary>
        /// Gets either a delimited string of email addresses or a list of recipients from an attribute value.
        /// </summary>
        /// <param name="recipientType">The recipient type.</param>
        /// <param name="attributeValue">The attribute value.</param>
        /// <param name="action">The action.</param>
        /// <param name="mergeFields">The merge fields.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="delimitedEmails">The delimited emails.</param>
        /// <param name="recipientList">The recipient list.</param>
        /// <returns></returns>
        private bool GetEmailsFromAttributeValue(RecipientType recipientType, string attributeValue, WorkflowAction action, Dictionary <string, object> mergeFields, RockContext rockContext, out string delimitedEmails, out List <RockEmailMessageRecipient> recipientList)
        {
            delimitedEmails = null;
            recipientList   = null;

            Guid?guid = attributeValue.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Get(guid.Value, rockContext);
                if (attribute != null)
                {
                    var recipientTypePrefix   = string.Empty;
                    var groupRoleAttributeKey = AttributeKey.GroupRole;
                    switch (recipientType)
                    {
                    case RecipientType.CC:
                        recipientTypePrefix = "CC ";
                        break;

                    case RecipientType.BCC:
                        recipientTypePrefix = "BCC ";
                        break;
                    }

                    string toValue = action.GetWorkflowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.EmailFieldType":
                        {
                            delimitedEmails = toValue;
                            return(true);
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry($"Invalid {recipientTypePrefix}Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!person.IsEmailActive)
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields)
                                    {
                                        { "Person", person }
                                    };

                                    recipientList = new List <RockEmailMessageRecipient> {
                                        new RockEmailMessageRecipient(person, personDict)
                                    };
                                    return(true);
                                }
                            }

                            return(false);
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toValue.AsIntegerOrNull();
                            Guid?groupGuid = toValue.AsGuidOrNull();

                            /*
                             * 2020-03-25 - JPH
                             *
                             * Per Jon, even though the user may select a Group or Security Role Attribute for the CC and BCC
                             * Attributes, we only want to allow Group Role filtering for the 'Send To Email Addresses' Attribute.
                             * Otherwise, the UI starts to become too overwhelming for the end user making the selections.
                             */
                            Guid?groupRoleValueGuid = recipientType == RecipientType.SendTo ?
                                                      GetGroupRoleValueGuid(action, groupRoleAttributeKey) :
                                                      null;

                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }
                            else if (groupGuid.HasValue)
                            {
                                // Handle situations where the attribute value stored is the Guid
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry($"Invalid {recipientTypePrefix}Recipient: No valid group id or Guid", true);
                            }

                            if (groupRoleValueGuid.HasValue)
                            {
                                qry = qry.Where(m => m.GroupRole != null && m.GroupRole.Guid.Equals(groupRoleValueGuid.Value));
                            }

                            if (qry != null)
                            {
                                recipientList = new List <RockEmailMessageRecipient>();
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    if (person.IsEmailActive &&
                                        person.EmailPreference != EmailPreference.DoNotEmail &&
                                        !string.IsNullOrWhiteSpace(person.Email))
                                    {
                                        var personDict = new Dictionary <string, object>(mergeFields)
                                        {
                                            { "Person", person }
                                        };

                                        recipientList.Add(new RockEmailMessageRecipient(person, personDict));
                                    }
                                }

                                return(true);
                            }

                            return(false);
                        }
                        }
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(attributeValue))
            {
                delimitedEmails = attributeValue;
                return(true);
            }

            return(false);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            StringBuilder sbErrorMessages = new StringBuilder();

            if (!action.IsNotNull())
            {
                action.AddLogEntry("ReferenceValidation: Input (action) is null.");
                return(false);
            }

            int    refCount    = action.Activity.Workflow.GetAttributeValue("ReferenceCount").AsInteger();
            int    maxRef      = action.Activity.Workflow.GetAttributeValue("ReferenceLimit").AsInteger();
            string firstName   = action.Activity.GetAttributeValue("Firstname");
            string lastName    = action.Activity.GetAttributeValue("Lastname");
            string phoneNumber = action.Activity.GetAttributeValue("Phone");
            string phoneType   = action.Activity.GetAttributeValue("PhoneType");
            string email       = action.Activity.GetAttributeValue("Email");
            Guid?  addressGuid = action.Activity.GetAttributeValue("Address").AsGuidOrNull();

            if (refCount < maxRef)
            {
                validateName(firstName, lastName, sbErrorMessages);
                validatePhone(phoneNumber, phoneType, sbErrorMessages);
                validateEmail(email, sbErrorMessages);
                validateRelationships(action, refCount, maxRef, sbErrorMessages);

                LocationService locationService = new LocationService(new RockContext());
                Location        location        = locationService.Get(addressGuid.Value);
                if (addressGuid.HasValue && addressGuid != new Guid())
                {
                    validateAddress(location, sbErrorMessages);
                }
                else
                {
                    sbErrorMessages.AppendLine("<li> A valid address is required.</li>");
                }

                if (sbErrorMessages.Length == 0)
                {
                    ContactInfo userInfo = new ContactInfo();
                    userInfo.name        = formatName(firstName, lastName);
                    userInfo.address     = formatAddress(location);
                    userInfo.phoneNumber = formatPhone(phoneNumber);
                    userInfo.email       = email.Trim();

                    //if this is the 1st successful entry,
                    //store in the list for future comparison.
                    if (refCount == 0)
                    {
                        Reference.Clear();
                        Reference.Add(userInfo);
                    }
                    else if (refCount > 0 && refCount < maxRef)
                    {
                        for (var i = 0; i < Reference.Count; i++)
                        {
                            string fieldCorrectionStr = "";
                            if (checkForDuplicates(Reference[i], userInfo, out fieldCorrectionStr))
                            {
                                if (!String.IsNullOrEmpty(fieldCorrectionStr))
                                {
                                    string[] words = fieldCorrectionStr.Trim().Split(' ');
                                    foreach (var word in words)
                                    {
                                        sbErrorMessages.AppendFormat("<li>This reference's {0} matches that of reference {1}, Please correct.</li>", word.Trim(), i + 1);
                                    }
                                }
                                else
                                {
                                    action.AddLogEntry("ReferenceValidation: CheckForDuplicates returns true, but correction string is empty.");
                                }
                            }
                        }
                        if (sbErrorMessages.Length == 0)
                        {
                            Reference.Add(userInfo);
                        }
                    }
                }
            }
            Guid ErMsg = GetActionAttributeValue(action, "ErrorMessages").AsGuid();

            if (sbErrorMessages.Length > 0)
            {
                // If we get here, validation has failed
                SetWorkflowAttributeValue(action, ErMsg, sbErrorMessages.ToString());
                action.AddLogEntry("ReferenceValidation: Validation failed");
                return(reactivateCurrentActions(rockContext, action));
            }
            // If we get here, validation was successful
            SetWorkflowAttributeValue(action, ErMsg, string.Empty);
            action.AddLogEntry("ReferenceValidation: Validation successful");
            return(true);
        }