/// <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 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;
        }
        /// <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;
        }
        /// <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;
        }
Example #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>();

            if ( action != null && action.Activity != null &&
                action.Activity.Workflow != null && action.Activity.Workflow.Id > 0 )
            {
                var text = GetAttributeValue( action, "Note" ).ResolveMergeFields( GetMergeFields( action ) );

                var note = new Note();
                note.IsSystem = false;
                note.IsAlert = GetAttributeValue( action, "IsAlert" ).AsBoolean();
                note.EntityId = action.Activity.Workflow.Id;
                note.Caption = string.Empty;
                note.Text = text;

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

                new NoteService( rockContext ).Add( note );

                return true;
            }
            else
            {
                errorMessages.Add( "A Note can only be added to a persisted workflow with a valid ID." );
                return false;
            }
        }
Example #6
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;
        }
Example #7
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>();

            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;
        }
Example #9
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 )
                {
                    var personAttribute = AttributeCache.Read( GetAttributeValue( action, "PersonAttribute" ).AsGuid() );
                    var ssnAttribute = AttributeCache.Read( GetAttributeValue( action, "SSNAttribute" ).AsGuid() );
                    var requestTypeAttribute = AttributeCache.Read( GetAttributeValue( action, "RequestTypeAttribute" ).AsGuid() );
                    var billingCodeAttribute = AttributeCache.Read( GetAttributeValue( action, "BillingCodeAttribute" ).AsGuid() );

                    return provider.SendRequest( rockContext, action.Activity.Workflow, personAttribute,
                        ssnAttribute, requestTypeAttribute, billingCodeAttribute, out errorMessages );
                }
                else
                {
                    errorMessages.Add( "Invalid Background Check Provider!" );
                }
            }
            else
            {
                errorMessages.Add( "Invalid Background Check Provider Guid!" );
            }

            return false;
        }
Example #10
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 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;
        }
Example #13
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 message = GetAttributeValue( action, "Message" ).ResolveMergeFields( GetMergeFields( action ) );
     errorMessages.Add( message );
     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 ( action.Activity.Workflow.InitiatorPersonAliasId.HasValue )
            {
                var personAlias = new PersonAliasService( rockContext ).Get( action.Activity.Workflow.InitiatorPersonAliasId.Value );
                if ( personAlias != null )
                {
                    // Get the attribute to set
                    Guid guid = GetAttributeValue( action, "PersonAttribute" ).AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        var personAttribute = AttributeCache.Read( guid, rockContext );
                        if ( personAttribute != null )
                        {
                            // If this is a person type attribute
                            if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id )
                            {
                                SetWorkflowAttributeValue( action, guid, personAlias.Guid.ToString() );
                            }
                            else if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.TEXT.AsGuid(), rockContext ).Id )
                            {
                                SetWorkflowAttributeValue( action, guid, personAlias.Person.FullName );
                            }
                        }
                    }
                }
            }

            return true;
        }
Example #15
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;
        }
        /// <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;
            }*/
        }
Example #17
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages)
        {
            errorMessages = new List<string>();

            EntityTypeCache cachedEntityType = EntityTypeCache.Read(GetAttributeValue(action, "EntityType").AsGuid());
            var propertyValues = GetAttributeValue(action, "EntityProperties").Replace(" ! ", " | ").ResolveMergeFields(GetMergeFields(action)).TrimEnd('|').Split('|').Select(p => p.Split('^')).Select(p => new { Name = p[0], Value = p[1] });

            if (cachedEntityType != null)
            {
                Type entityType = cachedEntityType.GetEntityType();
                IEntity newEntity = (IEntity)Activator.CreateInstance(entityType);

                foreach (var prop in propertyValues)
                {
                    PropertyInfo propInf = entityType.GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
                    if (null != propInf && propInf.CanWrite)
                    {
                        if (!(GetAttributeValue(action, "EmptyValueHandling") == "IGNORE" && String.IsNullOrWhiteSpace(prop.Value)))
                        {
                            try
                            {
                                propInf.SetValue(newEntity, ObjectConverter.ConvertObject(prop.Value, propInf.PropertyType, GetAttributeValue(action, "EmptyValueHandling") == "NULL"), null);
                            }
                            catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException)
                            {
                                errorMessages.Add("Invalid Property Value: " + prop.Name + ": " + ex.Message);
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Property: " + prop.Name);
                    }
                }

                rockContext.Set(entityType).Add(newEntity);
                rockContext.SaveChanges();

                // If request attribute was specified, requery the request and set the attribute's value
                Guid? entityAttributeGuid = GetAttributeValue(action, "EntityAttribute").AsGuidOrNull();
                if (entityAttributeGuid.HasValue)
                {
                    newEntity = (IEntity)rockContext.Set(entityType).Find(new object[] { newEntity.Id });
                    if (newEntity != null)
                    {
                        SetWorkflowAttributeValue(action, entityAttributeGuid.Value, newEntity.Guid.ToString());
                    }
                }

                return true;

            }
            else
            {
                errorMessages.Add("Invalid Entity Type");
            }
            return false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateWorkflow" /> class.
        /// </summary>
        /// <param name="startAction">The start action.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="startAction" /> is <see langword="null" />.
        /// </exception>
        public DelegateWorkflow(WorkflowAction startAction)
        {
            if (startAction == null)
            {
                throw new ArgumentNullException("startAction");
            }

            _START_ACTION = startAction;
        }
Example #19
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.Status = "DeleteWorkflowNow";

            // return false to stop further processing
            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 connection request
            ConnectionRequest request = null;
            Guid connectionRequestGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionRequestAttribute" ).AsGuid() ).AsGuid();
            request = new ConnectionRequestService( rockContext ).Get( connectionRequestGuid );
            if ( request == null )
            {
                errorMessages.Add( "Invalid Connection Request Attribute or Value!" );
                return false;
            }

            // Get connection state
            ConnectionState? connectionState = null;
            Guid? connectionStateAttributeGuid = GetAttributeValue( action, "ConnectionStateAttribute" ).AsGuidOrNull();
            if ( connectionStateAttributeGuid.HasValue )
            {
                connectionState = action.GetWorklowAttributeValue( connectionStateAttributeGuid.Value ).ConvertToEnumOrNull<ConnectionState>();
            }
            if ( connectionState == null )
            {
                connectionState = GetAttributeValue( action, "ConnectionState" ).ConvertToEnumOrNull<ConnectionState>();
            }
            if ( connectionState == null )
            {
                errorMessages.Add( "Invalid Connection State Attribute or Value!" );
                return false;
            }
            request.ConnectionState = connectionState.Value;

            // Get follow up date
            if ( connectionState.Value == ConnectionState.FutureFollowUp )
            {
                DateTime? followupDate = null;
                Guid? FollowUpDateAttributeGuid = GetAttributeValue( action, "FollowUpDateAttribute" ).AsGuidOrNull();
                if ( FollowUpDateAttributeGuid.HasValue )
                {
                    followupDate = action.GetWorklowAttributeValue( FollowUpDateAttributeGuid.Value ).AsDateTime();
                }
                if ( followupDate == null )
                {
                    followupDate = GetAttributeValue( action, "FollowUpDate" ).AsDateTime();
                }
                if ( followupDate == null )
                {
                    errorMessages.Add( "Invalid Follow Up DateAttribute or Value!" );
                    return false;
                }
                request.FollowupDate = followupDate.Value;
            }

            rockContext.SaveChanges();

            return true;
        }
Example #21
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;
        }
Example #22
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;
        }
Example #23
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 message = GetAttributeValue( action, "Message" ).ResolveMergeFields( GetMergeFields( action ) );

            action.Activity.Workflow.AddLogEntry( message, true );

            return true;
        }
Example #24
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;
        }
Example #25
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages)
        {
            errorMessages = new List<string>();

            Guid workflowAttributeGuid = GetAttributeValue(action, "Entity").AsGuid();
            Guid entityGuid = action.GetWorklowAttributeValue(workflowAttributeGuid).AsGuid();

            if (!entityGuid.IsEmpty())
            {
                IEntity entityObject = null;
                EntityTypeCache cachedEntityType = EntityTypeCache.Read(GetAttributeValue(action, "EntityType").AsGuid());

                if (cachedEntityType != null)
                {
                    Type entityType = cachedEntityType.GetEntityType();
                    entityObject = rockContext.Set<IEntity>().AsQueryable().Where(e => e.Guid == entityGuid).FirstOrDefault();
                }
                else {
                    var field = AttributeCache.Read(workflowAttributeGuid).FieldType.Field;
                    entityObject = ((Rock.Field.IEntityFieldType)field).GetEntity(entityGuid.ToString(), rockContext);
                }

                var propertyValues = GetAttributeValue(action, "EntityProperties").Replace(" ! ", " | ").ResolveMergeFields(GetMergeFields(action)).TrimEnd('|').Split('|').Select(p => p.Split('^')).Select(p => new { Name = p[0], Value = p[1] });

                foreach (var prop in propertyValues)
                {
                    PropertyInfo propInf = entityObject.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
                    if (null != propInf && propInf.CanWrite)
                    {
                        if (!(GetAttributeValue(action, "EmptyValueHandling") == "IGNORE" && String.IsNullOrWhiteSpace(prop.Value)))
                        {
                            try
                            {
                                propInf.SetValue(entityObject, ObjectConverter.ConvertObject(prop.Value, propInf.PropertyType, GetAttributeValue(action, "EmptyValueHandling") == "NULL"), null);
                            }
                            catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException)
                            {
                                errorMessages.Add("Invalid Property Value: " + prop.Name + ": " + ex.Message);
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Property: " + prop.Name);
                    }
                }

                rockContext.SaveChanges();
                return true;
            }
            else {
                errorMessages.Add("Invalid Entity Attribute");
            }
            return false;
        }
Example #26
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;
        }
Example #27
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;
                }
            }
        }
Example #28
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;
        }
Example #29
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;
        }
Example #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>();

            Guid guid = GetAttributeValue( action, "Attribute" ).AsGuid();
            if ( !guid.IsEmpty() )
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    if ( entity != null )
                    {
                        if ( entity is Person && attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id )
                        {
                            var person = entity as Person;

                            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( "Could not determine person primary alias!" );
                            }
                        }
                        else if ( entity is Group && attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.GROUP.AsGuid(), rockContext ).Id )
                        {
                            var group = entity as Group;
                            SetWorkflowAttributeValue( action, guid, group.Id.ToString() );
                            return true;
                        }
                        else
                        {
                            errorMessages.Add( "The attribute is not the correct type for the entity!" );
                        }
                    }
                }
                else
                {
                    errorMessages.Add( "Invalid attribute!" );
                }
            }
            else
            {
                errorMessages.Add( "Invalid attribute!" );
            }

            errorMessages.ForEach( m => action.AddLogEntry( m, 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>();

            Guid?  groupGuid      = null;
            Person person         = null;
            string attributeValue = string.Empty;
            Guid   groupRoleGuid  = Guid.Empty;
            string attributeKey   = string.Empty;

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

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

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

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

            Guid guid = personAttribute.AsGuid();

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

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get group member attribute value
            attributeValue = GetAttributeValue(action, "AttributeValue");
            guid           = attributeValue.AsGuid();
            if (guid.IsEmpty())
            {
                attributeValue = attributeValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

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

            // get optional role filter
            groupRoleGuid = GetAttributeValue(action, "GroupRoleFilter").AsGuid();

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

            // set attribute
            if (groupGuid.HasValue && person != null)
            {
                var qry = new GroupMemberService(rockContext).Queryable()
                          .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id);

                if (groupRoleGuid != Guid.Empty)
                {
                    qry = qry.Where(m => m.GroupRole.Guid == groupRoleGuid);
                }

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

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

            return(true);
        }
Example #32
0
 /// <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 abstract Boolean Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages);
Example #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>();

            // 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 (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.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()));
            }

            // Remove Person from Group
            if (!errorMessages.Any())
            {
                try {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMembers       = groupMemberService.Queryable().Where(m => m.PersonId == person.Id && m.GroupId == group.Id);

                    if (groupRoleId.HasValue)
                    {
                        groupMembers = groupMembers.Where(m => m.GroupRoleId == groupRoleId.Value);
                    }

                    foreach (var groupMember in groupMembers)
                    {
                        groupMemberService.Delete(groupMember);
                    }

                    rockContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    errorMessages.Add(string.Format("An error occurred while removing the group member: {0}", ex.Message));
                }
            }

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

            return(true);
        }
Example #34
0
        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.HasValue ? addressGuid.Value : Guid.NewGuid());
                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);
        }
Example #35
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, PERSON_ATTRIBUTE_KEY).AsGuid(), rockContext);

            if (attribute != null)
            {
                var    mergeFields  = GetMergeFields(action);
                string firstName    = GetAttributeValue(action, FIRST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string lastName     = GetAttributeValue(action, LAST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string email        = GetAttributeValue(action, EMAIL_KEY, true).ResolveMergeFields(mergeFields);
                string mobileNumber = GetAttributeValue(action, MOBILE_NUMBER_KEY, true).ResolveMergeFields(mergeFields) ?? string.Empty;

                int?birthDay   = GetAttributeValue(action, BIRTH_DAY_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthMonth = GetAttributeValue(action, BIRTH_MONTH_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthYear  = GetAttributeValue(action, BIRTH_YEAR_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) && string.IsNullOrWhiteSpace(mobileNumber)))
                {
                    errorMessages.Add("First Name, Last Name, and either Email or Mobile Number are required. One or more of these values was not provided!");
                }
                else
                {
                    Person      person        = null;
                    PersonAlias personAlias   = null;
                    var         personService = new PersonService(rockContext);

                    var personQuery = new PersonService.PersonMatchQuery(firstName, lastName, email, mobileNumber, null, birthMonth, birthDay, birthYear);
                    person = personService.FindPerson(personQuery, true);

                    if (person.IsNotNull())
                    {
                        personAlias = person.PrimaryAlias;
                    }
                    else
                    {
                        // Add New Person
                        person                   = new Person();
                        person.FirstName         = firstName.FixCase();
                        person.LastName          = lastName.FixCase();
                        person.IsEmailActive     = true;
                        person.Email             = email;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        person.BirthMonth        = birthMonth;
                        person.BirthDay          = birthDay;
                        person.BirthYear         = birthYear;

                        UpdatePhoneNumber(person, mobileNumber);

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

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

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, DEFAULT_CAMPUS_KEY, true).AsGuid());
                        var familyGroup   = PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus.Id : ( int? )null), false);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            person      = familyGroup.Members.Select(m => m.Person).First();
                            personAlias = person.PrimaryAlias;
                        }
                    }



                    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
                    {
                        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));
                return(false);
            }

            return(true);
        }
Example #36
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)
                    {
                        errorMessages.Add("No valid background check exists for this workflow");
                        return(false);
                    }
                    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);
        }
Example #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 <RockPushMessageRecipient>();

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

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorkflowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var           personAlias = new PersonAliasService(rockContext).Get(personAliasGuid);
                                List <string> devices     = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(a => a.PersonAliasId.HasValue && a.PersonAliasId == personAlias.Id && a.IsActive && a.NotificationsEnabled)
                                                            .Select(a => a.DeviceRegistrationId)
                                                            .ToList();

                                string deviceIds = String.Join(",", devices);

                                if (devices.Count == 0)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person does not have devices that support notifications", true);
                                }
                                else
                                {
                                    var person    = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    var recipient = new RockPushMessageRecipient(person, deviceIds, mergeFields);
                                    recipients.Add(recipient);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, 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))
                                {
                                    List <string> devices = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(p => p.PersonAliasId.HasValue && p.PersonAliasId == person.PrimaryAliasId && p.IsActive && p.NotificationsEnabled && !string.IsNullOrEmpty(p.DeviceRegistrationId))
                                                            .Select(p => p.DeviceRegistrationId)
                                                            .ToList();

                                    string deviceIds = String.Join(",", devices);

                                    if (deviceIds.IsNotNullOrWhiteSpace())
                                    {
                                        var recipient = new RockPushMessageRecipient(person, deviceIds, mergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockPushMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

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

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

            string title     = GetAttributeValue(action, "Title");
            Guid   titleGuid = title.AsGuid();

            if (!titleGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(titleGuid, rockContext);
                if (attribute != null)
                {
                    string titleAttributeValue = action.GetWorkflowAttributeValue(titleGuid);
                    if (!string.IsNullOrWhiteSpace(titleAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            title = titleAttributeValue;
                        }
                    }
                }
            }

            string sound     = GetAttributeValue(action, "Sound");
            Guid   soundGuid = sound.AsGuid();

            if (!soundGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(soundGuid, rockContext);
                if (attribute != null)
                {
                    string soundAttributeValue = action.GetWorkflowAttributeValue(soundGuid);
                    if (!string.IsNullOrWhiteSpace(soundAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.BooleanFieldType")
                        {
                            sound = soundAttributeValue;
                        }
                    }
                }
            }
            sound = sound.AsBoolean() ? "default" : "";

            string url     = GetAttributeValue(action, "Url");
            Guid   urlGuid = url.AsGuid();

            if (!urlGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(urlGuid, rockContext);
                if (attribute != null)
                {
                    string urlAttributeValue = action.GetWorkflowAttributeValue(urlGuid);
                    if (!string.IsNullOrWhiteSpace(urlAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            url = urlAttributeValue;
                        }
                    }
                }
            }

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var pushMessage = new RockPushMessage();
                pushMessage.SetRecipients(recipients);
                pushMessage.Title      = title;
                pushMessage.Message    = message;
                pushMessage.Sound      = sound;
                pushMessage.OpenAction = url.IsNotNullOrWhiteSpace() ? Utility.PushOpenAction.LinkToUrl : Utility.PushOpenAction.NoAction;
                pushMessage.Data       = new PushData
                {
                    Url = url
                };

                // Check if the URL is a mobile app style URL, which is "<guid>[?key=value]".
                if (url.Length >= 36 && Guid.TryParse(url.Substring(0, 36), out var pageGuid))
                {
                    var pageId = PageCache.Get(pageGuid)?.Id;

                    if (pageId.HasValue)
                    {
                        pushMessage.Data.MobilePageId = pageId.Value;

                        // Check if there are any query string values.
                        if (url.Length >= 38 && url[36] == '?')
                        {
                            var queryString = url.Substring(37).ParseQueryString();

                            pushMessage.Data.MobilePageQueryString = new Dictionary <string, string>();

                            foreach (string key in queryString.Keys)
                            {
                                pushMessage.Data.MobilePageQueryString.AddOrReplace(key, queryString[key].ToString());
                            }
                        }

                        pushMessage.OpenAction = Utility.PushOpenAction.LinkToMobilePage;
                    }
                }

                pushMessage.Send(out errorMessages);
            }

            return(true);
        }
Example #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>();

            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);
        }
Example #39
0
 /// <summary>
 /// Gets the attribute value for the action
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 protected string GetAttributeValue(WorkflowAction action, string key)
 {
     return(GetAttributeValue(action, key, false));
 }
 public WorkflowToReturnCustomAction(WorkflowAction workflowAction)
 {
     _workflowAction = workflowAction;
 }
Example #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>();

            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.Get(selectPersonGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        // If this is a person type attribute
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, selectedGroupMember.PrimaryAliasGuid.ToString());
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(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);
        }
Example #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>();

            Guid?    groupGuid          = null;
            Person   person             = null;
            DateTime attendanceDateTime = DateTime.Now;
            bool     addToGroup         = true;

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

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

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

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

            Guid guid = personAttribute.AsGuid();

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

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get attendance date
            Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid();

            if (!dateTimeAttributeGuid.IsEmpty())
            {
                string attributeDatetime = action.GetWorklowAttributeValue(dateTimeAttributeGuid);

                if (!string.IsNullOrWhiteSpace(attributeDatetime))
                {
                    if (!DateTime.TryParse(attributeDatetime, out attendanceDateTime))
                    {
                        errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime));
                    }
                }
            }

            // get add to group
            addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean();

            // get location
            Guid locationGuid          = Guid.Empty;
            Guid locationAttributeGuid = GetAttributeValue(action, "Location").AsGuid();

            if (!locationAttributeGuid.IsEmpty())
            {
                var locationAttribute = AttributeCache.Read(locationAttributeGuid, rockContext);

                if (locationAttribute != null)
                {
                    locationGuid = action.GetWorklowAttributeValue(locationAttributeGuid).AsGuid();
                }
            }

            //// get Schedule
            Guid scheduleGuid          = Guid.Empty;
            Guid scheduleAttributeGuid = GetAttributeValue(action, "Schedule").AsGuid();

            if (!scheduleAttributeGuid.IsEmpty())
            {
                var scheduleAttribute = AttributeCache.Read(scheduleAttributeGuid, rockContext);
                if (scheduleAttribute != null)
                {
                    scheduleGuid = action.GetWorklowAttributeValue(scheduleAttributeGuid).AsGuid();
                }
            }

            // set attribute
            if (groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue)
            {
                var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole")
                            .Where(g => g.Guid == groupGuid)
                            .FirstOrDefault();
                if (group != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                    // get group member
                    var groupMember = groupMemberService.Queryable()
                                      .Where(m => m.Group.Guid == groupGuid &&
                                             m.PersonId == person.Id)
                                      .FirstOrDefault();
                    if (groupMember == null)
                    {
                        if (addToGroup)
                        {
                            if (group != null)
                            {
                                groupMember                   = new GroupMember();
                                groupMember.GroupId           = group.Id;
                                groupMember.PersonId          = person.Id;
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMember.GroupRole         = group.GroupType.DefaultGroupRole;
                                groupMemberService.Add(groupMember);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name));
                            return(true);
                        }
                    }

                    AttendanceService attendanceService = new AttendanceService(rockContext);

                    Attendance attendance = new Attendance();
                    attendance.GroupId       = group.Id;
                    attendance.PersonAliasId = person.PrimaryAliasId;
                    attendance.StartDateTime = attendanceDateTime;
                    attendance.DidAttend     = true;

                    if (locationGuid != Guid.Empty)
                    {
                        var location = new LocationService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == locationGuid)
                                       .FirstOrDefault();

                        if (location != null)
                        {
                            attendance.LocationId = location.Id;
                        }
                    }

                    attendanceService.Add(attendance);
                    rockContext.SaveChanges();

                    if (attendance.LocationId.HasValue)
                    {
                        Rock.CheckIn.KioskLocationAttendance.Flush(attendance.LocationId.Value);
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid));
                }
            }

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

            return(true);
        }
Example #43
0
 /// <summary>
 /// Logs the messages for exit.
 /// </summary>
 /// <param name="action"></param>
 /// <param name="errorMessages">The error messages.</param>
 /// <returns></returns>
 private bool LogMessagesForExit(WorkflowAction action, List <string> errorMessages)
 {
     errorMessages.ForEach(m => action.AddLogEntry(m));
     return(!errorMessages.Any());
 }
Example #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>();
            var mergeFields = GetMergeFields(action);

            // Validate the person exists
            var personGuid = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();

            if (!personGuid.HasValue)
            {
                errorMessages.Add("The person guid is required but was missing");
                return(LogMessagesForExit(action, errorMessages));
            }

            var personService = new PersonService(rockContext);
            var person        = personService.Queryable("Aliases").AsNoTracking()
                                .FirstOrDefault(p => p.Guid == personGuid.Value || p.Aliases.Any(pa => pa.Guid == personGuid.Value));

            if (person == null)
            {
                errorMessages.Add($"The person with the guid '{personGuid.Value}' was not found");
                return(LogMessagesForExit(action, errorMessages));
            }

            if (!person.PrimaryAliasId.HasValue)
            {
                errorMessages.Add($"{person.FullName} does not have a primary alias identifier");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step type exists. Could be a step type id or a guid
            var stepType = GetStepType(rockContext, action, out var errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepType == null)
            {
                errorMessages.Add("The step type could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step status exists and is in the same program as the step type
            var stepStatus = GetStepStatus(stepType, action, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepStatus == null)
            {
                errorMessages.Add("The step status could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Get the start and end dates
            var startDate = GetLavaAttributeValue(action, AttributeKey.StartDate).AsDateTime() ?? RockDateTime.Now;
            var endDate   = GetLavaAttributeValue(action, AttributeKey.EndDate).AsDateTime();

            var campusAttributeValue = GetLavaAttributeValue(action, AttributeKey.Campus);
            var campusId             = campusAttributeValue.AsIntegerOrNull();
            var campusGuid           = campusAttributeValue.AsGuidOrNull();

            if (campusGuid != null)
            {
                var campus = CampusCache.Get(campusGuid.Value);
                if (campus != null)
                {
                    campusId = campus.Id;
                }
            }

            // The completed date is today or the end date if the status is a completed status
            var completedDate = stepStatus.IsCompleteStatus ? (endDate ?? RockDateTime.Now) : ( DateTime? )null;

            // Create the step object
            var step = new Step
            {
                StepTypeId        = stepType.Id,
                PersonAliasId     = person.PrimaryAliasId.Value,
                StartDateTime     = startDate,
                EndDateTime       = endDate,
                CompletedDateTime = completedDate,
                StepStatusId      = stepStatus.Id,
                CampusId          = campusId
            };

            // Validate the step
            if (!step.IsValid)
            {
                errorMessages.AddRange(step.ValidationResults.Select(a => a.ErrorMessage));
                return(LogMessagesForExit(action, errorMessages));
            }

            // Check if the step can be created because of Allow Multiple rules on the step type and also prerequisite requirements
            var stepService = new StepService(rockContext);
            var canAdd      = stepService.CanAdd(step, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
            }
            else if (!canAdd)
            {
                errorMessages.Add("Cannot add the step for an unspecified reason");
            }
            else
            {
                try
                {
                    stepService.Add(step);
                    rockContext.SaveChanges();

                    SetCreatedItemAttribute(action, AttributeKey.StepAttribute, step, rockContext);
                }
                catch (Exception exception)
                {
                    errorMessages.Add($"Exception thrown: {exception.Message}");
                    ExceptionLogService.LogException(exception);
                }
            }

            return(LogMessagesForExit(action, errorMessages));
        }
Example #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>();

            string attributeValue = GetAttributeValue(action, "PersonAttribute");
            Guid?  guid           = attributeValue.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Read(guid.Value, rockContext);
                if (attribute != null)
                {
                    string firstName = GetAttributeValue(action, "FirstName", true);
                    string lastName  = GetAttributeValue(action, "LastName", true);
                    string email     = GetAttributeValue(action, "Email", true);

                    if (string.IsNullOrWhiteSpace(firstName) ||
                        string.IsNullOrWhiteSpace(lastName) ||
                        string.IsNullOrWhiteSpace(email))
                    {
                        errorMessages.Add("First Name, Last Name, and Email are required. One or more of these values was not provided!");
                    }
                    else
                    {
                        Person      person        = null;
                        PersonAlias personAlias   = null;
                        var         personService = new PersonService(rockContext);
                        var         people        = personService.GetByMatch(firstName, lastName, email).ToList();
                        if (people.Count == 1)
                        {
                            person      = people.First();
                            personAlias = person.PrimaryAlias;
                        }
                        else
                        {
                            // Add New Person
                            person                   = new Person();
                            person.FirstName         = firstName;
                            person.LastName          = lastName;
                            person.IsEmailActive     = true;
                            person.Email             = email;
                            person.EmailPreference   = EmailPreference.EmailAllowed;
                            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

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

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

                            var defaultCampus = CampusCache.Read(GetAttributeValue(action, "DefaultCampus", true).AsGuid());
                            var familyGroup   = PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus.Id : (int?)null), false);
                            if (familyGroup != null && familyGroup.Members.Any())
                            {
                                person      = familyGroup.Members.Select(m => m.Person).First();
                                personAlias = person.PrimaryAlias;
                            }
                        }

                        if (person != null && personAlias != null)
                        {
                            action.Activity.Workflow.SetAttributeValue(attribute.Key, personAlias.Guid.ToString());
                            action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                            return(true);
                        }
                        else
                        {
                            errorMessages.Add("Person or Primary Alias could not be determined!");
                        }
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Person Attribute could not be found for selected attribute value ('{0}')!", guid.Value.ToString()));
                }
            }
            else
            {
                errorMessages.Add(string.Format("Selected Person Attribute value ('{0}') was not a valid Guid!", attributeValue));
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }

            return(true);
        }
Example #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 mergeFields = GetMergeFields(action);

            var registrationTemplateService         = new RegistrationTemplateService(rockContext);
            var registrationTemplateDiscountService = new RegistrationTemplateDiscountService(rockContext);

            var registrationTemplate = registrationTemplateService.Get(GetAttributeValue(action, "RegistrationTemplate").ResolveMergeFields(mergeFields).AsGuid());

            if (registrationTemplate == null)
            {
                errorMessages.Add("Could not find selected registration template");
                return(false);
            }

            var length = GetAttributeValue(action, "DiscountCodeLength", true).ResolveMergeFields(mergeFields).AsInteger();

            if (length < 3)
            {
                length = 3;
            }

            string code = GetRandomCode(length);

            while (registrationTemplateDiscountService
                   .Queryable().AsNoTracking()
                   .Any(d =>
                        d.RegistrationTemplateId == registrationTemplate.Id &&
                        d.Code == code))
            {
                code = GetRandomCode(length);
            }

            var discountCode = new RegistrationTemplateDiscount();

            discountCode.Code = code;

            //Set discount value
            var     discountType   = GetAttributeValue(action, "DiscountType");
            decimal discountAmount = GetAttributeValue(action, "DiscountAmount", true).ResolveMergeFields(mergeFields).AsDecimal();

            if (discountType == "Percent")
            {
                discountCode.DiscountPercentage = discountAmount / 100;
            }
            if (discountType == "Amount")
            {
                discountCode.DiscountAmount = discountAmount;
            }

            var maximumUsage = GetAttributeValue(action, "MaximumUsage", true).ResolveMergeFields(mergeFields).AsInteger();

            if (maximumUsage > 0)
            {
                discountCode.MaxUsage = maximumUsage;
            }

            var maximumRegistrants = GetAttributeValue(action, "MaximumRegistrants", true).ResolveMergeFields(mergeFields).AsInteger();

            if (maximumRegistrants > 0)
            {
                discountCode.MaxRegistrants = maximumRegistrants;
            }

            var minimumRegistrants = GetAttributeValue(action, "MinimumRegistrants", true).ResolveMergeFields(mergeFields).AsInteger();

            if (minimumRegistrants < 0)
            {
                discountCode.MinRegistrants = minimumRegistrants;
            }

            var effectiveDates = GetAttributeValue(action, "EffectiveDates", true);

            if (!string.IsNullOrWhiteSpace(effectiveDates))
            {
                var dates = effectiveDates.Split(',');
                if (dates.Length > 1 &&
                    !string.IsNullOrWhiteSpace(dates[0]) &&
                    !string.IsNullOrWhiteSpace(dates[1]))
                {
                    discountCode.StartDate = dates[0].AsDateTime();
                    discountCode.EndDate   = dates[1].AsDateTime();
                }
            }

            registrationTemplate.Discounts.Add(discountCode);
            rockContext.SaveChanges();
            SetWorkflowAttributeValue(action, "DiscountCodeAttribute", code);
            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>();

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

            var guidGroupAttribute = GetAttributeValue(action, "Group").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");
            }

            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, "Person").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);
        }
Example #48
0
 private bool IsManuallyPositioned(WorkflowAction wfAction)
 {
     return(_menuSettings.Settings.MenuItems.Keys.Any(key => _menuSettings.Settings.MenuItems[key].ContainsKey(wfAction.ActionId)));
 }
Example #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 the entity type
            EntityTypeCache entityType     = null;
            var             entityTypeGuid = GetAttributeValue(action, "EntityType").AsGuidOrNull();

            if (entityTypeGuid.HasValue)
            {
                entityType = EntityTypeCache.Get(entityTypeGuid.Value);
            }
            if (entityType == null)
            {
                errorMessages.Add(string.Format("Entity Type could not be found for selected value ('{0}')!", entityTypeGuid.ToString()));
                return(false);
            }

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

            // Get the entity
            EntityTypeService entityTypeService  = new EntityTypeService(_rockContext);
            IEntity           entityObject       = null;
            string            entityIdGuidString = GetAttributeValue(action, "EntityIdGuid", true).ResolveMergeFields(mergeFields).Trim();
            var entityGuid = entityIdGuidString.AsGuidOrNull();

            if (entityGuid.HasValue)
            {
                entityObject = entityTypeService.GetEntity(entityType.Id, entityGuid.Value);
            }
            else
            {
                var entityId = entityIdGuidString.AsIntegerOrNull();
                if (entityId.HasValue)
                {
                    entityObject = entityTypeService.GetEntity(entityType.Id, entityId.Value);
                }
            }

            if (entityObject == null)
            {
                errorMessages.Add(string.Format("Entity could not be found for selected value ('{0}')!", entityIdGuidString));
                return(false);
            }

            // Get the property settings
            string propertyName       = GetAttributeValue(action, "PropertyName", true).ResolveMergeFields(mergeFields);
            string propertyValue      = GetAttributeValue(action, "PropertyValue", true).ResolveMergeFields(mergeFields);
            string emptyValueHandling = GetAttributeValue(action, "EmptyValueHandling");

            if (emptyValueHandling == "IGNORE" && String.IsNullOrWhiteSpace(propertyValue))
            {
                action.AddLogEntry("Skipping empty value.");
                return(true);
            }

            PropertyInfo propInf = entityObject.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);

            if (propInf == null)
            {
                errorMessages.Add(string.Format("Property does not exist ('{0}')!", propertyName));
                return(false);
            }

            if (!propInf.CanWrite)
            {
                errorMessages.Add(string.Format("Property is not writable ('{0}')!", entityIdGuidString));
                return(false);
            }

            try
            {
                propInf.SetValue(entityObject, ConvertObject(propertyValue, propInf.PropertyType, emptyValueHandling == "NULL"), null);
            }
            catch (Exception ex) when(ex is InvalidCastException || ex is FormatException || ex is OverflowException)
            {
                errorMessages.Add(string.Format("Could not convert property value ('{0}')! {1}", propertyValue, ex.Message));
                return(false);
            }

            if (!entityObject.IsValid)
            {
                errorMessages.Add(string.Format("Invalid property value ('{0}')! {1}", propertyValue, entityObject.ValidationResults.Select(r => r.ErrorMessage).ToList().AsDelimited(" ")));
                return(false);
            }

            try
            {
                _rockContext.SaveChanges();
            }
            catch (Exception ex)
            {
                errorMessages.Add(string.Format("Could not save value ('{0}')! {1}", propertyValue, ex.Message));
                return(false);
            }

            action.AddLogEntry(string.Format("Set '{0}' property to '{1}'.", propertyName, propertyValue));

            return(true);
        }
Example #50
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

            // Set the note type if this is first request
            if (!Page.IsPostBack)
            {
                var entityType = EntityTypeCache.Read(typeof(Rock.Model.Workflow));
                var noteTypes  = NoteTypeCache.GetByEntity(entityType.Id, string.Empty, string.Empty);
                ncWorkflowNotes.NoteTypes = noteTypes;
            }

            if (_workflowType == null)
            {
                ShowNotes(false);
                ShowMessage(NotificationBoxType.Danger, "Configuration Error", "Workflow type was not configured or specified correctly.");
                return(false);
            }

            if (!_workflowType.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                ShowNotes(false);
                ShowMessage(NotificationBoxType.Warning, "Sorry", "You are not authorized to view this type of workflow.");
                return(false);
            }

            // If operating against an existing workflow, get the workflow and load attributes
            if (!WorkflowId.HasValue)
            {
                WorkflowId = PageParameter("WorkflowId").AsIntegerOrNull();
                if (!WorkflowId.HasValue)
                {
                    Guid guid = PageParameter("WorkflowGuid").AsGuid();
                    if (!guid.IsEmpty())
                    {
                        _workflow = _workflowService.Queryable()
                                    .Where(w => w.Guid.Equals(guid) && w.WorkflowTypeId == _workflowType.Id)
                                    .FirstOrDefault();
                        if (_workflow != null)
                        {
                            WorkflowId = _workflow.Id;
                        }
                    }
                }
            }

            if (WorkflowId.HasValue)
            {
                if (_workflow == null)
                {
                    _workflow = _workflowService.Queryable()
                                .Where(w => w.Id == WorkflowId.Value && w.WorkflowTypeId == _workflowType.Id)
                                .FirstOrDefault();
                }
                if (_workflow != null)
                {
                    hlblWorkflowId.Text = _workflow.WorkflowId;

                    _workflow.LoadAttributes();
                    foreach (var activity in _workflow.Activities)
                    {
                        activity.LoadAttributes();
                    }
                }
            }

            // If an existing workflow was not specified, activate a new instance of workflow and start processing
            if (_workflow == null)
            {
                string workflowName = PageParameter("WorkflowName");
                if (string.IsNullOrWhiteSpace(workflowName))
                {
                    workflowName = "New " + _workflowType.WorkTerm;
                }

                _workflow = Rock.Model.Workflow.Activate(_workflowType, workflowName);
                if (_workflow != null)
                {
                    // If a PersonId or GroupId parameter was included, load the corresponding
                    // object and pass that to the actions for processing
                    object entity   = null;
                    int?   personId = PageParameter("PersonId").AsIntegerOrNull();
                    if (personId.HasValue)
                    {
                        entity = new PersonService(_rockContext).Get(personId.Value);
                    }
                    else
                    {
                        int?groupId = PageParameter("GroupId").AsIntegerOrNull();
                        if (groupId.HasValue)
                        {
                            entity = new GroupService(_rockContext).Get(groupId.Value);
                        }
                    }

                    // Loop through all the query string parameters and try to set any workflow
                    // attributes that might have the same key
                    foreach (string key in Request.QueryString.AllKeys)
                    {
                        _workflow.SetAttributeValue(key, Request.QueryString[key]);
                    }

                    List <string> errorMessages;
                    if (!_workflowService.Process(_workflow, entity, out errorMessages))
                    {
                        ShowNotes(false);
                        ShowMessage(NotificationBoxType.Danger, "Workflow Processing Error(s):",
                                    "<ul><li>" + errorMessages.AsDelimited("</li><li>") + "</li></ul>");
                        return(false);
                    }
                    if (_workflow.Id != 0)
                    {
                        WorkflowId = _workflow.Id;
                    }
                }
            }

            if (_workflow == null)
            {
                ShowNotes(false);
                ShowMessage(NotificationBoxType.Danger, "Workflow Activation Error", "Workflow could not be activated.");
                return(false);
            }

            if (_workflow.IsActive)
            {
                if (ActionTypeId.HasValue)
                {
                    foreach (var activity in _workflow.ActiveActivities)
                    {
                        _action = activity.Actions.Where(a => a.ActionTypeId == ActionTypeId.Value).FirstOrDefault();
                        if (_action != null)
                        {
                            _activity = activity;
                            _activity.LoadAttributes();

                            _actionType  = _action.ActionType;
                            ActionTypeId = _actionType.Id;
                            return(true);
                        }
                    }
                }

                var canEdit = UserCanEdit || _workflow.IsAuthorized(Authorization.EDIT, CurrentPerson);

                // Find first active action form
                int personId = CurrentPerson != null ? CurrentPerson.Id : 0;
                foreach (var activity in _workflow.Activities
                         .Where(a =>
                                a.IsActive &&
                                (
                                    (canEdit) ||
                                    (!a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue) ||
                                    (a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId) ||
                                    (a.AssignedGroup != null && a.AssignedGroup.Members.Any(m => m.PersonId == personId))
                                )
                                )
                         .OrderBy(a => a.ActivityType.Order))
                {
                    if (canEdit || (activity.ActivityType.IsAuthorized(Authorization.VIEW, CurrentPerson)))
                    {
                        foreach (var action in activity.ActiveActions)
                        {
                            if (action.ActionType.WorkflowForm != null && action.IsCriteriaValid)
                            {
                                _activity = activity;
                                _activity.LoadAttributes();

                                _action      = action;
                                _actionType  = _action.ActionType;
                                ActionTypeId = _actionType.Id;
                                return(true);
                            }
                        }
                    }
                }
            }

            ShowNotes(false);
            ShowMessage(NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information.");
            return(false);
        }
Example #51
0
        private Person GetPersonAliasFromActionAttribute(string key, RockContext rockContext, WorkflowAction action, List <string> errorMessages)
        {
            string value = GetAttributeValue(action, key);
            Guid   guidPersonAttribute = value.AsGuid();

            if (!guidPersonAttribute.IsEmpty())
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                                return(personAliasService.Queryable().AsNoTracking()
                                       .Where(a => a.Guid.Equals(personAliasGuid))
                                       .Select(a => a.Person)
                                       .FirstOrDefault());
                            }
                            else
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(null);
                            }
                        }
                        else
                        {
                            errorMessages.Add(string.Format("The attribute used for {0} to provide the person was not of type 'Person'.", key));
                            return(null);
                        }
                    }
                }
            }

            return(null);
        }
Example #52
0
        private void CompleteFormAction(string formAction)
        {
            if (!string.IsNullOrWhiteSpace(formAction) &&
                _workflow != null &&
                _actionType != null &&
                _actionType.WorkflowForm != null &&
                _activity != null &&
                _action != null)
            {
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("Action", _action);
                mergeFields.Add("Activity", _activity);
                mergeFields.Add("Workflow", _workflow);

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

                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>", null, true) + "</li></ul>");
                }
                if (_workflow.Id != 0)
                {
                    WorkflowId = _workflow.Id;
                }
            }
        }
 public void LogWorkflowAction(WorkflowAction workflowAction)
 {
 }
Example #54
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Check to see if the action's activity does not yet have the the 'InviteLink' attribute.x
            string signNowDocumentId = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "SignNowDocumentId").AsGuid());

            if (string.IsNullOrEmpty(signNowDocumentId))
            {
                errorMessages.Add("A sign now document is required to complete this action");
                return(false);
            }

            Guid documentGuid = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "Document").AsGuid()).AsGuid();


            PersonAliasService personAliasService = new PersonAliasService(rockContext);
            BinaryFileService  binaryfileService  = new BinaryFileService(rockContext);


            SignNow signNow        = new SignNow();
            string  snErrorMessage = "";
            string  token          = signNow.GetAccessToken(false, out snErrorMessage);

            if (!string.IsNullOrEmpty(snErrorMessage))
            {
                errorMessages.Add(snErrorMessage);
                return(false);
            }

            //Check if document is signed.
            JObject document = SignNowSDK.Document.Get(token, signNowDocumentId);

            if ((( JArray )document["signatures"]).Count() > 0)
            {
                // Download the file
                string tempPath     = Path.GetTempPath();
                string tempFileName = ( String )document["document_name"];
                var    result       = SignNowSDK.Document.Download(token, signNowDocumentId, tempPath, tempFileName);

                // Put it into the workflow attribute
                BinaryFile signedPDF = binaryfileService.Get(documentGuid);
                if (signedPDF == null)
                {
                    signedPDF = new BinaryFile();
                    // TODO: This probably shouldn't be hardcoded
                    signedPDF.MimeType    = "application/pdf";
                    signedPDF.FileName    = tempFileName;
                    signedPDF.IsTemporary = false;
                    binaryfileService.Add(signedPDF);

                    // Update the file type if necessary
                    Guid binaryFileTypeGuid = Guid.Empty;

                    var destinationAttribute    = AttributeCache.Get(GetActionAttributeValue(action, "Document").AsGuid(), rockContext);
                    var binaryFileTypeQualifier = destinationAttribute.QualifierValues["binaryFileType"];
                    if (!String.IsNullOrWhiteSpace(binaryFileTypeQualifier.Value))
                    {
                        if (binaryFileTypeQualifier.Value != null)
                        {
                            binaryFileTypeGuid = binaryFileTypeQualifier.Value.AsGuid();

                            signedPDF.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(binaryFileTypeGuid).Id;
                        }
                    }
                    signedPDF.ContentStream = new FileStream($"{tempPath}{tempFileName}.pdf", FileMode.Open);

                    rockContext.SaveChanges();

                    // Now store the attribute
                    if (destinationAttribute.EntityTypeId == new Workflow().TypeId)
                    {
                        action.Activity.Workflow.SetAttributeValue(destinationAttribute.Key, signedPDF.Guid.ToString());
                    }
                    else if (destinationAttribute.EntityTypeId == new WorkflowActivity().TypeId)
                    {
                        action.Activity.SetAttributeValue(destinationAttribute.Key, signedPDF.Guid.ToString());
                    }
                }
                else
                {
                    signedPDF.FileName      = tempFileName;
                    signedPDF.ContentStream = new FileStream($"{tempPath}{tempFileName}.pdf", FileMode.Open);
                }

                // Delete the file when we are done:
                File.Delete(tempPath + tempFileName);

                // We have a signed copy
                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "PDFSigned").AsGuid(), "True");
            }
            else
            {
                // Not signed yet.
                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "PDFSigned").AsGuid(), "False");
            }
            return(true);
        }
Example #55
0
 /// <summary>
 /// Loads the attributes for the action.  The attributes are loaded by the framework prior to executing the action,
 /// so typically workflow actions do not need to load the attributes
 /// </summary>
 /// <param name="action">The action.</param>
 public void LoadAttributes(WorkflowAction action)
 {
     action.ActionType.LoadAttributes();
 }
Example #56
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.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;
            }

            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.GetWorkflowAttributeValue(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);
            }
        }
 public WorkflowReturnCustomAction(WorkflowAction workflowAction)
 {
     ScheduleActivity(_activityName, _activityVersion).OnFailedCancellation(c => workflowAction);
 }
Example #58
0
        /// <summary>
        /// Gets the entity from the specified service using the guid directly from an Attribute or from a Workflow Attribute.
        /// </summary>
        /// <typeparam name="T">The type of entity to get.</typeparam>
        /// <param name="action">The workflow action to look at.</param>
        /// <param name="directAttributeKey">The key of the Attribute that points directly to the entity.</param>
        /// <param name="workflowAttributeKey">The key of the Attribute that points to a Workflow Attribute that points to the entity.</param>
        /// <param name="entityService">The service to use to get the entity.</param>
        /// <returns></returns>
        public T GetEntityFromWorkflowAttributes <T>(WorkflowAction action, string directAttributeKey, string workflowAttributeKey, Service <T> entityService) where T : Entity <T>, new()
        {
            Guid?entityAttributeGuid = GetAttributeValue(action, workflowAttributeKey).AsGuidOrNull();

            return(entityService.Get((entityAttributeGuid.HasValue ? action.GetWorkflowAttributeValue(entityAttributeGuid.Value).AsGuidOrNull() : null) ?? GetAttributeValue(action, directAttributeKey).AsGuid()));
        }
Example #59
0
            public WorkflowWithCustomAction(WorkflowAction workflowAction)
            {
                ScheduleLambda("lambda_name").OnFailure(e => workflowAction);

                ScheduleTimer("timer_name").AfterLambda("lambda_name");
            }
Example #60
0
        /// <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>();

            if (!action.LastProcessedDateTime.HasValue &&
                action.ActionType != null &&
                action.ActionType.WorkflowForm != null &&
                action.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)
                    {
                        var systemEmail = new SystemEmailService(rockContext).Get(action.ActionType.WorkflowForm.NotificationSystemEmailId.Value);
                        if (systemEmail != null)
                        {
                            var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot");
                            Email.Send(systemEmail.Guid, recipients, appRoot);
                        }
                        else
                        {
                            action.AddLogEntry("Could not find the selected notifiction system email!", true);
                        }
                    }
                    else
                    {
                        action.AddLogEntry("Could not send form notifiction due to no assigned person or group member not having email address!", true);
                    }
                }
                else
                {
                    action.AddLogEntry("Could not send form notifiction due to no assigned person or group!", true);
                }
            }

            return(false);
        }