/// <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.GetWorkflowAttributeValue(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.GetWorkflowAttributeValue(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.GetWorkflowAttributeValue(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);
        }
        /// <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.GetWorkflowAttributeValue(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.GetWorkflowAttributeValue(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);
        }
Example #3
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.GetWorkflowAttributeValue(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.GetWorkflowAttributeValue(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);
        }
Example #4
0
        /// <summary>
        /// Gets the lava resolved string using a text value or text from an attribute value.
        /// </summary>
        /// <param name="attributeKey">The attribute key.</param>
        /// <returns></returns>
        private string GetResolvedLava(string attributeKey)
        {
            var attributeGuid = GetAttributeValue(_action, attributeKey).AsGuidOrNull();

            // If it's just text then get the text and resolve the lava
            if (!attributeGuid.HasValue)
            {
                return(GetAttributeValue(_action, attributeKey).ResolveMergeFields(_mergeFields));
            }

            // If it's text within an attribute then resolve using that
            return(_action.GetWorkflowAttributeValue(attributeGuid.Value).ResolveMergeFields(_mergeFields));
        }
        /// <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.GetWorkflowAttributeValue(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.GetWorkflowAttributeValue(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);
        }
Example #6
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.GetWorkflowAttributeValue(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);
        }
Example #7
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var personAliasGuid = action.GetWorkflowAttributeValue(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);
        }
Example #8
0
        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.GetWorkflowAttributeValue(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);
        }
Example #9
0
        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.GetWorkflowAttributeValue(GetActionAttributeValue(action, "AttributeMatrix").AsGuid()).AsGuidOrNull();
            var itemGuid            = GetActionAttributeValue(action, "ItemGuid").ResolveMergeFields(GetMergeFields(action)).AsGuidOrNull();
            var itemAttributes      = GetActionAttributeValue(action, "ItemAttributes").AsDictionaryOrNull();

            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)
                {
                    item.LoadAttributes();

                    foreach (var attribute in item.Attributes)
                    {
                        if (itemAttributes.ContainsKey(attribute.Key))
                        {
                            item.SetAttributeValue(attribute.Key, itemAttributes[attribute.Key].ResolveMergeFields(GetMergeFields(action)));
                        }
                    }
                    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.GetWorkflowAttributeValue(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);
        }
Example #11
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

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

            if (guid.IsEmpty())
            {
                url = url.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                url = action.GetWorkflowAttributeValue(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");
            }
        }
Example #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>();

            var  itemListValue       = GetAttributeValue(action, "ItemList");
            Guid itemListValueAsGuid = itemListValue.AsGuid();

            if (!itemListValueAsGuid.IsEmpty())
            {
                var workflowAttributeValue = action.GetWorkflowAttributeValue(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);
        }
Example #13
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.Get(attributeGuid.Value);
                    if (attribute != null)
                    {
                        value = action.GetWorkflowAttributeValue(attributeGuid.Value);
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            if (attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.ENCRYPTED_TEXT.AsGuid()).Id)
                            {
                                value = Security.Encryption.DecryptString(value);
                            }
                            else if (attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.SSN.AsGuid()).Id)
                            {
                                value = Rock.Field.Types.SSNFieldType.UnencryptAndClean(value);
                            }
                        }
                    }
                }
            }

            return(value);
        }
Example #14
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.GetWorkflowAttributeValue(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");
        }
Example #15
0
        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.GetWorkflowAttributeValue(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);
        }
Example #16
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.GetWorkflowAttributeValue(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);
        }
        /// <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.GetWorkflowAttributeValue(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 = WorkflowActivityTypeCache.Get(workflowActivityGuid);

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

            var entityType = EntityTypeCache.Get(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);
        }
Example #18
0
        /// <summary>
        /// Gets the group role attribute value Guid.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="attributeKey">The group role attribute key.</param>
        /// <returns></returns>
        private Guid?GetGroupRoleValueGuid(WorkflowAction action, string attributeKey)
        {
            Guid?groupRoleGuid = null;

            Guid?groupRoleAttributeGuid = GetAttributeValue(action, attributeKey).AsGuidOrNull();

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

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

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

            if (!groupAttributeGuid.IsEmpty())
            {
                Guid?groupGuid = action.GetWorkflowAttributeValue(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.Get(leaderGuid, rockContext);
                            if (personAttribute != null)
                            {
                                // If this is a person type attribute
                                if (personAttribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                                {
                                    SetWorkflowAttributeValue(action, leaderGuid, groupLeader.PrimaryAlias.Guid.ToString());
                                }
                                else if (personAttribute.FieldTypeId == FieldTypeCache.Get(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);
        }
Example #20
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var personAliasGuid = action.GetWorkflowAttributeValue(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);
        }
        /// <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.GetWorkflowAttributeValue(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 = WorkflowActivityTypeCache.Get(workflowActivityGuid);

            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);
        }
Example #22
0
        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.GetWorkflowAttributeValue(GetAttributeValue(action, attributeAttributeKey).AsGuid()), valueConverterData));
        }
Example #23
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())
            {
                return(null);
            }

            var attributePerson = AttributeCache.Get(guidPersonAttribute, rockContext);

            if (attributePerson == null)
            {
                return(null);
            }

            string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute);

            if (string.IsNullOrWhiteSpace(attributePersonValue))
            {
                return(null);
            }

            if (attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
            {
                errorMessages.Add($"The attribute used for {key} to provide the person was not of type 'Person'.");
                return(null);
            }

            Guid personAliasGuid = attributePersonValue.AsGuid();

            if (personAliasGuid.IsEmpty())
            {
                errorMessages.Add($"Person could not be found for selected value ('{guidPersonAttribute}')!");
                return(null);
            }

            PersonAliasService personAliasService = new PersonAliasService(rockContext);

            return(personAliasService.Queryable().AsNoTracking()
                   .Where(a => a.Guid.Equals(personAliasGuid))
                   .Select(a => a.Person)
                   .FirstOrDefault());
        }
Example #24
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            SignatureDocumentService signatureDocumentService = new SignatureDocumentService(rockContext);
            BinaryFileService        binaryfileService        = new BinaryFileService(rockContext);
            PersonAliasService       personAliasService       = new PersonAliasService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var        mergeFields        = GetMergeFields(action);
            int        documentTemplateId = GetAttributeValue(action, "DocumentTemplateId", true).AsInteger();
            Guid       documentGuid       = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "Document").AsGuid()).AsGuid();
            BinaryFile binaryFile         = binaryfileService.Get(documentGuid);
            string     documentKey        = GetAttributeValue(action, "DocumentKey", true).ResolveMergeFields(mergeFields);
            string     documentName       = GetAttributeValue(action, "DocumentName", true).ResolveMergeFields(mergeFields);
            Guid       assignedTo         = GetAttributeValue(action, "AssignedTo", true).AsGuid();
            Guid       appliesTo          = GetAttributeValue(action, "AppliesTo", true).AsGuid();
            Guid       signedBy           = GetAttributeValue(action, "SignedBy", true).AsGuid();

            if (binaryFile != null)
            {
                // Create the signature document
                Rock.Model.SignatureDocument document = new Rock.Model.SignatureDocument();
                document.AssignedToPersonAliasId = personAliasService.Get(assignedTo).Id;
                document.AppliesToPersonAliasId  = personAliasService.Get(appliesTo).Id;
                document.SignedByPersonAliasId   = personAliasService.Get(signedBy).Id;
                document.Name         = documentName;
                document.DocumentKey  = documentKey;
                document.BinaryFileId = binaryFile.Id;
                document.SignatureDocumentTemplateId = documentTemplateId;
                document.LastInviteDate = RockDateTime.Now;
                document.LastStatusDate = RockDateTime.Now;
                document.Status         = SignatureDocumentStatus.Signed;

                // Add the signature document to the service
                signatureDocumentService.Add(document);
            }

            return(true);
        }
Example #25
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var             scheduleGuid    = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "ScheduleAttribute").AsGuid()).AsGuid();
            ScheduleService scheduleService = new ScheduleService(rockContext);
            var             schedule        = scheduleService.Get(scheduleGuid);

            if (schedule != null)
            {
                // Now store the target attribute
                var targetAttribute = AttributeCache.Get(GetActionAttributeValue(action, "DateTimeAttribute").AsGuid(), rockContext);
                if (targetAttribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                {
                    action.Activity.Workflow.SetAttributeValue(targetAttribute.Key, schedule.GetNextStartDateTime(Rock.RockDateTime.Now).ToString());
                }
                else if (targetAttribute.EntityTypeId == new WorkflowActivity().TypeId)
                {
                    action.Activity.SetAttributeValue(targetAttribute.Key, schedule.GetNextStartDateTime(Rock.RockDateTime.Now).ToString());
                }
            }
            return(true);
        }
Example #26
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var cacheTagsAttributeValue = GetActionAttributeValue(action, "CacheTags");

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

            if (cacheTagsGuid != null)
            {
                cacheTags = action.GetWorkflowAttributeValue(cacheTagsGuid.Value);
            }
            else
            {
                //the value is the cachetags
                cacheTags = cacheTagsAttributeValue;
            }
            RockCache.RemoveForTags(cacheTags);
            action.AddLogEntry("Cleared cache tags: " + cacheTags);

            return(true);
        }
Example #27
0
        private bool GetRemovePersonFromCurrentFamilyValue(WorkflowAction action)
        {
            bool removePersonFromCurrentFamily = false;
            // get Remove Person From Current Family
            string removePersonFromCurrentFamilyString = GetAttributeValue(action, AttributeKey.RemovePersonFromCurrentFamily);
            var    guid = removePersonFromCurrentFamilyString.AsGuid();

            if (guid.IsEmpty())
            {
                removePersonFromCurrentFamily = removePersonFromCurrentFamilyString.AsBoolean();
            }
            else
            {
                var workflowAttributeValue = action.GetWorkflowAttributeValue(guid);

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

            return(removePersonFromCurrentFamily);
        }
Example #28
0
        private Person GetPersonFromWorkflowAttribute(RockContext rockContext, WorkflowAction action, Guid guidPersonAttribute)
        {
            Person person = null;

            var attributePerson = AttributeCache.Get(guidPersonAttribute, rockContext);

            if (attributePerson != null)
            {
                string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute);
                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();
                    }
                }
            }

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

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

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

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

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

                                if (devices.Count == 0)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person does not have devices that support notifications", true);
                                }
                                else
                                {
                                    var person    = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    var recipient = new RockPushMessageRecipient(person, deviceIds, mergeFields);
                                    recipients.Add(recipient);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }

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

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

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

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    List <string> devices = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(p => p.PersonAliasId.HasValue && p.PersonAliasId == person.PrimaryAliasId && p.NotificationsEnabled && !string.IsNullOrEmpty(p.DeviceRegistrationId))
                                                            .Select(p => p.DeviceRegistrationId)
                                                            .ToList();

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

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

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

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

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

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

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

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

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var pushMessage = new RockPushMessage();
                pushMessage.SetRecipients(recipients);
                pushMessage.Title   = title;
                pushMessage.Message = message;
                pushMessage.Sound   = sound;
                pushMessage.Send();
            }

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

            string updateValue = GetAttributeValue(action, "Value");
            Guid?  valueGuid   = updateValue.AsGuidOrNull();

            if (valueGuid.HasValue)
            {
                updateValue = action.GetWorkflowAttributeValue(valueGuid.Value);

                // if the value is null no workflow attribute was found for that guid so use the actual guid as the value
                if (updateValue == null)
                {
                    updateValue = valueGuid.Value.ToString();
                }
            }
            else
            {
                updateValue = updateValue.ResolveMergeFields(GetMergeFields(action));
            }

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

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string value = GetAttributeValue(action, "Person");
                    guid = value.AsGuid();
                    if (!guid.IsEmpty())
                    {
                        var attributePerson = AttributeCache.Get(guid, rockContext);
                        if (attributePerson != null)
                        {
                            string attributePersonValue = action.GetWorkflowAttributeValue(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);

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