Beispiel #1
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 have the the 'SignNowDocumentId' attribute.
            string signNowDocumentId = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "SignNowDocumentId").AsGuid());

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

            // Check to see if the document has been signed
            bool documentSignedFlag = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "PDFSigned").AsGuid()).AsBoolean();

            if (!documentSignedFlag)
            {
                // We can't move on until the document is signed.
                return(false);
            }

            // If we get this far, the document is signed and it's time to move on.
            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>();

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

            // Get the attribute's guid
            Guid guid = GetAttributeValue(action, "Attribute").AsGuid();

            if (!guid.IsEmpty())
            {
                // Get the attribute
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    if (attribute.FieldTypeId == FieldTypeCache.Get(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.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);
                            }
                        }
                    }

                    else if (attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.GROUP.AsGuid(), rockContext).Id)
                    {
                        // If attribute type is a group, value should be group guid
                        Guid?groupGuid = action.GetWorklowAttributeValue(guid).AsGuidOrNull();
                        if (groupGuid.HasValue)
                        {
                            var group = new GroupService(rockContext).Get(groupGuid.Value);
                            if (group != null)
                            {
                                action.Activity.AssignedPersonAlias   = null;
                                action.Activity.AssignedPersonAliasId = null;
                                action.Activity.AssignedGroup         = group;
                                action.Activity.AssignedGroupId       = group.Id;
                                action.AddLogEntry(string.Format("Assigned activity to '{0}' group ({1})", group.Name, group.Id));
                                return(true);
                            }
                        }
                    }
                }
            }

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

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

            // Get the connection request
            ConnectionRequest request     = null;
            Guid connectionRequestGuid    = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid();
            var  connectionRequestService = new ConnectionRequestService(rockContext);

            request = connectionRequestService.Get(connectionRequestGuid);
            if (request == null)
            {
                errorMessages.Add("Invalid Connection Request Attribute or Value!");
                return(false);
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid          = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionOpportunityAttribute").AsGuid()).AsGuid();

            opportunity = new ConnectionOpportunityService(rockContext).Get(opportunityTypeGuid);
            if (opportunity == null)
            {
                errorMessages.Add("Invalid Connection Opportunity Attribute or Value!");
                return(false);
            }

            // Get the transfer note
            string note = GetAttributeValue(action, "TransferNote", true);

            if (request != null && opportunity != null)
            {
                request.ConnectionOpportunityId = opportunity.Id;

                var guid = Rock.SystemGuid.ConnectionActivityType.TRANSFERRED.AsGuid();
                var transferredActivityId = new ConnectionActivityTypeService(rockContext)
                                            .Queryable()
                                            .Where(t => t.Guid == guid)
                                            .Select(t => t.Id)
                                            .FirstOrDefault();

                ConnectionRequestActivity connectionRequestActivity = new ConnectionRequestActivity();
                connectionRequestActivity.ConnectionRequestId      = request.Id;
                connectionRequestActivity.ConnectionOpportunityId  = opportunity.Id;
                connectionRequestActivity.ConnectionActivityTypeId = transferredActivityId;
                connectionRequestActivity.Note = note;
                new ConnectionRequestActivityService(rockContext).Add(connectionRequestActivity);

                rockContext.SaveChanges();
            }

            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>();

            // Get the connection request
            ConnectionRequest request = null;
            Guid connectionRequestGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionRequestAttribute" ).AsGuid() ).AsGuid();
            var connectionRequestService = new ConnectionRequestService( rockContext );
            request = connectionRequestService.Get( connectionRequestGuid );
            if ( request == null )
            {
                errorMessages.Add( "Invalid Connection Request Attribute or Value!" );
                return false;
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionOpportunityAttribute" ).AsGuid() ).AsGuid();
            opportunity = new ConnectionOpportunityService( rockContext ).Get( opportunityTypeGuid );
            if ( opportunity == null )
            {
                errorMessages.Add( "Invalid Connection Opportunity Attribute or Value!" );
                return false;
            }

            // Get the tranfer note
            string note = GetAttributeValue( action, "TransferNote", true );

            if ( request != null && opportunity != null )
            {
                request.ConnectionOpportunityId = opportunity.Id;

                var guid = Rock.SystemGuid.ConnectionActivityType.TRANSFERRED.AsGuid();
                var transferredActivityId = new ConnectionActivityTypeService( rockContext )
                    .Queryable()
                    .Where( t => t.Guid == guid )
                    .Select( t => t.Id )
                    .FirstOrDefault();

                ConnectionRequestActivity connectionRequestActivity = new ConnectionRequestActivity();
                connectionRequestActivity.ConnectionRequestId = request.Id;
                connectionRequestActivity.ConnectionOpportunityId = opportunity.Id;
                connectionRequestActivity.ConnectionActivityTypeId = transferredActivityId;
                connectionRequestActivity.Note = note;
                new ConnectionRequestActivityService( rockContext ).Add( connectionRequestActivity );

                rockContext.SaveChanges();
            }

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

            // 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 status
            ConnectionStatus status = null;
            Guid?            connectionStatusGuid          = null;
            Guid?            connectionStatusAttributeGuid = GetAttributeValue(action, "ConnectionStatusAttribute").AsGuidOrNull();

            if (connectionStatusAttributeGuid.HasValue)
            {
                connectionStatusGuid = action.GetWorklowAttributeValue(connectionStatusAttributeGuid.Value).AsGuidOrNull();
                if (connectionStatusGuid.HasValue)
                {
                    status = request.ConnectionOpportunity.ConnectionType.ConnectionStatuses
                             .Where(s => s.Guid.Equals(connectionStatusGuid.Value))
                             .FirstOrDefault();
                }
            }
            if (status == null)
            {
                connectionStatusGuid = GetAttributeValue(action, "ConnectionStatus").AsGuidOrNull();
                if (connectionStatusGuid.HasValue)
                {
                    status = request.ConnectionOpportunity.ConnectionType.ConnectionStatuses
                             .Where(s => s.Guid.Equals(connectionStatusGuid.Value))
                             .FirstOrDefault();
                }
            }
            if (status == null)
            {
                errorMessages.Add("Invalid Connection Status Attribute or Value!");
                return(false);
            }

            request.ConnectionStatusId = status.Id;
            rockContext.SaveChanges();

            return(true);
        }
Beispiel #8
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var  personAttribute = GetAttributeValue(action, "PersonAttribute");
            Guid personAttrGuid  = personAttribute.AsGuid();

            if (!personAttrGuid.IsEmpty())
            {
                var personAttributeInst = AttributeCache.Read(personAttrGuid, rockContext);
                if (personAttributeInst != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(personAttrGuid);
                    Guid   personAliasGuid      = attributePersonValue.AsGuid();

                    if (personAliasGuid != null)
                    {
                        var personAlias = (new PersonAliasService(rockContext)).Get(personAliasGuid);
                        if (personAlias != null)
                        {
                            var prayerRequestAttr         = GetAttributeValue(action, "PrayerRequest").ResolveMergeFields(GetMergeFields(action));
                            var prayerRequestValue        = action.GetWorklowAttributeValue(prayerRequestAttr.AsGuid());
                            var prayerRequestCategoryAttr = GetAttributeValue(action, "Category").ResolveMergeFields(GetMergeFields(action));
                            var categoryInst = action.GetWorklowAttributeValue(prayerRequestCategoryAttr.AsGuid());
                            var category     = (new CategoryService(rockContext)).Get(categoryInst.AsGuid());
                            if (prayerRequestValue != null)
                            {
                                submitPrayer(personAlias, prayerRequestValue, category, rockContext);
                            }
                            else
                            {
                                errorMessages.Add(string.Format("PrayerRequest not valid entry"));
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add(string.Format("PersonAlias cannot be found: {0}", personAliasGuid));
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Person attribute could not be found for '{0}'!", personAttrGuid.ToString()));
                }
            }
            else
            {
                errorMessages.Add(string.Format("Selected person attribute ('{0}') was not a valid Guid!", personAttribute));
            }
            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>();

            // 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 status
            ConnectionStatus status = null;
            Guid? connectionStatusGuid = null;
            Guid? connectionStatusAttributeGuid = GetAttributeValue( action, "ConnectionStatusAttribute" ).AsGuidOrNull();
            if ( connectionStatusAttributeGuid.HasValue )
            {
                connectionStatusGuid = action.GetWorklowAttributeValue( connectionStatusAttributeGuid.Value ).AsGuidOrNull();
                if ( connectionStatusGuid.HasValue )
                {
                    status = request.ConnectionOpportunity.ConnectionType.ConnectionStatuses
                        .Where( s => s.Guid.Equals( connectionStatusGuid.Value ) )
                        .FirstOrDefault();
                }
            }
            if ( status == null )
            {
                connectionStatusGuid = GetAttributeValue( action, "ConnectionStatus" ).AsGuidOrNull();
                if ( connectionStatusGuid.HasValue )
                {
                    status = request.ConnectionOpportunity.ConnectionType.ConnectionStatuses
                        .Where( s => s.Guid.Equals( connectionStatusGuid.Value ) )
                        .FirstOrDefault();
                }
            }
            if ( status == null )
            {
                errorMessages.Add( "Invalid Connection Status Attribute or Value!" );
                return false;
            }

            request.ConnectionStatusId = status.Id;
            rockContext.SaveChanges();

            return true;
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var originAttributeValue = GetActionAttributeValue(action, "Origin");

            var origin = "";
            //first check to see if is attribute
            var cacheTagsGuid = originAttributeValue.AsGuidOrNull();

            if (cacheTagsGuid != null)
            {
                origin = action.GetWorklowAttributeValue(cacheTagsGuid.Value);
            }
            else
            {
                var mergeFields = GetMergeFields(action);
                origin = originAttributeValue.ResolveMergeFields(mergeFields);
            }

            try
            {
                var campusTask = Task.Run(async() => await CampusUtilities.GetClosestCampus(origin));
                campusTask.Wait();

                var campusAttributeValue = GetActionAttributeValue(action, "Campus").AsGuid();
                SetWorkflowAttributeValue(action, campusAttributeValue, campusTask.Result.Guid.ToString());
            }
            catch (Exception e)
            {
                action.AddLogEntry("Exception while trying to load closest campus: " + e.Message, true);
            }


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

            var personAliasGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Person").AsGuid()).AsGuidOrNull();

            if (personAliasGuid.HasValue)
            {
                PersonAliasService personAliasService = new PersonAliasService(new RockContext());
                PersonAlias        personAlias        = personAliasService.Get(personAliasGuid.Value);

                var client = new RestClient(GlobalAttributesCache.Value("MinistrySafeAPIURL"));

                var request = new RestRequest("/users/{ExternalId}", Method.GET);
                request.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken"));
                request.AddUrlSegment("ExternalId", personAlias.Id.ToString());
                var tmp  = client.Execute <MinistrySafeUser>(request);
                var user = tmp.Data;

                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "Score").AsGuid(), user.score.ToString());
                if (user.complete_date != null)
                {
                    SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "CompletionDate").AsGuid(), user.complete_date.ToString());
                }

                return(true);
            }
            return(false);
        }
Beispiel #12
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 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))
            {
                var nameMaxLength = action.Activity.Workflow.GetAttributeFrom <MaxLengthAttribute>("Name").Length;

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

            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  itemListValue       = GetAttributeValue(action, "ItemList");
            Guid itemListValueAsGuid = itemListValue.AsGuid();

            if (!itemListValueAsGuid.IsEmpty())
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(itemListValueAsGuid);
                if (workflowAttributeValue != null)
                {
                    itemListValue = workflowAttributeValue;
                }
            }
            else
            {
                itemListValue = itemListValue.ResolveMergeFields(GetMergeFields(action));
            }

            if (string.IsNullOrWhiteSpace(itemListValue))
            {
                action.AddLogEntry("List is empty, not activating any activities.", true);
                return(true);
            }


            Guid guid = GetAttributeValue(action, "Activity").AsGuid();

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

            var workflow = action.Activity.Workflow;

            var activityTypeCache = WorkflowActivityTypeCache.Get(guid);

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

            string activityAttributeKey    = GetAttributeValue(action, "ActivityAttributeKey");
            bool   hasActivityAttributeKey = !string.IsNullOrWhiteSpace(activityAttributeKey);

            foreach (var item in itemListValue.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var activity = WorkflowActivity.Activate(activityTypeCache, workflow);
                if (hasActivityAttributeKey)
                {
                    activity.SetAttributeValue(activityAttributeKey, item);
                }
                action.AddLogEntry(string.Format("Activated new '{0}' activity", activityTypeCache.ToString()));
            }

            return(true);
        }
Beispiel #14
0
        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="key">The key.</param>
        /// <param name="checkWorkflowAttributeValue">if set to <c>true</c> and the returned value is a guid, check to see if the workflow
        /// or activity contains an attribute with that guid. This is useful when using the WorkflowTextOrAttribute field types to get the
        /// actual value or workflow value.</param>
        /// <returns></returns>
        protected string GetAttributeValue(WorkflowAction action, string key, bool checkWorkflowAttributeValue)
        {
            string value = GetActionAttributeValue(action, key);

            if (checkWorkflowAttributeValue)
            {
                Guid?attributeGuid = value.AsGuidOrNull();
                if (attributeGuid.HasValue)
                {
                    var attribute = AttributeCache.Read(attributeGuid.Value);
                    if (attribute != null)
                    {
                        value = action.GetWorklowAttributeValue(attributeGuid.Value);
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            if (attribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.ENCRYPTED_TEXT.AsGuid()).Id)
                            {
                                value = Security.Encryption.DecryptString(value);
                            }
                            else if (attribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.SSN.AsGuid()).Id)
                            {
                                value = Rock.Field.Types.SSNFieldType.UnencryptAndClean(value);
                            }
                        }
                    }
                }
            }

            return(value);
        }
Beispiel #15
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 url  = GetAttributeValue(action, "Url");
            Guid   guid = url.AsGuid();

            if (guid.IsEmpty())
            {
                url = url.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                url = action.GetWorklowAttributeValue(guid);
            }

            var  processOpt      = GetAttributeValue(action, "ProcessingOptions");
            bool canSendRedirect = !string.IsNullOrWhiteSpace(url) && HttpContext.Current != null;

            if (canSendRedirect)
            {
                HttpContext.Current.Response.Redirect(url, false);
            }

            if (processOpt == "1")
            {
                // 1) if HttpContext.Current is null, this workflow action might be running as a job (there is no browser session associated), so Redirect couldn't have been sent to a browser
                // 2) if there was no url specified, the redirect wouldn't have executed either
                return(canSendRedirect);
            }
            else
            {
                return(processOpt != "2");
            }
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeMatrixGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "AttributeMatrix").AsGuid()).AsGuidOrNull();
            var itemAttributes      = GetActionAttributeValue(action, "ItemAttributes").AsDictionaryOrNull();

            if (attributeMatrixGuid.HasValue && itemAttributes != null)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.Value);

                // Create the new item
                AttributeMatrixItem item = new AttributeMatrixItem();
                item.AttributeMatrix = matrix;
                item.LoadAttributes();

                foreach (var attribute in item.Attributes)
                {
                    if (itemAttributes.ContainsKey(attribute.Key))
                    {
                        item.SetAttributeValue(attribute.Key, itemAttributes[attribute.Key].ResolveMergeFields(GetMergeFields(action)));
                    }
                }
                matrix.AttributeMatrixItems.Add(item);
                rockContext.SaveChanges();
                item.SaveAttributeValues(rockContext);
            }

            return(true);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeMatrixGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "AttributeMatrix").AsGuid()).AsGuidOrNull();
            var itemGuid            = GetActionAttributeValue(action, "ItemGuid").ResolveMergeFields(GetMergeFields(action)).AsGuidOrNull();

            if (attributeMatrixGuid.HasValue && itemGuid.HasValue)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.Value);

                AttributeMatrixItem item = matrix.AttributeMatrixItems.Where(i => i.Guid == itemGuid.Value).FirstOrDefault();

                if (item != null)
                {
                    matrix.AttributeMatrixItems.Remove(item);
                    attributeMatrixItemService.Delete(item);
                }
            }

            return(true);
        }
Beispiel #18
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 url  = GetAttributeValue(action, "Url");
            Guid   guid = url.AsGuid();

            if (guid.IsEmpty())
            {
                url = url.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                url = action.GetWorklowAttributeValue(guid);
            }

            if (!string.IsNullOrWhiteSpace(url) && HttpContext.Current != null)
            {
                HttpContext.Current.Response.Redirect(url, false);
            }

            string processOpt = GetAttributeValue(action, "ProcessingOptions");

            if (processOpt == "1")
            {
                return(HttpContext.Current != null);
            }

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

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

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

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

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

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

            return false;
        }
Beispiel #21
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())
            {
                IEntityFieldType entityField = AttributeCache.Get(workflowAttributeGuid).FieldType.Field as IEntityFieldType;
                if (entityField == null)
                {
                    errorMessages.Add("Attribute Type is not an Entity.");
                    return(false);
                }

                IEntity entityObject = entityField.GetEntity(entityGuid.ToString(), rockContext);

                if (entityObject == null)
                {
                    errorMessages.Add("Failed to get entity.");
                    return(false);
                }

                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);
            }

            errorMessages.Add("Invalid Entity Attribute");
            return(false);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeGuid       = GetActionAttributeValue(action, "AttributeMatrix").AsGuidOrNull();
            var attributeMatrixGuid = action.GetWorklowAttributeValue(attributeGuid.HasValue?attributeGuid.Value:Guid.Empty).AsGuidOrNull();
            var itemAttributes      = GetActionAttributeValue(action, "ItemAttributes").AsDictionaryOrNull();

            if (attributeGuid.HasValue && itemAttributes != null)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.HasValue? attributeMatrixGuid.Value:Guid.Empty);

                // If the matrix is null, create it first
                if (matrix == null)
                {
                    var attribute = AttributeCache.Get(GetActionAttributeValue(action, "AttributeMatrix").AsGuid());
                    matrix = new AttributeMatrix();
                    matrix.AttributeMatrixItems      = new List <AttributeMatrixItem>();
                    matrix.AttributeMatrixTemplateId = attribute.QualifierValues["attributematrixtemplate"]?.Value?.AsInteger() ?? 0;
                    attributeMatrixService.Add(matrix);

                    // Persist it and make sure it gets saved
                    rockContext.SaveChanges();
                    if (attribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                    {
                        action.Activity.Workflow.SetAttributeValue(attribute.Key, matrix.Guid.ToString());
                    }
                    else if (attribute.EntityTypeId == new WorkflowActivity().TypeId)
                    {
                        action.Activity.SetAttributeValue(attribute.Key, matrix.Guid.ToString());
                    }
                }

                // Create the new item
                AttributeMatrixItem item = new AttributeMatrixItem();
                item.AttributeMatrix = matrix;
                item.LoadAttributes();

                foreach (var attribute in item.Attributes)
                {
                    if (itemAttributes.ContainsKey(attribute.Key))
                    {
                        item.SetAttributeValue(attribute.Key, itemAttributes[attribute.Key].ResolveMergeFields(GetMergeFields(action)));
                    }
                }
                matrix.AttributeMatrixItems.Add(item);
                rockContext.SaveChanges();
                item.SaveAttributeValues(rockContext);
            }

            return(true);
        }
Beispiel #23
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;
        }
Beispiel #24
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            Guid guid = GetAttributeValue(action, "Attribute").AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string existingValue = action.GetWorklowAttributeValue(guid);
                    string value         = GetAttributeValue(action, "Value");
                    string separator;

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

                    var mergeFields = GetMergeFields(action);

                    value = value.ResolveMergeFields(mergeFields);

                    string valueAction;
                    string newValue;

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

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

            var workflowActivityGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "Activity").AsGuid()).AsGuid();

            if (workflowActivityGuid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var attributeKey   = GetAttributeValue(action, "WorkflowAttributeKey", true);
            var attributeValue = GetAttributeValue(action, "WorkflowAttributeValue", true);

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

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

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

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

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

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

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


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

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

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

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

                    if ( attribute.EntityTypeId == new Rock.Model.Workflow().TypeId )
                    {
                        action.Activity.Workflow.SetAttributeValue( attribute.Key, newValue );
                        action.AddLogEntry( string.Format( "{2} '{0}' attribute to '{1}'.", attribute.Name, newValue, valueAction ) );
                    }
                    else if ( attribute.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId )
                    {
                        action.Activity.SetAttributeValue( attribute.Key, newValue );
                        action.AddLogEntry( string.Format( "{2} '{0}' attribute to '{1}'.", attribute.Name, newValue, valueAction ) );
                    }
                }
            }
            return true;
        }
Beispiel #27
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var  personAttribute = GetAttributeValue(action, "PersonAttribute");
            Guid personAttrGuid  = personAttribute.AsGuid();

            if (!personAttrGuid.IsEmpty())
            {
                var personAttributeInst = AttributeCache.Read(personAttrGuid, rockContext);
                if (personAttributeInst != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(personAttrGuid);
                    Guid   personAliasGuid      = attributePersonValue.AsGuid();

                    if (personAliasGuid != null)
                    {
                        var personAlias = (new PersonAliasService(rockContext)).Get(personAliasGuid);
                        if (personAlias != null)
                        {
                            // Get the persons current attendance if it exists
                            try
                            {
                                var currentAttendance = rockContext.Attendances.Where(a => a.PersonAlias.Id == personAlias.Id && DbFunctions.TruncateTime(a.CreatedDateTime.Value) == RockDateTime.Now.Date)
                                                        .FirstOrDefault();

                                if (currentAttendance != null)
                                {
                                    rockContext.Attendances.Remove(currentAttendance);
                                }
                            }
                            catch (ArgumentNullException ane)
                            {
                                errorMessages.Add(string.Format("Could not retrieve currentAttendance for person {0}. Exception: {1}", personAlias.Person.FullName, ane.Message));
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add(string.Format("PersonAlias cannot be found: {0}", personAliasGuid));
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Person attribute could not be found for '{0}'!", personAttrGuid.ToString()));
                }
            }
            else
            {
                errorMessages.Add(string.Format("Selected person attribute ('{0}') was not a valid Guid!", personAttribute));
            }
            return(true);
        }
Beispiel #28
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var mergeFields = GetMergeFields(action);

            // Get the connection request
            ConnectionRequest request = null;
            var 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 the connector
            PersonAlias personAlias         = null;
            Guid?       personAttributeGuid = GetAttributeValue(action, "PersonAttribute").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorklowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias == null)
                    {
                        errorMessages.Add("Invalid Person");
                        return(false);
                    }
                }
            }

            request.ConnectorPersonAlias = personAlias;
            rockContext.SaveChanges();

            return(true);
        }
Beispiel #29
0
        private Guid?GetGroupRoleValue(WorkflowAction action)
        {
            Guid?groupRoleGuid = null;

            string groupRole = GetAttributeValue(action, "GroupRole");
            Guid?  groupRoleAttributeGuid = GetAttributeValue(action, "GroupRole").AsGuidOrNull();

            if (groupRoleAttributeGuid.HasValue)
            {
                groupRoleGuid = action.GetWorklowAttributeValue(groupRoleAttributeGuid.Value).AsGuidOrNull();
            }

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

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

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

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

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

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

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

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

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

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

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

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

                if ( groupGuid.HasValue )
                {
                    var groupLeader = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                                       .Where(g => g.Group.Guid == groupGuid && g.GroupRole.IsLeader)
                                       .Select(g => g.Person).FirstOrDefault();

                    if ( groupLeader != null )
                    {
                        // Get the attribute to set
                        Guid leaderGuid = GetAttributeValue(action, "Leader").AsGuid();
                        if ( !leaderGuid.IsEmpty() )
                        {
                            var personAttribute = AttributeCache.Read(leaderGuid, rockContext);
                            if ( personAttribute != null )
                            {
                                // If this is a person type attribute
                                if ( personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id )
                                {
                                    SetWorkflowAttributeValue(action, leaderGuid, groupLeader.PrimaryAlias.Guid.ToString());
                                }
                                else if ( personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id )
                                {
                                    SetWorkflowAttributeValue(action, leaderGuid, groupLeader.FullName);
                                }
                            }
                        }
                    }
                }
                else
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

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

            return true;
        }
Beispiel #32
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 workflowActivityGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "Activity").AsGuid()).AsGuid();

            if (workflowActivityGuid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var reference = GetAttributeValue(action, "WorkflowReference", true);

            Rock.Model.Workflow workflow = null;
            if (reference.AsGuidOrNull() != null)
            {
                var referenceGuid = reference.AsGuid();
                workflow = new WorkflowService(rockContext).Queryable()
                           .Where(w => w.Guid == referenceGuid)
                           .FirstOrDefault();
            }
            else if (reference.AsIntegerOrNull() != null)
            {
                var referenceInt = reference.AsInteger();
                workflow = new WorkflowService(rockContext).Queryable()
                           .Where(w => w.Id == referenceInt)
                           .FirstOrDefault();
            }
            else
            {
                action.AddLogEntry("Invalid Workflow Property", true);
                return(false);
            }

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

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

            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>();

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

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

                if (groupGuid.HasValue)
                {
                    var groupLeader = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                                      .Where(g => g.Group.Guid == groupGuid && g.GroupRole.IsLeader)
                                      .Select(g => g.Person).FirstOrDefault();

                    if (groupLeader != null)
                    {
                        // Get the attribute to set
                        Guid leaderGuid = GetAttributeValue(action, "Leader").AsGuid();
                        if (!leaderGuid.IsEmpty())
                        {
                            var personAttribute = AttributeCache.Read(leaderGuid, rockContext);
                            if (personAttribute != null)
                            {
                                // If this is a person type attribute
                                if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                                {
                                    SetWorkflowAttributeValue(action, leaderGuid, groupLeader.PrimaryAlias.Guid.ToString());
                                }
                                else if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                                {
                                    SetWorkflowAttributeValue(action, leaderGuid, groupLeader.FullName);
                                }
                            }
                        }
                    }
                }
                else
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

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

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

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

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

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

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

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

                    }
                   
                }
            }

            errorMessages.Add( "An assignment to person could not be completed." );
            return false;
        
        }
Beispiel #35
0
        private List <DayOfWeek> GetDaysOfWeek(RockContext context, WorkflowAction action)
        {
            Guid daysOfWeekAttrGuid = GetAttributeValue(action, "DaysOfWeekAttribute").AsGuid();

            if (!daysOfWeekAttrGuid.IsEmpty())
            {
                var daysOfWeekAttributeInst = AttributeCache.Read(daysOfWeekAttrGuid, context);
                if (daysOfWeekAttributeInst != null)
                {
                    List <DayOfWeek> daysOfWeek = action.GetWorklowAttributeValue(daysOfWeekAttrGuid).Split(',').Select(a => (DayOfWeek)(a.AsInteger())).ToList();
                    return(daysOfWeek);
                }
            }
            return(null);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var personAliasGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Person").AsGuid()).AsGuidOrNull();

            if (personAliasGuid.HasValue)
            {
                PersonAliasService personAliasService = new PersonAliasService(new RockContext());
                PersonAlias        personAlias        = personAliasService.Get(personAliasGuid.Value);


                var client = new RestClient(GlobalAttributesCache.Value("MinistrySafeAPIURL"));

                var post = new RestRequest("/users", Method.POST);
                post.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken"));
                post.AddJsonBody(new
                {
                    user = new MinistrySafeUser()
                    {
                        external_id = personAlias.Id.ToString(),
                        first_name  = personAlias.Person.NickName,
                        last_name   = personAlias.Person.LastName,
                        email       = personAlias.Person.Email
                    },
                    tags = string.Join(",", GetActionAttributeValue(action, "MinistrySafeTags").Trim('|').Split('|'))
                }
                                 );
                var execution = client.Execute <bool>(post);

                if (execution.Data == true)
                {
                    var request = new RestRequest("/users/{ExternalId}", Method.GET);
                    request.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken"));
                    request.AddUrlSegment("ExternalId", personAlias.Id.ToString());
                    var tmp  = client.Execute <MinistrySafeUser>(request);
                    var user = tmp.Data;

                    if (user.direct_login_url != null)
                    {
                        SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "MinistrySafeURL").AsGuid(), user.direct_login_url);
                    }

                    return(true);
                }
            }
            return(false);
        }
Beispiel #37
0
        private string GetValue(WorkflowAction action, string key, RockContext rockContext)
        {
            string value = GetAttributeValue(action, key);
            Guid?  guid  = value.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Read(guid.Value, rockContext);
                if (attribute != null)
                {
                    return(action.GetWorklowAttributeValue(guid.Value));
                }
            }

            return(value);
        }
        public T GetFromAttribute <T, T2>(WorkflowAction action, string attributeKey, string attributeAttributeKey, Func <string, T2, T> valueConverter, T2 valueConverterData)
        {
            // Try getting from Workflow Action's Attribute
            var attributeStr = GetAttributeValue(action, attributeKey);

            if (!string.IsNullOrWhiteSpace(attributeStr))
            {
                var attributeVal = valueConverter(attributeStr, valueConverterData);
                if (attributeVal != null)
                {
                    return(attributeVal);
                }
            }

            // Fall back to Workflow Action's Workflow Attribute
            return(valueConverter(action.GetWorklowAttributeValue(GetAttributeValue(action, attributeAttributeKey).AsGuid()), valueConverterData));
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var  groupAttribute = GetAttributeValue(action, "GroupAttribute");
            Guid groupAttrGuid  = groupAttribute.AsGuid();

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

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

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

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

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

            errorMessages.Add("An assignment to person could not be completed.");
            return(false);
        }
Beispiel #40
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");
                    guid = value.AsGuid();
                    if (guid.IsEmpty())
                    {
                        value = value.ResolveMergeFields(GetMergeFields(action));
                    }
                    else
                    {
                        var attributeValue = action.GetWorklowAttributeValue(guid);

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

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

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

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

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

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

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

            return true;
        }
Beispiel #43
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.Read( 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;
        }
Beispiel #44
0
        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, "URL");
                    guid = value.AsGuid();
                    if (guid.IsEmpty())
                    {
                        value = value.ResolveMergeFields(GetMergeFields(action));
                    }
                    else
                    {
                        var attributeValue = action.GetWorklowAttributeValue(guid);

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

                    if (!string.IsNullOrWhiteSpace(value) && IsUrl(value))
                    {
                        var url = GetShortUrlFromString(value);

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

                    }
                    else
                    {
                        action.AddLogEntry(string.Format("Error: '{0}' is not a valid url.", value));
                    }

                }
            }

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

            string updateValue = GetAttributeValue( action, "Value" );
            Guid? valueGuid = updateValue.AsGuidOrNull();
            if ( valueGuid.HasValue )
            {
                updateValue = action.GetWorklowAttributeValue( valueGuid.Value );
            }
            else
            {
                updateValue = updateValue.ResolveMergeFields( GetMergeFields( action ) );
            }

            string personAttribute = GetAttributeValue( action, "PersonAttribute" );

            Guid guid = personAttribute.AsGuid();
            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string value = GetAttributeValue( action, "Person" );
                    guid = value.AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        var attributePerson = AttributeCache.Read( guid, rockContext );
                        if ( attributePerson != null )
                        {
                            string attributePersonValue = action.GetWorklowAttributeValue( guid );
                            if ( !string.IsNullOrWhiteSpace( attributePersonValue ) )
                            {
                                if ( attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType" )
                                {
                                    Guid personAliasGuid = attributePersonValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var person = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .Select( a => a.Person )
                                            .FirstOrDefault();
                                        if ( person != null )
                                        {
                                            // update person attribute
                                            Rock.Attribute.Helper.SaveAttributeValue( person, attribute, updateValue, rockContext );
                                            action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName ) );
                                            return true;
                                        }
                                        else
                                        {
                                            errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guid.ToString() ) );
                                        }
                                    }
                                }
                                else
                                {
                                    errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                                }
                            }
                        }
                    }
                }
                else
                {
                    errorMessages.Add( string.Format( "Person attribute could not be found for '{0}'!", guid.ToString() ) );
                }
            }
            else
            {
                errorMessages.Add( string.Format( "Selected person attribute ('{0}') was not a valid Guid!", personAttribute ) );
            }

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

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

            //Get the Attribute Values
            var metricId = GetAttributeValue(action, "MetricId");
            var metricValue = GetAttributeValue(action, "MetricValue");
            var metricDate = GetAttributeValue(action, "MetricDate");
            var metricEntityId = GetAttributeValue(action, "EntityId");
            var metricNotes = GetAttributeValue(action, "Notes");
            var metricType = GetAttributeValue(action, "MetricType");

            //Get Metric Id
            string metricIdContent = metricId;
            Guid metricIdGuid = metricId.AsGuid();
            if (metricIdGuid.IsEmpty())
            {
                metricIdContent = metricIdContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricIdGuid);

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

            //Get Metric Value
            string metricValueContent = metricValue;
            Guid metricValueGuid = metricValue.AsGuid();
            if (metricValueGuid.IsEmpty())
            {
                metricValueContent = metricValueContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricValueGuid);

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

            //Get Metric Date
            string metricDateContent = metricDate;
            Guid metricDateGuid = metricDate.AsGuid();
            if (metricDateGuid.IsEmpty())
            {
                metricDateContent = metricDateContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricDateGuid);

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

            //Get Metric Notes
            string metricNotesContent = metricNotes;
            Guid metricNotesGuid = metricNotes.AsGuid();
            if (metricNotesGuid.IsEmpty())
            {
                metricNotesContent = metricNotesContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricNotesGuid);

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

            //Get Metric EntityId
            string metricEntityIdContent = metricEntityId;
            Guid metricEntityIdGuid = metricEntityId.AsGuid();
            if (metricEntityIdGuid.IsEmpty())
            {
                metricEntityIdContent = metricEntityIdContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricEntityIdGuid);

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

            //Get Metric Type
            string metricTypeContent = metricType;
            Guid metricTypeGuid = metricType.AsGuid();
            if (metricTypeGuid.IsEmpty())
            {
                metricTypeContent = metricTypeContent.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var attributeValue = action.GetWorklowAttributeValue(metricTypeGuid);

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

            //Convert the Attribute values to approprate types
            DateTime metricDateAsDate = Convert.ToDateTime(metricDateContent);
            Decimal metricValueAsDecimal = Decimal.Parse(metricValueContent);
            int metricEntityIdAsInt = Int32.Parse(metricEntityIdContent);
            int metricTypeAsInt = Int32.Parse(metricTypeContent);

            //Convert Metric Attribute to Id
            var metricIdAsGuidAsValues = metricIdContent.Split('|');
            var metricIdAsGuid = Guid.Parse(metricIdAsGuidAsValues[0]);
            MetricService metricService = new MetricService(rockContext);
            var selectedMetric = metricService.Queryable().FirstOrDefault(m => m.Guid == metricIdAsGuid);
            if (selectedMetric != null)
            {
                int metricIdAsInt = selectedMetric.Id;

                //Save the Metric
                SaveMetric(metricDateAsDate, metricIdAsInt, metricValueAsDecimal, metricEntityIdAsInt, metricNotesContent, metricTypeAsInt);
            }

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

            var mergeFields = GetMergeFields( action );

            int? fromId = null;
            Guid? fromGuid = GetAttributeValue( action, "From" ).AsGuidOrNull();
            if ( fromGuid.HasValue )
            {
                var fromValue = DefinedValueCache.Read( fromGuid.Value, rockContext );
                if ( fromValue != null )
                {
                    fromId = fromValue.Id;
                }
            }

            var recipients = new List<RecipientData>();

            string toValue = GetAttributeValue( action, "To" );
            Guid guid = toValue.AsGuid();
            if ( !guid.IsEmpty() )
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string toAttributeValue = action.GetWorklowAttributeValue( guid );
                    if ( !string.IsNullOrWhiteSpace( toAttributeValue ) )
                    {
                        switch ( attribute.FieldType.Class )
                        {
                            case "Rock.Field.Types.TextFieldType":
                                {
                                    recipients.Add( new RecipientData( toAttributeValue ) );
                                    break;
                                }
                            case "Rock.Field.Types.PersonFieldType":
                                {
                                    Guid personAliasGuid = toAttributeValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var phoneNumber = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .SelectMany( a => a.Person.PhoneNumbers )
                                            .Where( p => p.IsMessagingEnabled )
                                            .FirstOrDefault();

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

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

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

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

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

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

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

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

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

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

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

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

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

            return true;
        }
Beispiel #48
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 Dictionary<string, Dictionary<string, object>>();

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

            Guid? guid = to.AsGuidOrNull();
            if ( guid.HasValue )
            {
                var attribute = AttributeCache.Read( guid.Value, rockContext );
                if ( attribute != null )
                {
                    string toValue = action.GetWorklowAttributeValue( guid.Value );
                    if ( !string.IsNullOrWhiteSpace( toValue ) )
                    {
                        switch ( attribute.FieldType.Class )
                        {
                            case "Rock.Field.Types.TextFieldType":
                                {
                                    recipients.Add( toValue, mergeFields );
                                    break;
                                }
                            case "Rock.Field.Types.PersonFieldType":
                                {
                                    Guid personAliasGuid = toValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var person = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .Select( a => a.Person )
                                            .FirstOrDefault();
                                        if ( person == null )
                                        {
                                            action.AddLogEntry( "Invalid Recipient: Person not found", true );
                                        }
                                        else if ( string.IsNullOrWhiteSpace( person.Email ) )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient does not have an email address", true );
                                        }
                                        else if ( !( person.IsEmailActive ?? true ) )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient email is not active", true );
                                        }
                                        else if ( person.EmailPreference == EmailPreference.DoNotEmail )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient has requested 'Do Not Email'", true );
                                        }
                                        else
                                        {
                                            var personDict = new Dictionary<string, object>( mergeFields );
                                            personDict.Add( "Person", person );
                                            recipients.Add( person.Email, personDict );
                                        }
                                    }
                                    break;
                                }
                            case "Rock.Field.Types.GroupFieldType":
                                {
                                    int? groupId = toValue.AsIntegerOrNull();
                                    if ( !groupId.HasValue )
                                    {
                                        foreach ( var person in new GroupMemberService( rockContext )
                                            .GetByGroupId( groupId.Value )
                                            .Where( m => m.GroupMemberStatus == GroupMemberStatus.Active )
                                            .Select( m => m.Person ) )
                                        {
                                            if ( ( person.IsEmailActive ?? true ) &&
                                                person.EmailPreference != EmailPreference.DoNotEmail &&
                                                !string.IsNullOrWhiteSpace( person.Email ) )
                                            {
                                                var personDict = new Dictionary<string, object>( mergeFields );
                                                personDict.Add( "Person", person );
                                                recipients.Add( person.Email, personDict );
                                            }
                                        }
                                    }
                                    break;
                                }
                        }
                    }
                }
            }
            else
            {
                recipients.Add( to, mergeFields );
            }

            if ( recipients.Any() )
            {
                Email.Send( GetAttributeValue( action, "EmailTemplate" ).AsGuid(), recipients );
            }

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

            // Get person
            Person person = null;
            int personAliasId = 1;

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

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

            if (person != null)
            {
                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                personAliasId = person.PrimaryAliasId ?? default(int);
            }

            //Get DateTime
            DateTime currentDateTime =  DateTime.Now;

            //Get Stars Value
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            var type = GetAttributeValue(action, "Type");
            Guid typeGuid = type.AsGuid();

            var definedValue = definedValueService.GetByGuid(typeGuid);
            definedValue.LoadAttributes();
            var value = definedValue.GetAttributeValue("StarValue");
            var starsValue = Convert.ToDecimal(value);

            //Save Stars
            SaveStars(currentDateTime, personAliasId, starsValue, definedValue.Value);

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

            // get the tag
            string tagName = GetAttributeValue( action, "OrganizationTag" ).ResolveMergeFields( GetMergeFields( action ) ); ;
            if (!string.IsNullOrEmpty(tagName)) {

                // get person entity type
                var personEntityType = Rock.Web.Cache.EntityTypeCache.Read("Rock.Model.Person");

                // get tag
                TagService tagService = new TagService( rockContext );
                Tag orgTag = tagService.Queryable().Where( t => t.Name == tagName && t.EntityTypeId == personEntityType.Id && t.OwnerPersonAlias == null ).FirstOrDefault();

                if ( orgTag == null )
                {
                    // add tag first
                    orgTag = new Tag();
                    orgTag.Name = tagName;
                    orgTag.EntityTypeQualifierColumn = string.Empty;
                    orgTag.EntityTypeQualifierValue = string.Empty;

                    orgTag.EntityTypeId = personEntityType.Id;
                    tagService.Add( orgTag );
                    rockContext.SaveChanges();

                    // new up a list of items for later count
                    orgTag.TaggedItems = new List<TaggedItem>();
                }

                // get the person and add them to the tag
                string value = GetAttributeValue( action, "Person" );
                Guid guidPersonAttribute = value.AsGuid();
                if ( !guidPersonAttribute.IsEmpty() )
                {
                    var attributePerson = AttributeCache.Read( 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() )
                                {
                                    var person = new PersonAliasService( rockContext ).Queryable()
                                        .Where( a => a.Guid.Equals( personAliasGuid ) )
                                        .Select( a => a.Person )
                                        .FirstOrDefault();
                                    if ( person != null )
                                    {
                                        // add person to tag if they are not already in it
                                        if ( orgTag.TaggedItems.Where( i => i.EntityGuid == person.PrimaryAlias.AliasPersonGuid && i.TagId == orgTag.Id ).Count() == 0 )
                                        {
                                            TaggedItem taggedPerson = new TaggedItem();
                                            taggedPerson.Tag = orgTag;
                                            taggedPerson.EntityGuid = person.PrimaryAlias.AliasPersonGuid;
                                            orgTag.TaggedItems.Add( taggedPerson );
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            action.AddLogEntry( string.Format( "{0} already tagged with {1}", person.FullName, orgTag.Name ) );
                                        }

                                        return true;
                                    }
                                    else
                                    {
                                        errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) );
                                    }
                                }
                            }
                            else
                            {
                                errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                            }
                        }
                    }
                }
            } else {
                errorMessages.Add("No organization tag was provided");
            }

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

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

            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));
                        }
                    }

                    AttendanceService attendanceService = new AttendanceService(rockContext);

                    Attendance attendance = new Attendance();
                    attendance.GroupId = group.Id;
                    attendance.PersonAliasId = person.PrimaryAliasId;
                    attendance.StartDateTime = attendanceDateTime;
                    attendance.CampusId = group.CampusId;
                    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;
        }
Beispiel #52
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

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

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

            Guid? guid = to.AsGuidOrNull();
            if ( guid.HasValue )
            {
                var attribute = AttributeCache.Read( guid.Value, rockContext );
                if ( attribute != null )
                {
                    string toValue = action.GetWorklowAttributeValue( guid.Value );
                    if ( !string.IsNullOrWhiteSpace( toValue ) )
                    {
                        switch ( attribute.FieldType.Class )
                        {
                            case "Rock.Field.Types.TextFieldType":
                            case "Rock.Field.Types.EmailFieldType":
                                {
                                    var recipientList = toValue.SplitDelimitedValues().ToList();
                                    foreach ( string recipient in recipientList )
                                    {
                                        recipients.Add( new RecipientData( recipient, mergeFields ) );
                                    }
                                    break;
                                }
                            case "Rock.Field.Types.PersonFieldType":
                                {
                                    Guid personAliasGuid = toValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var person = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .Select( a => a.Person )
                                            .FirstOrDefault();
                                        if ( person == null )
                                        {
                                            action.AddLogEntry( "Invalid Recipient: Person not found", true );
                                        }
                                        else if ( string.IsNullOrWhiteSpace( person.Email ) )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient does not have an email address", true );
                                        }
                                        else if ( !( person.IsEmailActive ) )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient email is not active", true );
                                        }
                                        else if ( person.EmailPreference == EmailPreference.DoNotEmail )
                                        {
                                            action.AddLogEntry( "Email was not sent: Recipient has requested 'Do Not Email'", true );
                                        }
                                        else
                                        {
                                            var personDict = new Dictionary<string, object>( mergeFields );
                                            personDict.Add( "Person", person );
                                            recipients.Add( new RecipientData( person.Email, personDict ) );
                                        }
                                    }
                                    break;
                                }
                            case "Rock.Field.Types.GroupFieldType":
                            case "Rock.Field.Types.SecurityRoleFieldType":
                                {
                                    int? groupId = toValue.AsIntegerOrNull();
                                    Guid? groupGuid = toValue.AsGuidOrNull();
                                    IQueryable<GroupMember> qry = null;

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

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

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

            if ( recipients.Any() )
            {
                Email.Send( GetAttributeValue( action, "SystemEmail" ).AsGuid(), recipients, string.Empty, string.Empty, GetAttributeValue( action, "SaveCommunicationHistory" ).AsBoolean() );
            }

            return true;
        }
Beispiel #53
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 updateValue = GetAttributeValue( action, "Value" );
            Guid? valueGuid = updateValue.AsGuidOrNull();
            if ( valueGuid.HasValue )
            {
                updateValue = action.GetWorklowAttributeValue( valueGuid.Value );
            }
            else
            {
                updateValue = updateValue.ResolveMergeFields( GetMergeFields( action ) );
            }

            string personAttribute = GetAttributeValue( action, "PersonAttribute" );

            Guid guid = personAttribute.AsGuid();
            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string value = GetAttributeValue( action, "Person" );
                    guid = value.AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        var attributePerson = AttributeCache.Read( guid, rockContext );
                        if ( attributePerson != null )
                        {
                            string attributePersonValue = action.GetWorklowAttributeValue( guid );
                            if ( !string.IsNullOrWhiteSpace( attributePersonValue ) )
                            {
                                if ( attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType" )
                                {
                                    Guid personAliasGuid = attributePersonValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var person = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .Select( a => a.Person )
                                            .FirstOrDefault();
                                        if ( person != null )
                                        {
                                            // update person attribute
                                            person.LoadAttributes();
                                            string originalValue = person.GetAttributeValue( attribute.Key );

                                            // Handle encrypted text fields as well.
                                            if ( attribute.FieldType.Field is Field.Types.EncryptedTextFieldType )
                                            {
                                                updateValue = Security.Encryption.EncryptString( updateValue );
                                            }

                                            Rock.Attribute.Helper.SaveAttributeValue( person, attribute, updateValue, rockContext );

                                            if ( ( originalValue ?? string.Empty ).Trim() != ( updateValue ?? string.Empty ).Trim() )
                                            {
                                                var changes = new List<string>();

                                                string formattedOriginalValue = string.Empty;
                                                if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                                {
                                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                                }

                                                string formattedNewValue = string.Empty;
                                                if ( !string.IsNullOrWhiteSpace( updateValue ) )
                                                {
                                                    formattedNewValue = attribute.FieldType.Field.FormatValue( null, updateValue, attribute.QualifierValues, false );
                                                }

                                                History.EvaluateChange( changes, attribute.Name, formattedOriginalValue, formattedNewValue, attribute.FieldType.Field.IsSensitive() );
                                                if ( changes.Any() )
                                                {
                                                    HistoryService.SaveChanges( rockContext, typeof( Person ),
                                                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                        person.Id, changes );
                                                }
                                            }

                                            action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, updateValue ) );
                                            return true;

                                        }
                                        else
                                        {
                                            errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guid.ToString() ) );
                                        }
                                    }
                                }
                                else
                                {
                                    errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                                }
                            }
                        }
                    }
                }
                else
                {
                    errorMessages.Add( string.Format( "Person attribute could not be found for '{0}'!", guid.ToString() ) );
                }
            }
            else
            {
                errorMessages.Add( string.Format( "Selected person attribute ('{0}') was not a valid Guid!", personAttribute ) );
            }

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

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

            // get person
            Person person = null;

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

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

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorklowAttributeValue( GetAttributeValue( action, "LocationTypeAttribute" ).AsGuid() );
            if ( locationTypeAttributeValue != null )
            {
                locationType = DefinedValueCache.Read( locationTypeAttributeValue.AsGuid() );
            }
            if ( locationType == null )
            {
                locationType = DefinedValueCache.Read( GetAttributeValue( action, "LocationType" ).AsGuid() );
            }
            if ( locationType == null )
            {
                errorMessages.Add( "The location type to be updated was not selected." );
                return false;
            }

            // get the new phone number value
            Location location = null;
            string locationValue = GetAttributeValue( action, "Location" );
            Guid? locationGuid = locationValue.AsGuidOrNull();
            if ( !locationGuid.HasValue || locationGuid.Value.IsEmpty() )
            {
                string locationAttributeValue = GetAttributeValue( action, "LocationAttribute" );
                Guid? locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if ( locationAttributeValueGuid.HasValue )
                {
                    locationGuid = action.GetWorklowAttributeValue( locationAttributeValueGuid.Value ).AsGuidOrNull();
                }
            }

            if ( locationGuid.HasValue )
            {
                location = new LocationService( rockContext ).Get( locationGuid.Value );
            }

            if ( location == null )
            {
                errorMessages.Add( "The location value could not be determined." );
                return false;
            }

            // gets value indicating if location is a mailing location
            string mailingValue = GetAttributeValue( action, "IsMailing" );
            Guid? mailingValueGuid = mailingValue.AsGuidOrNull();
            if ( mailingValueGuid.HasValue )
            {
                mailingValue = action.GetWorklowAttributeValue( mailingValueGuid.Value );
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            bool? mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue = GetAttributeValue( action, "IsMapped" );
            Guid? mappedValueGuid = mappedValue.AsGuidOrNull();
            if ( mappedValueGuid.HasValue )
            {
                mappedValue = action.GetWorklowAttributeValue( mappedValueGuid.Value );
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            bool? mapped = mappedValue.AsBooleanOrNull();

            var groupLocationService = new GroupLocationService( rockContext );
            foreach ( var family in person.GetFamilies( rockContext ).ToList() )
            {
                var groupLocation = family.GroupLocations.FirstOrDefault( l => l.GroupLocationTypeValueId == locationType.Id );
                string oldValue = string.Empty;
                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    groupLocation.GroupId = family.Id;
                    groupLocation.GroupLocationTypeValueId = locationType.Id;
                    groupLocationService.Add( groupLocation );
                }
                else
                {
                    oldValue = groupLocation.Location.ToString();
                }

                var groupChanges = new List<string>();

                History.EvaluateChange(
                    groupChanges,
                    locationType.Value + " Location",
                    oldValue,
                    location.ToString() );

                groupLocation.Location = location;

                if ( mailing.HasValue )
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Mailing",
                        groupLocation.IsMailingLocation.ToString(),
                        mailing.Value.ToString() );
                    groupLocation.IsMailingLocation = mailing.Value;
                }

                if ( mapped.HasValue )
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Map Location",
                        groupLocation.IsMappedLocation.ToString(),
                        mapped.Value.ToString() );
                    groupLocation.IsMappedLocation = mapped.Value;
                }

                if ( groupChanges.Any() )
                {
                    groupChanges.Add( string.Format( "<em>(Updated by the '{0}' workflow)</em>", action.ActionType.ActivityType.WorkflowType.Name ) );
                    foreach ( var fm in family.Members )
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof( Person ),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof( Group ),
                            family.Id,
                            false );
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry( string.Format( "Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.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>();

            string size = GetAttributeValue( action, "size" ) ?? "200";
            string value = GetAttributeValue( action, "Person" );
            Guid personGuid = value.AsGuid();
            if ( !personGuid.IsEmpty() )
            {
                var attributePerson = AttributeCache.Read( personGuid, rockContext );
                if ( attributePerson != null )
                {
                    string attributePersonValue = action.GetWorklowAttributeValue( personGuid );
                    if ( !string.IsNullOrWhiteSpace( attributePersonValue ) )
                    {
                        if ( attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType" )
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if ( !personAliasGuid.IsEmpty() )
                            {
                                var person = new PersonAliasService( rockContext ).Queryable()
                                    .Where( a => a.Guid.Equals( personAliasGuid ) )
                                    .Select( a => a.Person )
                                    .FirstOrDefault();
                                if ( person != null )
                                {
                                    if ( !string.IsNullOrEmpty( person.Email ) )
                                    {
                                        // Build MD5 hash for email
                                        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                                        byte[] encodedEmail = new UTF8Encoding().GetBytes( person.Email.ToLower().Trim() );
                                        byte[] hashedBytes = md5.ComputeHash( encodedEmail );
                                        StringBuilder sb = new StringBuilder( hashedBytes.Length * 2 );
                                        for ( int i = 0; i < hashedBytes.Length; i++ )
                                        {
                                            sb.Append( hashedBytes[i].ToString( "X2" ) );
                                        }
                                        string hash = sb.ToString().ToLower();
                                        // Query Gravatar's https endpoint asking for a 404 on no match
                                        var restClient = new RestClient( string.Format( "https://secure.gravatar.com/avatar/{0}.jpg?default=404&size={1}", hash, size ) );
                                        var request = new RestRequest( Method.GET );
                                        var response = restClient.Execute( request );
                                        if ( response.StatusCode == HttpStatusCode.OK )
                                        {
                                            var bytes = response.RawBytes;
                                            // Create and save the image
                                            BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                            if ( fileType != null )
                                            {

                                                var binaryFileService = new BinaryFileService( rockContext );
                                                var binaryFile = new BinaryFile();
                                                binaryFileService.Add( binaryFile );
                                                binaryFile.IsTemporary = false;
                                                binaryFile.BinaryFileType = fileType;
                                                binaryFile.MimeType = "image/jpeg";
                                                binaryFile.FileName = person.NickName + person.LastName + ".jpg";
                                                binaryFile.ContentStream = new MemoryStream( bytes );

                                                person.PhotoId = binaryFile.Id;
                                                rockContext.SaveChanges();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        errorMessages.Add( string.Format( "Email address could not be found for {0} ({1})!", person.FullName.ToString(), personGuid.ToString() ) );
                                    }
                                }
                                else
                                {
                                    errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", personGuid.ToString() ) );
                                }
                            }
                        }
                        else
                        {
                            errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                        }
                    }
                }
            }

            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>();

            // get the tag
            string tagName = GetAttributeValue( action, "OrganizationTag" ).ResolveMergeFields( GetMergeFields( action ) ); ;
            if (!string.IsNullOrEmpty(tagName)) {

                // get person entity type
                var personEntityType = Rock.Web.Cache.EntityTypeCache.Read("Rock.Model.Person");

                // get tag
                TagService tagService = new TagService( rockContext );
                Tag orgTag = tagService.Queryable().Where( t => t.Name == tagName && t.EntityTypeId == personEntityType.Id && t.OwnerPersonAlias == null ).FirstOrDefault();

                if ( orgTag != null )
                {
                    // get person
                    string value = GetAttributeValue( action, "Person" );
                    Guid guidPersonAttribute = value.AsGuid();
                    if ( !guidPersonAttribute.IsEmpty() )
                    {
                        var attributePerson = AttributeCache.Read( 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() )
                                    {
                                        var person = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .Select( a => a.Person )
                                            .FirstOrDefault();
                                        if ( person != null )
                                        {
                                            var personAliasGuids = person.Aliases.Select( a => a.AliasPersonGuid ).ToList();
                                            TaggedItemService tiService = new TaggedItemService( rockContext );
                                            TaggedItem personTag = tiService.Queryable().Where( t => t.TagId == orgTag.Id && personAliasGuids.Contains( t.EntityGuid ) ).FirstOrDefault();
                                            if ( personTag != null )
                                            {
                                                tiService.Delete( personTag );
                                                rockContext.SaveChanges();
                                            }
                                            else
                                            {
                                                action.AddLogEntry( string.Format( "{0} was not in the {1} tag.", person.FullName, orgTag.Name ) );
                                            }
                                        }
                                        else
                                        {
                                            errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    action.AddLogEntry( string.Format( "{0} organization tag does not exist.", orgTag.Name ) );
                }
            } else {
                errorMessages.Add("No organization tag was provided");
            }

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

            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>();
            
            var personAttribute =  GetAttributeValue( action, "PersonAttribute" );
            Guid personAttrGuid = personAttribute.AsGuid();
            
            if (!personAttrGuid.IsEmpty())
            {
                var personAttributeInst = AttributeCache.Read( personAttrGuid, rockContext );
                if (personAttributeInst != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue( personAttrGuid );
                    Guid personAliasGuid = attributePersonValue.AsGuid();
                    
                    var attrAttribute = GetAttributeValue( action, "Attribute" );
                    Guid attributeGuid = attrAttribute.AsGuid();

                    if (!attributeGuid.IsEmpty())
                    {
                        // Get the attribute
                        var attributeInst = AttributeCache.Read( attributeGuid, rockContext );
                        if ( attributeInst != null )
                        {
                            var personAlias = (new PersonAliasService( rockContext )).Get( personAliasGuid );
                            if (personAlias != null)
                            {
                                personAlias.Person.LoadAttributes();
                                var mergeFields = GetMergeFields( action );
                                mergeFields.Add( "Person", personAlias.Person );

                                string value = GetAttributeValue( action, "Lava" );

                                value = value.ResolveMergeFields( mergeFields );

                                if (attributeInst.EntityTypeId == new Rock.Model.Workflow().TypeId)
                                {
                                    action.Activity.Workflow.SetAttributeValue( attributeInst.Key, value );
                                    action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attributeInst.Name, value ) );
                                }
                                else if (attributeInst.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId)
                                {
                                    action.Activity.SetAttributeValue( attributeInst.Key, value );
                                    action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attributeInst.Name, value ) );
                                }
                            }
                            else
                            {
                                errorMessages.Add( string.Format( "PersonAlias cannot be found: {0}", personAliasGuid ) );
                            }
                        }
                        else
                        {
                            errorMessages.Add( string.Format( "Workflow attribute could not be found for '{0}'!", attributeGuid.ToString() ) );
                        }
                    }
                    else
                    {
                        errorMessages.Add( string.Format( "Selected attribute ('{0}') was not a valid Guid!", attrAttribute ) );
                    }
                    
                }
                else
                {
                    errorMessages.Add( string.Format( "Person attribute could not be found for '{0}'!", personAttrGuid.ToString() ) );
                }
            } 
            else
            {
                errorMessages.Add( string.Format( "Selected person attribute ('{0}') was not a valid Guid!", personAttribute ) );
            }

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

            int? fromId = null;
            Guid? fromGuid = GetAttributeValue( action, "From" ).AsGuidOrNull();
            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            var recipients = new List<string>();
            string toValue = GetAttributeValue( action, "To" );
            Guid guid = toValue.AsGuid();
            if ( !guid.IsEmpty() )
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string toAttributeValue = action.GetWorklowAttributeValue( guid );
                    if ( !string.IsNullOrWhiteSpace( toAttributeValue ) )
                    {
                        switch ( attribute.FieldType.Class )
                        {
                            case "Rock.Field.Types.TextFieldType":
                                {
                                    recipients.Add( toAttributeValue );
                                    break;
                                }
                            case "Rock.Field.Types.PersonFieldType":
                                {
                                    Guid personAliasGuid = toAttributeValue.AsGuid();
                                    if ( !personAliasGuid.IsEmpty() )
                                    {
                                        var phoneNumber = new PersonAliasService( rockContext ).Queryable()
                                            .Where( a => a.Guid.Equals( personAliasGuid ) )
                                            .SelectMany( a => a.Person.PhoneNumbers )
                                            .Where( p => p.IsMessagingEnabled)
                                            .FirstOrDefault();

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

                            case "Rock.Field.Types.GroupFieldType":
                                {
                                    int? groupId = toValue.AsIntegerOrNull();
                                    if ( !groupId.HasValue )
                                    {
                                        foreach ( var person in new GroupMemberService( rockContext )
                                            .GetByGroupId( groupId.Value )
                                            .Where( m => m.GroupMemberStatus == GroupMemberStatus.Active )
                                            .Select( m => m.Person ) )
                                        {
                                            var phoneNumber = person.PhoneNumbers
                                                .Where( p => p.IsMessagingEnabled )
                                                .FirstOrDefault();
                                            if ( phoneNumber != null )
                                            {
                                                string smsNumber = phoneNumber.Number;
                                                if ( !string.IsNullOrWhiteSpace( phoneNumber.CountryCode ) )
                                                {
                                                    smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                                }
                                                recipients.Add( smsNumber );
                                            }
                                        }
                                    }
                                    break;
                                }
                        }
                    }
                }
            }
            else
            {
                if ( !string.IsNullOrWhiteSpace( toValue ) )
                {
                    recipients.Add( toValue );
                }
            }

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

            if ( recipients.Any() && fromId.HasValue && !string.IsNullOrWhiteSpace(message) )
            {
                var mergeFields = GetMergeFields( action );

                var channelData = new Dictionary<string, string>();
                channelData.Add( "FromValue", fromId.Value.ToString());
                channelData.Add( "Message", message.ResolveMergeFields( mergeFields ) );

                var channelEntity = EntityTypeCache.Read( Rock.SystemGuid.EntityType.COMMUNICATION_CHANNEL_SMS.AsGuid(), rockContext );
                if ( channelEntity != null )
                {
                    var channel = ChannelContainer.GetComponent( channelEntity.Name );
                    if ( channel != null && channel.IsActive )
                    {
                        var transport = channel.Transport;
                        if ( transport != null && transport.IsActive )
                        {
                            var appRoot = GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" );
                            transport.Send( channelData, recipients, appRoot, string.Empty );
                        }
                    }
                }
            }

            return true;
        }
Beispiel #59
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;
            Group group = null;
            string noteValue = string.Empty;
            string captionValue = string.Empty;
            bool isAlert = false;

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

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

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

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

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

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

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

            // get caption
            captionValue = GetAttributeValue( action, "Caption" );
            guid = captionValue.AsGuid();
            if ( guid.IsEmpty() )
            {
                captionValue = captionValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue( guid );

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

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

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

            // get alert type
            string isAlertString = GetAttributeValue( action, "IsAlert" );
            guid = isAlertString.AsGuid();
            if ( guid.IsEmpty() )
            {
                isAlert = isAlertString.AsBoolean();
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue( guid );

                if ( workflowAttributeValue != null )
                {
                    isAlert = workflowAttributeValue.AsBoolean();
                }
            }

            // get note type
            NoteTypeCache noteType = null;
            Guid noteTypeGuid = GetAttributeValue( action, "NoteType" ).AsGuid();

            if ( !noteTypeGuid.IsEmpty() )
            {
                noteType = NoteTypeCache.Read( noteTypeGuid, rockContext );

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

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

                if ( groupMembers.Count() > 0 )
                {
                    foreach ( var groupMember in groupMembers )
                    {
                        NoteService noteservice = new NoteService( rockContext );
                        Note note = new Note();
                        noteservice.Add( note );

                        note.NoteTypeId = noteType.Id;
                        note.Text = noteValue;
                        note.IsAlert = isAlert;
                        note.Caption = captionValue;
                        note.EntityId = groupMember.Id;

                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    errorMessages.Add( string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name ));
                }
            }

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

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

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

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

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

                    if ( groupGuid.HasValue )
                    {
                        group = new GroupService( rockContext ).Get( groupGuid.Value );
                        if ( group != null )
                        {
                            // use the group's grouptype's default group role if a group role wasn't specified
                            groupRoleId = group.GroupType.DefaultGroupRoleId;
                        }
                    }
                }
            }

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

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

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

            // Add Person to Group
            if ( !errorMessages.Any() )
            {
                var groupMemberService = new GroupMemberService( rockContext );
                var groupMember = new GroupMember();
                groupMember.PersonId = person.Id;
                groupMember.GroupId = group.Id;
                groupMember.GroupRoleId = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if ( groupMember.IsValid )
                {
                    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;
        }