Exemple #1
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                WorkflowTypeCache workflowType = null;
                if (WorkflowTypeGuid.HasValue)
                {
                    workflowType = WorkflowTypeCache.Read(WorkflowTypeGuid.Value);
                }

                if (workflowType == null && WorkflowTypeId.HasValue)
                {
                    workflowType = WorkflowTypeCache.Read(WorkflowTypeId.Value);
                }

                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    var workflow = Rock.Model.Workflow.Activate(workflowType, WorkflowName);

                    foreach (var keyVal in WorkflowAttributeValues)
                    {
                        workflow.SetAttributeValue(keyVal.Key, keyVal.Value);
                    }

                    List <string> workflowErrors;
                    new Rock.Model.WorkflowService(rockContext).Process(workflow, GetEntity(), out workflowErrors);
                }
            }
        }
Exemple #2
0
        private void LoadWorkflowType()
        {
            if (_rockContext == null)
            {
                _rockContext = new RockContext();
            }

            if (_workflowService == null)
            {
                _workflowService = new WorkflowService(_rockContext);
            }

            // Get the workflow type id (initial page request)
            if (!WorkflowTypeId.HasValue)
            {
                // Get workflow type set by attribute value
                Guid workflowTypeguid = GetAttributeValue("WorkflowType").AsGuid();
                if (!workflowTypeguid.IsEmpty())
                {
                    _workflowType = WorkflowTypeCache.Read(workflowTypeguid);
                }

                // If an attribute value was not provided, check for query/route value
                if (_workflowType != null)
                {
                    WorkflowTypeId = _workflowType.Id;
                }
            }

            // Get the workflow type
            if (_workflowType == null && WorkflowTypeId.HasValue)
            {
                _workflowType = WorkflowTypeCache.Read(WorkflowTypeId.Value);
            }
        }
Exemple #3
0
        /// <summary>
        /// Processes the specified <see cref="Rock.Model.Workflow" />
        /// </summary>
        /// <param name="workflow">The <see cref="Rock.Model.Workflow" /> instance to process.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">A <see cref="System.Collections.Generic.List{String}" /> that contains any error messages that were returned while processing the <see cref="Rock.Model.Workflow" />.</param>
        /// <returns></returns>
        public bool Process(Workflow workflow, object entity, out List <string> errorMessages)
        {
            var workflowType = WorkflowTypeCache.Read(workflow.WorkflowTypeId);

            if (workflowType != null && (workflowType.IsActive ?? true))
            {
                var rockContext = (RockContext)this.Context;

                if (workflow.IsPersisted)
                {
                    workflow.IsProcessing = true;
                    rockContext.SaveChanges();
                }

                bool result = workflow.ProcessActivities(rockContext, entity, out errorMessages);

                if (workflow.Status == "DeleteWorkflowNow")
                {
                    if (workflow.Id > 0)
                    {
                        rockContext.SaveChanges();
                        Delete(workflow);
                        rockContext.SaveChanges();
                    }
                    result = true;
                }
                else
                {
                    if (workflow.IsPersisted || workflowType.IsPersisted)
                    {
                        if (workflow.Id == 0)
                        {
                            Add(workflow);
                        }

                        rockContext.SaveChanges();

                        workflow.SaveAttributeValues(rockContext);
                        foreach (var activity in workflow.Activities)
                        {
                            activity.SaveAttributeValues(rockContext);
                        }

                        workflow.IsProcessing = false;
                        rockContext.SaveChanges();
                    }
                }

                return(result);
            }

            else
            {
                errorMessages = new List <string> {
                    "Workflow Type is invalid or not active!"
                };
                return(false);
            }
        }
Exemple #4
0
        /// <summary>
        /// Activates and processes a workflow activity.  If the workflow has not yet been activated, it will
        /// also be activated
        /// </summary>
        /// <param name="activityName">Name of the activity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        protected bool ProcessActivity(string activityName, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?guid = GetAttributeValue("WorkflowType").AsGuidOrNull();

            if (guid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var workflowService = new WorkflowService(rockContext);

                    var workflowType = WorkflowTypeCache.Read(guid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        if (CurrentWorkflow == null)
                        {
                            CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext);

                            if (IsOverride)
                            {
                                CurrentWorkflow.SetAttributeValue("Override", "True");
                            }
                        }

                        var activityType = workflowType.ActivityTypes.Where(a => a.Name == activityName).FirstOrDefault();
                        if (activityType != null)
                        {
                            WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                            if (workflowService.Process(CurrentWorkflow, CurrentCheckInState, out errorMessages))
                            {
                                // Keep workflow active for continued processing
                                CurrentWorkflow.CompletedDateTime = null;

                                return(true);
                            }
                        }
                        else
                        {
                            errorMessages.Add(string.Format("Workflow type does not have a '{0}' activity type", activityName));
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Workflow Type");
                    }
                }
            }

            return(false);
        }
Exemple #5
0
        public static Workflow Activate(WorkflowType workflowType, string name, RockContext rockContext)
        {
            if (workflowType != null)
            {
                var workflowTypeCache = WorkflowTypeCache.Read(workflowType.Id);
                var workflow          = Activate(workflowTypeCache, name, rockContext);
                if (workflow != null)
                {
                    workflow.WorkflowType = workflowType;
                }
                return(workflow);
            }

            return(null);
        }
Exemple #6
0
        private void LaunchWorkflow(Person person)
        {
            using (var rockContext = new RockContext())
            {
                var workflowType = WorkflowTypeCache.Read(_workflowTypeGuid.Value);
                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    var workflowService = new WorkflowService(rockContext);
                    var workflow        = Rock.Model.Workflow.Activate(workflowType, person.FullName, rockContext);
                    workflowService.Add(workflow);
                    rockContext.SaveChanges();

                    workflow.SetAttributeValue("Person", person.Guid);
                    workflow.SaveAttributeValues();
                }
            }
        }
Exemple #7
0
        private void LaunchWorkflow(String firstName, String lastName, String email)
        {
            using (var rockContext = new RockContext())
            {
                var workflowType = WorkflowTypeCache.Read(_workflowTypeGuid.Value);
                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    var workflowService = new WorkflowService(rockContext);
                    var workflow        = Rock.Model.Workflow.Activate(workflowType, string.Format("{0} {1}", firstName, lastName), rockContext);
                    workflowService.Add(workflow);
                    rockContext.SaveChanges();

                    workflow.SetAttributeValue("FirstName", firstName);
                    workflow.SetAttributeValue("LastName", lastName);
                    workflow.SetAttributeValue("Email", email);
                    workflow.SaveAttributeValues();
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Launches the workflow.
        /// </summary>
        /// <param name="workflowTypeGuid">The workflow type unique identifier.</param>
        /// <param name="family">The family.</param>
        private void LaunchWorkflow(Guid workflowTypeGuid, Group family)
        {
            int adultRoleId = GroupTypeCache.Read(SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Roles.Where(r => r.Guid == SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).FirstOrDefault().Id;

            var headOfHouse = family.Members.Where(m => m.GroupRoleId == adultRoleId).OrderBy(m => m.Person.Gender).FirstOrDefault();

            // don't launch a workflow if no adult is present in the family
            if (headOfHouse != null && headOfHouse.Person != null && headOfHouse.Person.PrimaryAlias != null)
            {
                var spouse = family.Members.Where(m => m.GroupRoleId == adultRoleId && m.PersonId != headOfHouse.Person.Id).FirstOrDefault();

                using (var rockContext = new RockContext())
                {
                    var workflowType = WorkflowTypeCache.Read(workflowTypeGuid);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        var workflowService = new WorkflowService(rockContext);
                        var workflow        = Rock.Model.Workflow.Activate(workflowType, headOfHouse.Person.FullName, rockContext);
                        workflowService.Add(workflow);
                        rockContext.SaveChanges();

                        workflow.SetAttributeValue("Family", family.Guid);
                        workflow.SetAttributeValue("HeadOfHouse", headOfHouse.Person.PrimaryAlias.Guid);

                        if (family.Campus != null)
                        {
                            workflow.SetAttributeValue("Campus", family.Campus.Guid);
                        }

                        if (spouse != null && spouse.Person != null && spouse.Person.PrimaryAlias != null)
                        {
                            workflow.SetAttributeValue("Spouse", spouse.Person.PrimaryAlias.Guid);
                        }

                        workflow.SaveAttributeValues();
                    }
                }
            }
        }
        /// <summary>
        /// Starts the workflow if one was defined in the block setting.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="rockContext">The rock context.</param>
        private void StartWorkflow(PrayerRequest prayerRequest, RockContext rockContext)
        {
            Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                var workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    try
                    {
                        var           workflow = Workflow.Activate(workflowType, prayerRequest.Name);
                        List <string> workflowErrors;
                        new WorkflowService(rockContext).Process(workflow, prayerRequest, out workflowErrors);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var workflowTypeGuid = GetAttributeValue(action, "WorkflowType").AsGuidOrNull();
            var workflowTypeFromAttributeGuid = GetAttributeValue(action, "WorkflowTypefromAttribute", true).AsGuidOrNull();
            var workflowName = GetAttributeValue(action, "WorkflowName");

            WorkflowTypeCache workflowType = null;

            if (workflowTypeGuid.HasValue)
            {
                workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
            }
            else if (workflowTypeFromAttributeGuid.HasValue)
            {
                workflowType = WorkflowTypeCache.Read(workflowTypeFromAttributeGuid.Value);
            }

            if (workflowType == null)
            {
                errorMessages.Add("Workflow type is required");
                return(false);
            }

            if (string.IsNullOrEmpty(workflowName))
            {
                errorMessages.Add("Workflow name is required");
                return(false);
            }

            if (!(workflowType.IsActive ?? true))
            {
                errorMessages.Add(string.Format("Workflow type {0} is not active", workflowType));
                return(true);
            }

            Dictionary <string, string> sourceKeyMap = null;
            var workflowAttributeKeys = GetAttributeValue(action, "WorkflowAttributeKey");

            if (!string.IsNullOrWhiteSpace(workflowAttributeKeys))
            {
                // TODO Find a way upstream to stop an additional being appended to the value
                sourceKeyMap = workflowAttributeKeys.AsDictionaryOrNull();
            }

            sourceKeyMap = sourceKeyMap ?? new Dictionary <string, string>();

            var workflow = Rock.Model.Workflow.Activate(workflowType, workflowName);

            workflow.LoadAttributes(rockContext);

            foreach (var keyPair in sourceKeyMap)
            {
                // Does the source key exist as an attribute in the source workflow?
                if (action.Activity.Workflow.Attributes.ContainsKey(keyPair.Key))
                {
                    if (workflow.Attributes.ContainsKey(keyPair.Value))
                    {
                        var value = action.Activity.Workflow.AttributeValues[keyPair.Key].Value;
                        workflow.SetAttributeValue(keyPair.Value, value);
                    }
                    else
                    {
                        errorMessages.Add(string.Format("'{0}' is not an attribute key in the activated workflow: '{1}'", keyPair.Value, workflow.Name));
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("'{0}' is not an attribute key in this workflow: '{1}'", keyPair.Key, action.Activity.Workflow.Name));
                }
            }

            List <string> workflowErrorMessages = new List <string>();

            new Rock.Model.WorkflowService(rockContext).Process(workflow, out workflowErrorMessages);
            errorMessages.AddRange(workflowErrorMessages);

            return(true);
        }
        protected void lbProfileNext_Click(object sender, EventArgs e)
        {
            // setup merge fields
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("PersonId", hfPersonId.Value);
            mergeFields.Add("FirstName", tbFirstName.Text);
            mergeFields.Add("LastName", tbLastName.Text);
            mergeFields.Add("StreetAddress", acAddress.Street1);
            mergeFields.Add("City", acAddress.City);
            mergeFields.Add("State", acAddress.State);
            mergeFields.Add("PostalCode", acAddress.PostalCode);
            mergeFields.Add("Country", acAddress.Country);
            mergeFields.Add("Email", tbEmail.Text);
            mergeFields.Add("HomePhone", pnbHomePhone.Text);
            mergeFields.Add("MobilePhone", pnbHomePhone.Text);
            mergeFields.Add("BirthDate", dpBirthdate.Text);
            mergeFields.Add("OtherUpdates", tbOtherUpdates.Text);

            // if an email was provided email results
            RockContext rockContext = new RockContext();

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("UpdateEmail")))
            {
                var receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("UpdateEmail")));

                if (receiptEmail != null && receiptEmail.To.IsNotNullOrWhitespace())
                {
                    var errorMessages = new List <string>();
                    var message       = new RockEmailMessage(receiptEmail);
                    foreach (var recipient in message.GetRecipientData())
                    {
                        recipient.MergeFields = mergeFields;
                    }
                    message.Send(out errorMessages);
                }
            }

            // launch workflow if configured
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("WorkflowType")))
            {
                var workflowService = new WorkflowService(rockContext);
                var workflowType    = WorkflowTypeCache.Read(new Guid(GetAttributeValue("WorkflowType")));

                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    var workflow = Rock.Model.Workflow.Activate(workflowType, "Kiosk Update Info");

                    // set attributes
                    workflow.SetAttributeValue("PersonId", hfPersonId.Value);
                    workflow.SetAttributeValue("FirstName", tbFirstName.Text);
                    workflow.SetAttributeValue("LastName", tbLastName.Text);
                    workflow.SetAttributeValue("StreetAddress", acAddress.Street1);
                    workflow.SetAttributeValue("City", acAddress.City);
                    workflow.SetAttributeValue("State", acAddress.State);
                    workflow.SetAttributeValue("PostalCode", acAddress.PostalCode);
                    workflow.SetAttributeValue("Country", acAddress.Country);
                    workflow.SetAttributeValue("Email", tbEmail.Text);
                    workflow.SetAttributeValue("HomePhone", pnbHomePhone.Text);
                    workflow.SetAttributeValue("MobilePhone", pnbHomePhone.Text);
                    workflow.SetAttributeValue("BirthDate", dpBirthdate.Text);
                    workflow.SetAttributeValue("OtherUpdates", tbOtherUpdates.Text);

                    // lauch workflow
                    List <string> workflowErrors;
                    workflowService.Process(workflow, out workflowErrors);
                }
            }

            HidePanels();
            pnlComplete.Visible = true;

            lCompleteMessage.Text = GetAttributeValue("CompleteMessageLava").ResolveMergeFields(mergeFields);
        }
Exemple #12
0
        /// <summary>
        /// Handles a recieved message
        /// </summary>
        /// <param name="toPhone">To phone.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="message">The message.</param>
        /// <param name="response">The response.</param>
        public static void MessageRecieved(string toPhone, string fromPhone, string message, out string response)
        {
            response = string.Empty;
            bool foundWorkflow = false;

            // get TextToWorkflow defined types for this number
            var definedType = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.TEXT_TO_WORKFLOW.AsGuid());

            if (definedType != null && definedType.DefinedValues != null && definedType.DefinedValues.Any())
            {
                var smsWorkflows = definedType.DefinedValues.Where(v => v.Value.AsNumeric() == toPhone.AsNumeric()).OrderBy(v => v.Order).ToList();

                // iterate through workflows looking for a keyword match
                foreach (DefinedValueCache dvWorkflow in smsWorkflows)
                {
                    string keywordExpression  = dvWorkflow.GetAttributeValue("KeywordExpression");
                    string workflowAttributes = dvWorkflow.GetAttributeValue("WorkflowAttributes");
                    string nameTemplate       = dvWorkflow.GetAttributeValue("WorkflowNameTemplate");

                    // if not keyword expression add wildcard expression
                    if (string.IsNullOrWhiteSpace(keywordExpression))
                    {
                        keywordExpression = ".*";
                    }

                    // if the keyword is just a * then replace it
                    if (keywordExpression == "*")
                    {
                        keywordExpression = ".*";
                    }

                    // Prefix keyword with start-of-string assertion (input needs to start with selected expression)
                    if (!keywordExpression.StartsWith("^"))
                    {
                        keywordExpression = $"^{keywordExpression}";
                    }

                    if (!string.IsNullOrWhiteSpace(keywordExpression))
                    {
                        Match match = Regex.Match(message, keywordExpression, RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            foundWorkflow = true;

                            var workflowTypeGuid = dvWorkflow.GetAttributeValue("WorkflowType").AsGuidOrNull();
                            if (workflowTypeGuid.HasValue)
                            {
                                // launch workflow
                                using (var rockContext = new Data.RockContext())
                                {
                                    var personService      = new PersonService(rockContext);
                                    var groupMemberService = new GroupMemberService(rockContext);

                                    var workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                                    if (workflowType != null)
                                    {
                                        // Activate a new workflow
                                        var workflow = Rock.Model.Workflow.Activate(workflowType, "Request from " + (fromPhone ?? "??"), rockContext);

                                        // give preference to people with the phone in the mobile phone type
                                        // first look for a person with the phone number as a mobile phone order by family role then age
                                        var mobilePhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                                        var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                                        // Get all people phone number
                                        var peopleWithMobileNumber = personService.Queryable()
                                                                     .Where(p =>
                                                                            p.PhoneNumbers.Any(n =>
                                                                                               (n.CountryCode + n.Number) == fromPhone.Replace("+", "") &&
                                                                                               n.NumberTypeValueId == mobilePhoneType.Id)
                                                                            )
                                                                     .Select(p => p.Id);

                                        // Find first person ordered by role (adult first), then by birthdate (oldest first)
                                        var fromPerson = groupMemberService.Queryable()
                                                         .Where(m =>
                                                                m.Group.GroupTypeId == familyGroupType.Id &&
                                                                peopleWithMobileNumber.Contains(m.PersonId))
                                                         .OrderBy(m => m.GroupRole.Order)
                                                         .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue)
                                                         .Select(m => m.Person)
                                                         .FirstOrDefault();

                                        // if no match then look for the phone in any phone type ordered by family role then age
                                        if (fromPerson == null)
                                        {
                                            var peopleWithAnyNumber = personService.Queryable()
                                                                      .Where(p =>
                                                                             p.PhoneNumbers.Any(n =>
                                                                                                (n.CountryCode + n.Number) == fromPhone.Replace("+", "") &&
                                                                                                n.NumberTypeValueId == mobilePhoneType.Id)
                                                                             )
                                                                      .Select(p => p.Id);

                                            fromPerson = groupMemberService.Queryable()
                                                         .Where(m =>
                                                                m.Group.GroupTypeId == familyGroupType.Id &&
                                                                peopleWithMobileNumber.Contains(m.PersonId))
                                                         .OrderBy(m => m.GroupRole.Order)
                                                         .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue)
                                                         .Select(m => m.Person).FirstOrDefault();
                                        }

                                        // Set initiator
                                        if (fromPerson != null)
                                        {
                                            workflow.InitiatorPersonAliasId = fromPerson.PrimaryAliasId;
                                        }

                                        // create merge object
                                        var formattedPhoneNumber = PhoneNumber.CleanNumber(PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), fromPhone));

                                        List <string> matchGroups = new List <string>();
                                        foreach (var matchItem in match.Groups)
                                        {
                                            matchGroups.Add(matchItem.ToString());
                                        }

                                        Dictionary <string, object> mergeValues = new Dictionary <string, object>();
                                        mergeValues.Add("FromPhone", formattedPhoneNumber);
                                        mergeValues.Add("ToPhone", toPhone);
                                        mergeValues.Add("MessageBody", message);
                                        mergeValues.Add("MatchedGroups", matchGroups);
                                        mergeValues.Add("ReceivedTime", RockDateTime.Now.ToString("HH:mm:ss"));
                                        mergeValues.Add("ReceivedDate", RockDateTime.Now.ToShortDateString());
                                        mergeValues.Add("ReceivedDateTime", RockDateTime.Now.ToString("o"));
                                        mergeValues.Add("FromPerson", fromPerson);

                                        // add phone number attribute
                                        workflow.SetAttributeValue("FromPhone", fromPhone);

                                        // set workflow attributes
                                        string[] attributes = workflowAttributes.Split('|');
                                        foreach (string attribute in attributes)
                                        {
                                            if (attribute.Contains('^'))
                                            {
                                                string[] settings = attribute.Split('^');
                                                workflow.SetAttributeValue(settings[0], settings[1].ResolveMergeFields(mergeValues));
                                            }
                                        }

                                        // set workflow name
                                        string name = nameTemplate.ResolveMergeFields(mergeValues);
                                        if (name.IsNotNullOrWhitespace())
                                        {
                                            workflow.Name = name;
                                        }

                                        // process the workflow
                                        List <string> workflowErrors;
                                        new Rock.Model.WorkflowService(rockContext).Process(workflow, out workflowErrors);

                                        // check to see if there is a response to return
                                        string responseAttribute = workflow.GetAttributeValue("SMSResponse");
                                        if (responseAttribute != null && !string.IsNullOrWhiteSpace(responseAttribute))
                                        {
                                            response = responseAttribute;
                                        }
                                    }
                                    else
                                    {
                                        response = "This keyword is no longer valid.";
                                    }
                                }
                            }
                            else
                            {
                                response = "No response could be provided for this keyword.";
                            }


                            // once we find one match stop processing
                            break;
                        }
                    }
                }

                if (!foundWorkflow)
                {
                    response = "The keyword you provided was not valid. ";
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            if (_group != null && _occurrence != null)
            {
                var rockContext        = new RockContext();
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                bool dateAdjusted = false;

                DateTime startDate = _occurrence.Date;

                // If this is a manuall entered occurrence, check to see if date was changed
                if (!_occurrence.ScheduleId.HasValue)
                {
                    DateTime?originalDate = PageParameter("Date").AsDateTime();
                    if (originalDate.HasValue && originalDate.Value.Date != startDate.Date)
                    {
                        startDate    = originalDate.Value.Date;
                        dateAdjusted = true;
                    }
                }
                DateTime endDate = startDate.AddDays(1);

                var existingAttendees = attendanceService
                                        .Queryable("PersonAlias")
                                        .Where(a =>
                                               a.GroupId == _group.Id &&
                                               a.LocationId == _occurrence.LocationId &&
                                               a.ScheduleId == _occurrence.ScheduleId &&
                                               a.StartDateTime >= startDate &&
                                               a.StartDateTime < endDate);

                if (dateAdjusted)
                {
                    foreach (var attendee in existingAttendees)
                    {
                        attendee.StartDateTime = _occurrence.Date;
                    }
                }

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    int?campusId = locationService.GetCampusIdForLocation(_occurrence.LocationId);
                    if (!campusId.HasValue)
                    {
                        campusId = _group.CampusId;
                    }
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Read(bddlCampus.SelectedValueAsInt() ?? 0);
                        if (campus != null)
                        {
                            campusId = campus.Id;
                        }
                    }

                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend   = null;
                            attendance.DidNotOccur = true;
                        }
                    }

                    foreach (var attendee in _attendees)
                    {
                        var attendance = existingAttendees
                                         .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                         .FirstOrDefault();

                        if (attendance == null)
                        {
                            int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                            if (personAliasId.HasValue)
                            {
                                attendance               = new Attendance();
                                attendance.GroupId       = _group.Id;
                                attendance.ScheduleId    = _group.ScheduleId;
                                attendance.PersonAliasId = personAliasId;
                                attendance.StartDateTime = _occurrence.Date.Date.Add(_occurrence.StartTime);
                                attendance.LocationId    = _occurrence.LocationId;
                                attendance.CampusId      = campusId;
                                attendance.ScheduleId    = _occurrence.ScheduleId;

                                // check that the attendance record is valid
                                cvAttendance.IsValid = attendance.IsValid;
                                if (!cvAttendance.IsValid)
                                {
                                    cvAttendance.ErrorMessage = attendance.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                                    return;
                                }

                                attendanceService.Add(attendance);
                            }
                        }

                        if (attendance != null)
                        {
                            if (cbDidNotMeet.Checked)
                            {
                                attendance.DidAttend   = null;
                                attendance.DidNotOccur = true;
                            }
                            else
                            {
                                attendance.DidAttend   = attendee.Attended;
                                attendance.DidNotOccur = null;
                            }
                        }
                    }
                }

                if (_occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Flush(_occurrence.LocationId.Value);
                }

                rockContext.SaveChanges();

                Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.Date.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }

                var qryParams = new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                };

                var groupTypeIds = PageParameter("GroupTypeIds");
                if (!string.IsNullOrWhiteSpace(groupTypeIds))
                {
                    qryParams.Add("GroupTypeIds", groupTypeIds);
                }

                NavigateToParentPage(qryParams);
            }
        }
Exemple #14
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var        rockContext = new RockContext();
            JobDataMap dataMap     = context.JobDetail.JobDataMap;

            // Get the details for the email that we'll be sending out.
            Guid?systemEmailGuid            = dataMap.GetString("ExpiringCreditCardEmail").AsGuidOrNull();
            SystemEmailService emailService = new SystemEmailService(rockContext);
            SystemEmail        systemEmail  = null;

            if (systemEmailGuid.HasValue)
            {
                systemEmail = emailService.Get(systemEmailGuid.Value);
            }

            // Fetch the configured Workflow once if one was set, we'll use it later.
            Guid?workflowGuid = dataMap.GetString("Workflow").AsGuidOrNull();
            WorkflowTypeCache workflowType = null;
            var workflowService            = new WorkflowService(rockContext);

            if (workflowGuid != null)
            {
                workflowType = WorkflowTypeCache.Read(workflowGuid.Value);
            }

            var qry = new FinancialScheduledTransactionService(rockContext)
                      .Queryable("ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue")
                      .Where(t => t.IsActive && t.FinancialPaymentDetail.ExpirationMonthEncrypted != null &&
                             (t.EndDate == null || t.EndDate > DateTime.Now))
                      .AsNoTracking();

            // Get the current month and year
            DateTime now     = DateTime.Now;
            int      month   = now.Month;
            int      year    = now.Year;
            int      counter = 0;

            foreach (var transaction in qry)
            {
                int?expirationMonthDecrypted = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationMonthEncrypted).AsIntegerOrNull();
                int?expirationYearDecrypted  = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationYearEncrypted).AsIntegerOrNull();
                if (expirationMonthDecrypted.HasValue && expirationMonthDecrypted.HasValue)
                {
                    string acctNum = string.Empty;

                    if (!string.IsNullOrEmpty(transaction.FinancialPaymentDetail.AccountNumberMasked) && transaction.FinancialPaymentDetail.AccountNumberMasked.Length >= 4)
                    {
                        acctNum = transaction.FinancialPaymentDetail.AccountNumberMasked.Substring(transaction.FinancialPaymentDetail.AccountNumberMasked.Length - 4);
                    }

                    int warningYear  = expirationYearDecrypted.Value;
                    int warningMonth = expirationMonthDecrypted.Value - 1;
                    if (warningMonth == 0)
                    {
                        warningYear -= 1;
                        warningMonth = 12;
                    }

                    string warningDate        = warningMonth.ToString() + warningYear.ToString();
                    string currentMonthString = month.ToString() + year.ToString();

                    if (warningDate == currentMonthString)
                    {
                        // as per ISO7813 https://en.wikipedia.org/wiki/ISO/IEC_7813
                        var expirationDate = string.Format("{0:D2}/{1:D2}", expirationMonthDecrypted, expirationYearDecrypted);

                        var recipients  = new List <RecipientData>();
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        var person      = transaction.AuthorizedPersonAlias.Person;
                        mergeFields.Add("Person", person);
                        mergeFields.Add("Card", acctNum);
                        mergeFields.Add("Expiring", expirationDate);
                        recipients.Add(new RecipientData(person.Email, mergeFields));

                        var emailMessage = new RockEmailMessage(systemEmail.Guid);
                        emailMessage.SetRecipients(recipients);
                        emailMessage.Send();

                        // Start workflow for this person
                        if (workflowType != null)
                        {
                            Dictionary <string, string> attributes = new Dictionary <string, string>();
                            attributes.Add("Person", transaction.AuthorizedPersonAlias.Guid.ToString());
                            attributes.Add("Card", acctNum);
                            attributes.Add("Expiring", expirationDate);
                            StartWorkflow(workflowService, workflowType, attributes, string.Format("{0} (scheduled transaction Id: {1})", person.FullName, transaction.Id));
                        }

                        counter++;
                    }
                }
            }

            context.Result = string.Format("{0} scheduled credit card transactions were examined with {1} notice(s) sent.", qry.Count(), counter);
        }
        /// <summary>
        /// Handles the Click event of the btnRegister control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            // Check _isValidSettings in case the form was showing and they clicked the visible register button.
            if (Page.IsValid && _isValidSettings)
            {
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);

                Person        person       = null;
                Person        spouse       = null;
                Group         family       = null;
                GroupLocation homeLocation = null;
                bool          isMatch      = false;

                var changes       = new List <string>();
                var spouseChanges = new List <string>();
                var familyChanges = new List <string>();

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if (_autoFill)
                {
                    if (CurrentPerson != null &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) &&
                        tbLastName.Text.Trim().Equals(CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        person  = personService.Get(CurrentPerson.Id);
                        isMatch = true;
                    }
                }

                // Try to find person by name/email
                if (person == null)
                {
                    var matches = personService.GetByMatch(tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim());
                    if (matches.Count() == 1)
                    {
                        person  = matches.First();
                        isMatch = true;
                    }
                }

                // Check to see if this is a new person
                if (person == null)
                {
                    // If so, create the person and family record for the new person
                    person                         = new Person();
                    person.FirstName               = tbFirstName.Text.Trim();
                    person.LastName                = tbLastName.Text.Trim();
                    person.Email                   = tbEmail.Text.Trim();
                    person.IsEmailActive           = true;
                    person.EmailPreference         = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                    person.RecordStatusValueId     = _dvcRecordStatus.Id;
                    person.Gender                  = Gender.Unknown;

                    family = PersonService.SaveNewPerson(person, rockContext, _group.CampusId, false);
                }
                else
                {
                    // updating current existing person
                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies(rockContext);

                    // If address can being entered, look for first family with a home location
                    if (!IsSimple)
                    {
                        foreach (var aFamily in families)
                        {
                            homeLocation = aFamily.GroupLocations
                                           .Where(l =>
                                                  l.GroupLocationTypeValueId == _homeAddressType.Id &&
                                                  l.IsMappedLocation)
                                           .FirstOrDefault();
                            if (homeLocation != null)
                            {
                                family = aFamily;
                                break;
                            }
                        }
                    }

                    // If a family wasn't found with a home location, use the person's first family
                    if (family == null)
                    {
                        family = families.FirstOrDefault();
                    }
                }

                // If using a 'Full' view, save the phone numbers and address
                if (!IsSimple)
                {
                    if (!isMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                    {
                        SetPhoneNumber(rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes);
                    }
                    if (!isMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                    {
                        SetPhoneNumber(rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes);
                    }

                    if (!isMatch || !string.IsNullOrWhiteSpace(acAddress.Street1))
                    {
                        string oldLocation = homeLocation != null?homeLocation.Location.ToString() : string.Empty;

                        string newLocation = string.Empty;

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        if (location != null)
                        {
                            if (homeLocation == null)
                            {
                                homeLocation = new GroupLocation();
                                homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                                family.GroupLocations.Add(homeLocation);
                            }
                            else
                            {
                                oldLocation = homeLocation.Location.ToString();
                            }

                            homeLocation.Location = location;
                            newLocation           = location.ToString();
                        }
                        else
                        {
                            if (homeLocation != null)
                            {
                                homeLocation.Location = null;
                                family.GroupLocations.Remove(homeLocation);
                                new GroupLocationService(rockContext).Delete(homeLocation);
                            }
                        }

                        History.EvaluateChange(familyChanges, "Home Location", oldLocation, newLocation);
                    }

                    // Check for the spouse
                    if (IsFullWithSpouse && !string.IsNullOrWhiteSpace(tbSpouseFirstName.Text) && !string.IsNullOrWhiteSpace(tbSpouseLastName.Text))
                    {
                        spouse = person.GetSpouse(rockContext);
                        bool isSpouseMatch = true;

                        if (spouse == null ||
                            !tbSpouseFirstName.Text.Trim().Equals(spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                            !tbSpouseLastName.Text.Trim().Equals(spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                        {
                            spouse        = new Person();
                            isSpouseMatch = false;

                            spouse.FirstName = tbSpouseFirstName.Text.FixCase();
                            History.EvaluateChange(spouseChanges, "First Name", string.Empty, spouse.FirstName);

                            spouse.LastName = tbSpouseLastName.Text.FixCase();
                            History.EvaluateChange(spouseChanges, "Last Name", string.Empty, spouse.LastName);

                            spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                            spouse.RecordStatusValueId     = _dvcRecordStatus.Id;
                            spouse.Gender = Gender.Unknown;

                            spouse.IsEmailActive   = true;
                            spouse.EmailPreference = EmailPreference.EmailAllowed;

                            var groupMember = new GroupMember();
                            groupMember.GroupRoleId = _adultRole.Id;
                            groupMember.Person      = spouse;

                            family.Members.Add(groupMember);

                            spouse.MaritalStatusValueId = _married.Id;
                            person.MaritalStatusValueId = _married.Id;
                        }

                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                        spouse.Email = tbSpouseEmail.Text;

                        if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                        {
                            SetPhoneNumber(rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), spouseChanges);
                        }

                        if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnSpouseCell.Number))
                        {
                            SetPhoneNumber(rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), spouseChanges);
                        }
                    }
                }

                // Save the person/spouse and change history
                rockContext.SaveChanges();
                HistoryService.SaveChanges(rockContext, typeof(Person),
                                           Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes);
                HistoryService.SaveChanges(rockContext, typeof(Person),
                                           Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges);
                if (spouse != null)
                {
                    HistoryService.SaveChanges(rockContext, typeof(Person),
                                               Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), spouse.Id, spouseChanges);
                    HistoryService.SaveChanges(rockContext, typeof(Person),
                                               Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), spouse.Id, familyChanges);
                }

                // Check to see if a workflow should be launched for each person
                WorkflowTypeCache workflowType = null;
                Guid?workflowTypeGuid          = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List <GroupMember>();
                AddPersonToGroup(rockContext, person, workflowType, newGroupMembers);
                AddPersonToGroup(rockContext, spouse, workflowType, newGroupMembers);

                // Show the results
                pnlView.Visible   = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Group", _group);
                mergeFields.Add("GroupMembers", newGroupMembers);

                string template = GetAttributeValue("ResultLavaTemplate");
                lResult.Text = template.ResolveMergeFields(mergeFields);

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
Exemple #16
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            // first ensure that entity commands are allowed in the context
            if (!this.IsAuthorized(context))
            {
                result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name));
                base.Render(context, result);
                return;
            }

            var    attributes       = new Dictionary <string, string>();
            string parmWorkflowType = null;
            string parmWorkflowName = null;
            string parmWorkflowId   = null;
            string parmActivityType = null;

            /* Parse the markup text to pull out configuration parameters. */
            var parms = ParseMarkup(_markup, context);

            foreach (var p in parms)
            {
                if (p.Key.ToLower() == "workflowtype")
                {
                    parmWorkflowType = p.Value;
                }
                else if (p.Key.ToLower() == "workflowname")
                {
                    parmWorkflowName = p.Value;
                }
                else if (p.Key.ToLower() == "workflowid")
                {
                    parmWorkflowId = p.Value;
                }
                else if (p.Key.ToLower() == "activitytype")
                {
                    parmActivityType = p.Value;
                }
                else
                {
                    attributes.AddOrReplace(p.Key, p.Value);
                }
            }

            /* Process inside a new stack level so our own created variables do not
             * persist throughout the rest of the workflow. */
            context.Stack(() =>
            {
                using (var rockContext = new RockContext())
                {
                    WorkflowService workflowService = new WorkflowService(rockContext);
                    Rock.Model.Workflow workflow    = null;
                    WorkflowActivity activity       = null;

                    /* They provided a WorkflowType, so we need to kick off a new workflow. */
                    if (parmWorkflowType != null)
                    {
                        string type = parmWorkflowType;
                        string name = parmWorkflowName ?? string.Empty;
                        WorkflowTypeCache workflowType = null;

                        /* Get the type of workflow */
                        if (type.AsGuidOrNull() != null)
                        {
                            workflowType = WorkflowTypeCache.Read(type.AsGuid());
                        }
                        else if (type.AsIntegerOrNull() != null)
                        {
                            workflowType = WorkflowTypeCache.Read(type.AsInteger());
                        }

                        /* Try to activate the workflow */
                        if (workflowType != null)
                        {
                            workflow = Rock.Model.Workflow.Activate(workflowType, parmWorkflowName);

                            /* Set any workflow attributes that were specified. */
                            foreach (var attr in attributes)
                            {
                                if (workflow.Attributes.ContainsKey(attr.Key))
                                {
                                    workflow.SetAttributeValue(attr.Key, attr.Value.ToString());
                                }
                            }

                            if (workflow != null)
                            {
                                List <string> errorMessages;

                                workflowService.Process(workflow, out errorMessages);

                                if (errorMessages.Any())
                                {
                                    context["Error"] = string.Join("; ", errorMessages.ToArray());
                                }

                                context["Workflow"] = workflow;
                            }
                            else
                            {
                                context["Error"] = "Could not activate workflow.";
                            }
                        }
                        else
                        {
                            context["Error"] = "Workflow type not found.";
                        }
                    }

                    /* They instead provided a WorkflowId, so we are working with an existing Workflow. */
                    else if (parmWorkflowId != null)
                    {
                        string id = parmWorkflowId.ToString();

                        /* Get the workflow */
                        if (id.AsGuidOrNull() != null)
                        {
                            workflow = workflowService.Get(id.AsGuid());
                        }
                        else if (id.AsIntegerOrNull() != null)
                        {
                            workflow = workflowService.Get(id.AsInteger());
                        }

                        if (workflow != null)
                        {
                            if (workflow.CompletedDateTime == null)
                            {
                                /* Currently we cannot activate an activity in a workflow that is currently
                                 * being processed. The workflow is held in-memory so the activity we would
                                 * activate would not show up for the processor and probably never run.
                                 */
                                if (!workflow.IsProcessing)
                                {
                                    bool hasError = false;

                                    /* If they provided an ActivityType parameter then we need to activate
                                     * a new activity in the workflow.
                                     */
                                    if (parmActivityType != null)
                                    {
                                        string type = parmActivityType.ToString();
                                        WorkflowActivityTypeCache activityType = null;

                                        /* Get the type of activity */
                                        if (type.AsGuidOrNull() != null)
                                        {
                                            activityType = WorkflowActivityTypeCache.Read(type.AsGuid());
                                        }
                                        else if (type.AsIntegerOrNull() != null)
                                        {
                                            activityType = WorkflowActivityTypeCache.Read(type.AsInteger());
                                        }

                                        if (activityType != null)
                                        {
                                            activity = WorkflowActivity.Activate(activityType, workflow);

                                            /* Set any workflow attributes that were specified. */
                                            foreach (var attr in attributes)
                                            {
                                                if (activity.Attributes.ContainsKey(attr.Key))
                                                {
                                                    activity.SetAttributeValue(attr.Key, attr.Value.ToString());
                                                }
                                            }
                                        }
                                        else
                                        {
                                            context["Error"] = "Activity type was not found.";
                                            hasError         = true;
                                        }
                                    }

                                    /* Process the existing Workflow. */
                                    if (!hasError)
                                    {
                                        List <string> errorMessages;
                                        workflowService.Process(workflow, out errorMessages);

                                        if (errorMessages.Any())
                                        {
                                            context["Error"] = string.Join("; ", errorMessages.ToArray());
                                        }

                                        context["Workflow"] = workflow;
                                        context["Activity"] = activity;
                                    }
                                }
                                else
                                {
                                    context["Error"] = "Cannot activate activity on workflow that is currently being processed.";
                                }
                            }
                            else
                            {
                                context["Error"] = "Workflow has already been completed.";
                            }
                        }
                        else
                        {
                            context["Error"] = "Workflow not found.";
                        }
                    }
                    else
                    {
                        context["Error"] = "Must specify one of WorkflowType or WorkflowId.";
                    }

                    RenderAll(NodeList, context, result);
                }
            });
        }