Example #1
0
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowTypeCache workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                GroupMember groupMember = null;
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    groupMember                   = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    GroupMemberStatus status = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember = _group.Members.Where(m =>
                                                       m.PersonId == person.Id &&
                                                       m.GroupRoleId == _defaultGroupRole.Id).FirstOrDefault();
                    if (groupMember.GroupMemberStatus != status)
                    {
                        var groupMemberService = new GroupMemberService(rockContext);

                        // reload this group member in the current context
                        groupMember = groupMemberService.Get(groupMember.Id);
                        groupMember.GroupMemberStatus = status;
                        rockContext.SaveChanges();
                    }
                }

                if (groupMember != null)
                {
                    groupMember.LoadAttributes();
                    groupMember.SetAttributeValue("RSVPCount", numHowMany.Value);
                    groupMember.SaveAttributeValues();

                    SendGroupEmail(groupMember);
                }

                if (groupMember != null && workflowType != null && (workflowType.IsActive ?? true))
                {
                    try
                    {
                        List <string> workflowErrors;
                        var           workflow = Workflow.Activate(workflowType, person.FullName);
                        new WorkflowService(rockContext).Process(workflow, groupMember, out workflowErrors);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowType workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMember        = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();

                    if (workflowType != null)
                    {
                        try
                        {
                            List <string> workflowErrors;
                            var           workflow = Workflow.Activate(workflowType, person.FullName);
                            new WorkflowService(rockContext).Process(workflow, groupMember, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }
        }
        public void LaunchWorkflow()
        {
            Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    Person      person        = null;
                    int?        groupMemberId = null;
                    GroupMember groupMember   = null;
                    if (gmpGroupMember.SelectedValueAsId().HasValue)
                    {
                        groupMemberId = gmpGroupMember.SelectedValueAsId();
                        if (groupMemberId.HasValue)
                        {
                            groupMember = new GroupMemberService(_rockContext).Get(groupMemberId.Value);
                            person      = groupMember.Person;
                        }
                    }
                    if (ppPerson.SelectedValue.HasValue)
                    {
                        person = new PersonService(_rockContext).Get(ppPerson.PersonId.Value);
                    }

                    try
                    {
                        var workflowEntity = GetAttributeValue("WorkflowEntity");

                        if (workflowEntity.Equals("Note") && _noteId.HasValue)
                        {
                            var noteRequest = new NoteService(_rockContext).Get(_noteId.Value);
                            if (noteRequest != null)
                            {
                                var           workflow = Workflow.Activate(workflowType, person.FullName);
                                List <string> workflowErrors;
                                new WorkflowService(_rockContext).Process(workflow, noteRequest, out workflowErrors);
                            }
                        }
                        else if (workflowEntity.Equals("GroupMember") && groupMemberId.HasValue && groupMember != null)
                        {
                            var           workflow = Workflow.Activate(workflowType, person.FullName);
                            List <string> workflowErrors;
                            new WorkflowService(_rockContext).Process(workflow, groupMember, out workflowErrors);
                        }
                        else
                        {
                            var           workflow = Workflow.Activate(workflowType, person.FullName);
                            List <string> workflowErrors;
                            new WorkflowService(_rockContext).Process(workflow, person, out workflowErrors);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Handles the FileUploaded event of the fsFile 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 fsFile_FileUploaded(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                var        binaryFileService = new BinaryFileService();
                BinaryFile binaryFile        = null;
                if (fsFile.BinaryFileId.HasValue)
                {
                    binaryFile = binaryFileService.Get(fsFile.BinaryFileId.Value);
                }

                if (binaryFile != null)
                {
                    if (!string.IsNullOrWhiteSpace(tbName.Text))
                    {
                        binaryFile.FileName = tbName.Text;
                    }

                    // set binaryFile.Id to original id since the UploadedFile is a temporary binaryFile with a different id
                    binaryFile.Id               = hfBinaryFileId.ValueAsInt();
                    binaryFile.Description      = tbDescription.Text;
                    binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();
                    if (binaryFile.BinaryFileTypeId.HasValue)
                    {
                        binaryFile.BinaryFileType = new BinaryFileTypeService().Get(binaryFile.BinaryFileTypeId.Value);
                    }

                    binaryFile.LoadAttributes();
                    Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile);

                    // Process uploaded file using an optional workflow
                    Guid workflowTypeGuid = Guid.NewGuid();
                    if (Guid.TryParse(GetAttributeValue("Workflow"), out workflowTypeGuid))
                    {
                        var workflowTypeService = new WorkflowTypeService();
                        var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                        if (workflowType != null)
                        {
                            var workflow = Workflow.Activate(workflowType, binaryFile.FileName);

                            List <string> workflowErrors;
                            if (workflow.Process(binaryFile, out workflowErrors))
                            {
                                binaryFile = binaryFileService.Get(binaryFile.Id);

                                if (workflowType.IsPersisted)
                                {
                                    var workflowService = new Rock.Model.WorkflowService();
                                    workflowService.Add(workflow, CurrentPersonId);
                                    workflowService.Save(workflow, CurrentPersonId);
                                }
                            }
                        }
                    }

                    ShowBinaryFileDetail(binaryFile);
                }
            }
        }
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowType workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMember        = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();

                    if (workflowType != null)
                    {
                        try
                        {
                            var workflowService = new WorkflowService(rockContext);
                            var workflow        = Workflow.Activate(workflowType, person.FullName);

                            List <string> workflowErrors;
                            if (workflow.Process(rockContext, groupMember, out workflowErrors))
                            {
                                if (workflow.IsPersisted || workflow.IsPersisted)
                                {
                                    if (workflow.Id == 0)
                                    {
                                        workflowService.Add(workflow);
                                    }

                                    rockContext.WrapTransaction(() =>
                                    {
                                        rockContext.SaveChanges();
                                        workflow.SaveAttributeValues(_rockContext);
                                        foreach (var activity in workflow.Activities)
                                        {
                                            activity.SaveAttributeValues(rockContext);
                                        }
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }
        }
Example #6
0
        protected void bntMerge_Click(object sender, EventArgs e)
        {
            PDFWorkflowObject pdfWorkflowObject = new PDFWorkflowObject();

            pdfWorkflowObject.LavaInput = ceLava.Text;

            pdfWorkflowObject.MergeObjects = new Dictionary <string, object>();
            if (cbCurrentPerson.Checked)
            {
                pdfWorkflowObject.MergeObjects.Add("CurrentPerson", CurrentPerson);
            }
            if (cbGlobal.Checked)
            {
                pdfWorkflowObject.MergeObjects.Add("GlobalAttributes", GlobalAttributesCache.Read());
            }


            Guid workflowTypeGuid = Guid.NewGuid();

            if (Guid.TryParse(GetAttributeValue("WorkflowType"), out workflowTypeGuid))
            {
                var workflowRockContext = new RockContext();
                var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                if (workflowType != null)
                {
                    var workflow = Workflow.Activate(workflowType, "PDFLavaWorkflow");

                    List <string> workflowErrors;
                    var           workflowService  = new WorkflowService(workflowRockContext);
                    var           workflowActivity = GetAttributeValue("WorkflowActivity");
                    var           activityType     = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                    if (activityType != null)
                    {
                        WorkflowActivity.Activate(activityType, workflow, workflowRockContext);
                        if (workflowService.Process(workflow, pdfWorkflowObject, out workflowErrors))
                        {
                            //success
                        }
                    }
                }
            }

            RockContext       rockContext       = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService(rockContext);

            pdfWorkflowObject.RenderedPDF.FileName = "LavaGeneratedPDF.pdf";
            binaryFileService.Add(pdfWorkflowObject.RenderedPDF);
            rockContext.SaveChanges();

            Response.Redirect(pdfWorkflowObject.RenderedPDF.Path);
        }
        protected void lbTransferAnotherLine_OnClick(object sender, EventArgs e)
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);
            var followUp      = personService.Get(ppFollowUp.SelectedValue.Value);

            var workflowTypeGuid = GetAttributeValue("ReassignWorkflowType").AsGuidOrNull();

            if (workflowTypeGuid.HasValue && ppAnotherLineNewConsolidator.SelectedValue.HasValue)
            {
                var workflowTypeService = new WorkflowTypeService(rockContext);
                var workflowType        = workflowTypeService.Get(workflowTypeGuid.Value);
                if (workflowType != null)
                {
                    try
                    {
                        List <string> workflowErrors;
                        var           workflow = Workflow.Activate(workflowType, followUp.FullName);
                        if (workflow.AttributeValues != null)
                        {
                            if (workflow.AttributeValues.ContainsKey(GetAttributeValue("ReassignAttributeKey")))
                            {
                                var personAlias =
                                    new PersonAliasService(rockContext).Get(ppAnotherLineNewConsolidator.PersonAliasId.Value);
                                if (personAlias != null)
                                {
                                    workflow.AttributeValues[GetAttributeValue("ReassignAttributeKey")].Value =
                                        personAlias.Guid.ToString();
                                }
                            }
                        }
                        new WorkflowService(rockContext).Process(workflow, followUp.PrimaryAlias, out workflowErrors);
                        if (!workflowErrors.Any())
                        {
                            var queryParms = new Dictionary <string, string>
                            {
                                { "success", "true" },
                                { "type", "transfer" },
                                { "personId", ppFollowUp.PersonId.ToString() }
                            };

                            NavigateToParentPage(queryParms);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
        protected void bntMerge_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            //Get the mergefields and pdf
            BinaryFileService           binaryFileService = new BinaryFileService(rockContext);
            Dictionary <string, object> mergeFields       = GetMergeFields();
            BinaryFile pdf = binaryFileService.Get(int.Parse(fpSelectedFile.SelectedValue));

            //Create the object we will need to pass to the workflow
            if (pdf != null && mergeFields.Count > 0)
            {
                var pdfEntity = new PDFWorkflowObject();
                pdfEntity.PDF          = pdf;
                pdfEntity.MergeObjects = mergeFields;

                Guid workflowTypeGuid = Guid.NewGuid();
                if (Guid.TryParse(GetAttributeValue("WorkflowType"), out workflowTypeGuid))
                {
                    var workflowRockContext = new RockContext();
                    var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                    var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                    if (workflowType != null)
                    {
                        var workflow = Workflow.Activate(workflowType, pdf.FileName);

                        List <string> workflowErrors;
                        var           workflowService  = new WorkflowService(workflowRockContext);
                        var           workflowActivity = GetAttributeValue("WorkflowActivity");
                        var           activityType     = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                        if (activityType != null)
                        {
                            WorkflowActivity.Activate(activityType, workflow, workflowRockContext);
                            if (workflowService.Process(workflow, pdfEntity, out workflowErrors))
                            {
                                //success
                            }
                        }
                    }
                }

                var mergedPDF = pdfEntity.PDF;
                //mergedPDF.Guid = Guid.NewGuid();
                binaryFileService.Add(mergedPDF);
                rockContext.SaveChanges();

                Response.Redirect(mergedPDF.Path);
            }
        }
Example #9
0
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var rockContext     = new RockContext();
            var workflowService = new WorkflowService(rockContext);
            WorkflowTypeCache workflowTypeCache = WorkflowTypeCache.Get(dataMap.GetString("WGuid").AsGuid());

            DataSet data = DbService.GetDataSet(dataMap.GetString("SQLQuery"), CommandType.Text, new Dictionary <string, object>());

            foreach (DataTable tbl in data.Tables)
            {
                foreach (DataRow row in tbl.Rows)
                {
                    Workflow workflow = Workflow.Activate(workflowTypeCache, "New " + workflowTypeCache.WorkTerm);

                    foreach (DataColumn col in tbl.Columns)
                    {
                        workflow.SetAttributeValue(col.ColumnName, row[col].ToString());
                    }

                    if (workflowService.Process(workflow, out List <string> errorMessages))
                    {
                        // If the workflow type is persisted, save the workflow
                        if (workflow.IsPersisted || workflowTypeCache.IsPersisted)
                        {
                            if (workflow.Id == 0)
                            {
                                workflowService.Add(workflow);
                            }

                            rockContext.WrapTransaction(() =>
                            {
                                rockContext.SaveChanges();
                                workflow.SaveAttributeValues(rockContext);
                                foreach (WorkflowActivity activity in workflow.Activities)
                                {
                                    activity.SaveAttributeValues(rockContext);
                                }
                            });
                        }
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Launch a workflow designed to process an e-mail address change request.
        /// </summary>
        /// <param name="workflowType">The type of workflow to be launched.</param>
        /// <param name="member">The member whose e-mail address is going to be changed.</param>
        /// <param name="emailAddress">The new e-mail address of the member.</param>
        void LaunchEmailWorkflow(Guid workflowTypeGuid, Person member, string emailAddress)
        {
            var rockContext  = new RockContext();
            var workflowType = new WorkflowTypeService(rockContext).Get(workflowTypeGuid);

            var workflow = Workflow.Activate(workflowType, string.Format("E-mail Change For {0}", member.FullName));

            workflow.LoadAttributes(rockContext);

            if (workflow.Attributes.ContainsKey("Email"))
            {
                workflow.SetAttributeValue("Email", emailAddress);
            }

            var errorMessages = new List <string>();

            new WorkflowService(rockContext).Process(workflow, member, out errorMessages);
        }
        /// <summary>
        /// Increments the prayer count.
        /// </summary>
        /// <param name="prayerRequestId">The prayer request identifier.</param>
        private void IncrementPrayerCount(int prayerRequestId)
        {
            using (var rockContext = new RockContext())
            {
                var request = new PrayerRequestService(rockContext).Get(prayerRequestId);
                var count   = request.PrayerCount ?? 0;
                request.PrayerCount = (count + 1);
                rockContext.SaveChanges();

                Guid?workflowTypeGuid = GetAttributeValue("PrayerCountWorkflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        if (GetAttributeValue("ProcessWorkflowImmediately").AsBoolean())
                        {
                            try
                            {
                                var           workflow = Workflow.Activate(workflowType, request.Name);
                                List <string> workflowErrors;
                                new WorkflowService(rockContext).Process(workflow, request, out workflowErrors);
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogService.LogException(ex, this.Context);
                            }
                        }
                        else
                        {
                            var workflowDetails = new List <LaunchWorkflowDetails>();
                            workflowDetails.Add(new LaunchWorkflowDetails(request));
                            var transaction = new Rock.Transactions.LaunchWorkflowsTransaction(workflowTypeGuid.Value, workflowDetails);
                            // NOTE: In v8, the initiator will always be null while using delayed start.
                            //transaction.InitiatorPersonAliasId = CurrentPersonAliasId; // available in v9
                            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
                        }
                    }
                }
            }
        }
        /// <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.Get(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);
                    }
                }
            }
        }
        /// <summary>
        /// Launches the file upload workflow.
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        /// <param name="binaryFileService">The binary file service.</param>
        private void LaunchFileUploadWorkflow(BinaryFile binaryFile, BinaryFileService binaryFileService)
        {
            // Process uploaded file using an optional workflow (which will probably populate attribute values)
            Guid workflowTypeGuid = Guid.NewGuid();

            if (Guid.TryParse(GetAttributeValue("Workflow"), out workflowTypeGuid))
            {
                try
                {
                    // temporarily set the binaryFile.Id to the uploaded binaryFile.Id so that workflow can do stuff with it
                    binaryFile.Id = fsFile.BinaryFileId ?? 0;

                    // create a rockContext for the workflow so that it can save it's changes, without
                    var workflowRockContext = new RockContext();
                    var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                    var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                    if (workflowType != null)
                    {
                        var workflow = Workflow.Activate(workflowType, binaryFile.FileName);

                        List <string> workflowErrors;
                        if (new Rock.Model.WorkflowService(workflowRockContext).Process(workflow, binaryFile, out workflowErrors))
                        {
                            binaryFile = binaryFileService.Get(binaryFile.Id);
                        }

                        nbWorkflowSuccess.Text    = string.Format("Succesfully processed a <strong>{0}</strong> workflow!", workflowType.Name);
                        nbWorkflowSuccess.Visible = true;
                    }
                }
                finally
                {
                    // set binaryFile.Id to original id again since the UploadedFile is a temporary binaryFile with a different id
                    binaryFile.Id = hfBinaryFileId.ValueAsInt();
                }
            }
        }
Example #14
0
        /// <summary>
        /// Trigger all configured workflows for the given list of membership records.
        /// </summary>
        /// <param name="membership">The list of GroupMember records that have been created or modified.</param>
        protected void TriggerWorkflows(List <GroupMember> membership)
        {
            RockContext     rockContext      = new RockContext();
            WorkflowService workflowService  = new WorkflowService(rockContext);
            Guid?           workflowTypeGuid = GetAttributeValue("IndividualWorkflow").AsGuidOrNull();
            Workflow        workflow;

            //
            // Process per-GroupMember workflow requests.
            //
            if (workflowTypeGuid.HasValue)
            {
                var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);

                if (workflowType != null && workflowType.Id != 0)
                {
                    //
                    // Walk each GroupMember object and fire off a Workflow for each.
                    //
                    foreach (var member in membership)
                    {
                        try
                        {
                            workflow = Workflow.Activate(workflowType, _person.FullName, rockContext);
                            if (workflow != null)
                            {
                                List <string> workflowErrors;

                                workflowService.Process(workflow, member, out workflowErrors);
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }

            //
            // Activate an optional workflow for the entire submission.
            //
            workflowTypeGuid = GetAttributeValue("SubmissionWorkflow").AsGuidOrNull();
            if (workflowTypeGuid.HasValue)
            {
                var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);

                if (workflowType != null && workflowType.Id != 0)
                {
                    try
                    {
                        workflow = Workflow.Activate(workflowType, _person.FullName, rockContext);
                        if (workflow != null)
                        {
                            List <string> workflowErrors;

                            if (workflow.Attributes.ContainsKey(GetAttributeValue("SubmissionAttribute")))
                            {
                                string guids = membership.Select(gm => gm.Guid.ToString()).ToList().AsDelimited(",");
                                workflow.SetAttributeValue(GetAttributeValue("SubmissionAttribute"), guids);
                            }
                            workflowService.Process(workflow, _person, out workflowErrors);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Example #15
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);

                DateTime startDate = _occurrence.Date;
                DateTime endDate   = _occurrence.Date.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 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
                {
                    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;
                                attendance.LocationId    = _occurrence.LocationId;
                                attendance.CampusId      = locationService.GetCampusIdForLocation(_occurrence.LocationId);
                                attendance.ScheduleId    = _occurrence.ScheduleId;
                                attendanceService.Add(attendance);
                            }
                        }

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

                rockContext.SaveChanges();

                WorkflowType workflowType     = null;
                Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                    if (workflowType != null)
                    {
                        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);
                        }
                    }
                }

                NavigateToParentPage(new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                });
            }
        }
Example #16
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (lopAddress.Location == null ||
                string.IsNullOrWhiteSpace(lopAddress.Location.Street1) ||
                string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode))
            {
                nbValidation.Visible = true;
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "setTimeout(function(){window.scroll(0,0);},200)", true);
                return;
            }
            else
            {
                nbValidation.Visible = false;
            }


            if (_group == null)
            {
                ShowMessage("There was an issue with the viewstate. Please reload and try again. If the problem perssits contact an administrator.", "Error", "panel panel-danger");
                return;
            }

            GroupService groupService = new GroupService(_rockContext);
            //Add basic information

            Group group;

            if (_group.Id == 0)
            {
                group = new Group()
                {
                    GroupTypeId = _groupType.Id
                };
                var destinationGroup = groupService.Get(GetAttributeValue("DestinationGroup").AsGuid());
                if (destinationGroup != null)
                {
                    group.ParentGroupId = destinationGroup.Id;
                }

                var parentMapping = GetAttributeValue("CampusGroupMap").ToKeyValuePairList();
                foreach (var pair in parentMapping)
                {
                    if (pair.Key.AsInteger() == cpCampus.SelectedValueAsId())
                    {
                        group.ParentGroupId = (( string )pair.Value).AsInteger();
                    }
                }

                var zip = "No Zip";
                if (lopAddress.Location != null && !string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode))
                {
                    zip = lopAddress.Location.PostalCode;
                }
                group.Name = string.Format("{0} - {1}", tbName.Text, zip);
                groupService.Add(group);
                group.CreatedByPersonAliasId = _person.PrimaryAliasId;
                group.IsActive = true;
            }
            else
            {
                group          = groupService.Get(_group.Id);
                group.IsActive = true;
            }

            group.CampusId    = cpCampus.SelectedValueAsId();
            group.Description = tbDescription.Text;


            //Set location
            if (lopAddress.Location != null && lopAddress.Location.Id != 0)
            {
                if (group.GroupLocations != null && !group.GroupLocations.Select(gl => gl.LocationId).Contains(lopAddress.Location.Id))
                {
                    // Disassociate the old address(es)
                    GroupLocationService groupLocationService = new GroupLocationService(_rockContext);
                    var meetingLocationDv = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION);
                    var homeLocationDv    = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                    groupLocationService.DeleteRange(group.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == meetingLocationDv.Id || gl.GroupLocationTypeValueId == homeLocationDv.Id || gl.GroupLocationTypeValueId == null));
                    group.GroupLocations.Add(new GroupLocation()
                    {
                        LocationId = lopAddress.Location.Id, GroupLocationTypeValueId = meetingLocationDv.Id
                    });
                }
            }

            //Set Schedule
            if (_groupType.AllowedScheduleTypes != ScheduleType.None)
            {
                switch (rblSchedule.SelectedValueAsEnum <ScheduleType>())
                {
                case ScheduleType.None:
                    group.ScheduleId = null;
                    break;

                case ScheduleType.Weekly:
                    var weeklySchedule = new Schedule()
                    {
                        WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek, WeeklyTimeOfDay = timeWeekly.SelectedTime
                    };
                    group.Schedule = weeklySchedule;
                    break;

                case ScheduleType.Custom:
                    var customSchedule = new Schedule()
                    {
                        iCalendarContent = sbSchedule.iCalendarContent
                    };
                    group.Schedule = customSchedule;
                    break;

                case ScheduleType.Named:
                    if (spSchedule.SelectedValue.AsInteger() != 0)
                    {
                        group.ScheduleId = spSchedule.SelectedValue.AsInteger();
                    }
                    break;

                default:
                    break;
                }
            }

            if (group.Members != null && group.Members.Any())
            {
                foreach (var member in group.Members.Where(gm => gm.PersonId != _person.Id))
                {
                    member.GroupMemberStatus = GroupMemberStatus.Inactive;
                }

                foreach (int groupMemberId in gMembers.SelectedKeys)
                {
                    var groupMember = group.Members.Where(m => m.Id == groupMemberId).FirstOrDefault();
                    if (groupMember != null)
                    {
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    }
                }
            }
            else
            {
                var groupRoleId = new GroupTypeRoleService(_rockContext).Get(GetAttributeValue("GroupRole").AsGuid()).Id;
                group.Members.Add(new GroupMember()
                {
                    PersonId = _person.Id, GroupRoleId = groupRoleId
                });
            }

            //Save attributes
            _rockContext.SaveChanges();
            group.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phAttributes, group);
            var attributeGuid        = GetAttributeValue("MultiSelectAttribute");
            var multiselectAttribute = new AttributeService(_rockContext).Get(attributeGuid.AsGuid());

            if (multiselectAttribute != null)
            {
                var attributeValue = group.GetAttributeValue(multiselectAttribute.Key)
                                     .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .ToList();
                var newAttributeText = GetAttributeValue("AttributeText");
                if (!attributeValue.Contains(newAttributeText))
                {
                    attributeValue.Add(newAttributeText);
                }
                group.SetAttributeValue(multiselectAttribute.Key, string.Join(",", attributeValue));
            }
            group.SaveAttributeValues();

            //Update cache
            var availableGroupIds = (List <int>)GetCacheItem(GetAttributeValue("DestinationGroup"));

            if (availableGroupIds != null)
            {
                availableGroupIds.Add(group.Id);
                AddCacheItem(GetAttributeValue("DestinationGroup"), availableGroupIds);
            }

            var workflowTypeService        = new WorkflowTypeService(_rockContext);
            WorkflowTypeCache workflowType = null;
            Guid?workflowTypeGuid          = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
            }
            GroupMember currentGroupMember = group.Members.Where(gm => gm.PersonId == _person.Id).FirstOrDefault();

            if (currentGroupMember != null && workflowType != null && (workflowType.IsActive ?? true))
            {
                try
                {
                    List <string> workflowErrors;
                    var           workflow = Workflow.Activate(workflowType, _person.FullName);

                    if (workflow.AttributeValues.ContainsKey("Group"))
                    {
                        if (group != null)
                        {
                            workflow.AttributeValues["Group"].Value = group.Guid.ToString();
                        }
                    }

                    if (workflow.AttributeValues.ContainsKey("Person"))
                    {
                        if (_person != null)
                        {
                            workflow.AttributeValues["Person"].Value = _person.PrimaryAlias.Guid.ToString();
                        }
                    }
                    new WorkflowService(_rockContext).Process(workflow, currentGroupMember, out workflowErrors);
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(ex, this.Context);
                }
            }
            ShowMessage(GetAttributeValue("SuccessText"), "Thank you!", "panel panel-success");
        }
Example #17
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            string query            = dataMap.GetString("SQLQuery");
            Guid?  workflowTypeGuid = dataMap.GetString("Workflow").AsGuidOrNull();

            // run a SQL query to do something
            int?commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull();
            int failed         = 0;
            int successful     = 0;

            try
            {
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = Rock.Web.Cache.WorkflowTypeCache.Read(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        DataSet rows = DbService.GetDataSet(query, System.Data.CommandType.Text, null, commandTimeout);

                        List <string> workflowErrors;
                        using (var rockContext = new RockContext())
                        {
                            // Fire off a workflow for each row in the query
                            foreach (DataRow row in rows.Tables[0].Rows)
                            {
                                var workflow = Workflow.Activate(workflowType, workflowType.Name);
                                workflow.LoadAttributes(rockContext);

                                // Iterate over each column setting attribute values in the workflow
                                foreach (DataColumn column in rows.Tables[0].Columns)
                                {
                                    if (workflow.Attributes.ContainsKey(column.ColumnName))
                                    {
                                        workflow.SetAttributeValue(column.ColumnName, Convert.ToString(row[column]));
                                    }
                                }

                                // Now process the workflow
                                var processed = new WorkflowService(rockContext).Process(workflow, out workflowErrors);
                                if (processed)
                                {
                                    successful++;
                                }
                                else
                                {
                                    failed++;
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }

            context.Result = string.Format("Workflow Launch Results:<br />Success: " + successful + "<br />Failed: " + failed);
        }
        /// <summary>
        /// Handles the FileUploaded event of the fsFile 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 fsFile_FileUploaded(object sender, EventArgs e)
        {
            var        rockContext       = new RockContext();
            var        binaryFileService = new BinaryFileService(rockContext);
            BinaryFile binaryFile        = null;

            if (fsFile.BinaryFileId.HasValue)
            {
                binaryFile = binaryFileService.Get(fsFile.BinaryFileId.Value);
            }

            if (binaryFile != null)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text))
                {
                    binaryFile.FileName = tbName.Text;
                }

                // set binaryFile.Id to original id since the UploadedFile is a temporary binaryFile with a different id
                binaryFile.Id               = hfBinaryFileId.ValueAsInt();
                binaryFile.Description      = tbDescription.Text;
                binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();
                if (binaryFile.BinaryFileTypeId.HasValue)
                {
                    binaryFile.BinaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFile.BinaryFileTypeId.Value);
                }

                var tempList = OrphanedBinaryFileIdList;
                tempList.Add(fsFile.BinaryFileId.Value);
                OrphanedBinaryFileIdList = tempList;

                // load attributes, then get the attribute values from the UI
                binaryFile.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile);

                // Process uploaded file using an optional workflow (which will probably populate attribute values)
                Guid workflowTypeGuid = Guid.NewGuid();
                if (Guid.TryParse(GetAttributeValue("Workflow"), out workflowTypeGuid))
                {
                    try
                    {
                        // temporarily set the binaryFile.Id to the uploaded binaryFile.Id so that workflow can do stuff with it
                        binaryFile.Id = fsFile.BinaryFileId ?? 0;

                        // create a rockContext for the workflow so that it can save it's changes, without
                        var workflowRockContext = new RockContext();
                        var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                        var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                        if (workflowType != null)
                        {
                            var workflow = Workflow.Activate(workflowType, binaryFile.FileName);

                            List <string> workflowErrors;
                            if (new Rock.Model.WorkflowService(workflowRockContext).Process(workflow, binaryFile, out workflowErrors))
                            {
                                binaryFile = binaryFileService.Get(binaryFile.Id);
                            }
                        }
                    }
                    finally
                    {
                        // set binaryFile.Id to original id again since the UploadedFile is a temporary binaryFile with a different id
                        binaryFile.Id = hfBinaryFileId.ValueAsInt();
                    }
                }

                ShowBinaryFileDetail(binaryFile);
            }
        }
Example #19
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(ExtensionMethods.SelectedValueAsInt(bddlCampus) ?? 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();

                WorkflowType workflowType     = null;
                Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                    if (workflowType != null)
                    {
                        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);
            }
        }
        /// <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 existingAttendees = attendanceService.Queryable()
                                        .Where(a =>
                                               a.GroupId == _group.Id &&
                                               a.ScheduleId == _group.ScheduleId &&
                                               a.StartDateTime >= _occurrence.StartDateTime &&
                                               a.StartDateTime < _occurrence.EndDateTime)
                                        .ToList();

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule)
                // 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
                {
                    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 item in lvMembers.Items)
                    {
                        var hfMember = item.FindControl("hfMember") as HiddenField;
                        var cbMember = item.FindControl("cbMember") as CheckBox;

                        if (hfMember != null && cbMember != null)
                        {
                            int personId = hfMember.ValueAsInt();

                            var attendance = existingAttendees
                                             .Where(a => a.PersonAlias.PersonId == personId)
                                             .FirstOrDefault();

                            if (attendance == null)
                            {
                                int?personAliasId = personAliasService.GetPrimaryAliasId(personId);
                                if (personAliasId.HasValue)
                                {
                                    attendance               = new Attendance();
                                    attendance.GroupId       = _group.Id;
                                    attendance.ScheduleId    = _group.ScheduleId;
                                    attendance.PersonAliasId = personAliasId;
                                    attendance.StartDateTime = _occurrence.StartDateTime;
                                    attendanceService.Add(attendance);
                                }
                            }

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

                rockContext.SaveChanges();

                WorkflowType workflowType     = null;
                Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                    if (workflowType != null)
                    {
                        try
                        {
                            var workflowService = new WorkflowService(rockContext);
                            var workflow        = Workflow.Activate(workflowType, _group.Name);

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

                            List <string> workflowErrors;
                            if (workflow.Process(rockContext, _group, out workflowErrors))
                            {
                                if (workflow.IsPersisted || workflow.IsPersisted)
                                {
                                    if (workflow.Id == 0)
                                    {
                                        workflowService.Add(workflow);
                                    }

                                    rockContext.WrapTransaction(() =>
                                    {
                                        rockContext.SaveChanges();
                                        workflow.SaveAttributeValues(_rockContext);
                                        foreach (var activity in workflow.Activities)
                                        {
                                            activity.SaveAttributeValues(rockContext);
                                        }
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }

                NavigateToParentPage(new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                });
            }
        }
Example #21
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            string query = dataMap.GetString("SQLQuery");

            Guid?dataViewGuid     = dataMap.GetString("DataView").AsGuidOrNull();
            Guid?workflowTypeGuid = dataMap.GetString("Workflow").AsGuidOrNull();

            // run a SQL query to do something
            int?commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull();
            int failed         = 0;
            int successful     = 0;

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

            try
            {
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = Rock.Web.Cache.WorkflowTypeCache.Get(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        using (var rockContext = new RockContext())
                        {
                            // Handle the SQL Query
                            if (!query.IsNullOrWhiteSpace())
                            {
                                DataSet rows = DbService.GetDataSet(query, System.Data.CommandType.Text, null, commandTimeout);

                                // Fire off a workflow for each row in the query
                                foreach (DataRow row in rows.Tables[0].Rows)
                                {
                                    var workflow = Workflow.Activate(workflowType, workflowType.Name);
                                    workflow.LoadAttributes(rockContext);

                                    // Iterate over each column setting attribute values in the workflow
                                    foreach (DataColumn column in rows.Tables[0].Columns)
                                    {
                                        if (workflow.Attributes.ContainsKey(column.ColumnName))
                                        {
                                            workflow.SetAttributeValue(column.ColumnName, Convert.ToString(row[column]));
                                        }
                                    }

                                    // Now process the workflow
                                    var processed = new WorkflowService(rockContext).Process(workflow, out errors);
                                    if (processed)
                                    {
                                        successful++;
                                    }
                                    else
                                    {
                                        failed++;
                                    }
                                }
                            }

                            // If a dataview is specified, then we'll fire off workflows for that dataview
                            if (dataViewGuid != null)
                            {
                                var dataView = new DataViewService(rockContext).Get(dataViewGuid.Value);

                                var entityList = dataView.GetQuery(new DataViewGetQueryArgs {
                                    SortProperty = null, DatabaseTimeoutSeconds = commandTimeout
                                });
                                foreach (IEntity entity in entityList)
                                {
                                    var workflow = Workflow.Activate(workflowType, workflowType.Name);

                                    var processed = new WorkflowService(rockContext).Process(workflow, entity, out errors);
                                    if (processed)
                                    {
                                        successful++;
                                    }
                                    else
                                    {
                                        failed++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }

            context.Result = string.Format("Workflow Launch Results:<br />Success:  {0}<br />Failed: {1}{2}", successful, failed, errors.Count > 0 ? "<br />Errors: " + string.Join("<br />", errors) : "");
        }
        public void Execute(IJobExecutionContext context)
        {
            // Get job settings
            var dataMap = context.JobDetail.JobDataMap;
            string query = dataMap.GetString( "SQLQuery" );
            var workflowTypeGuid = dataMap.GetString("Workflow").AsGuidOrNull();
            var sqlToWorkflowAttributeMapping = dataMap.GetString("sqlToWorkflow").AsDictionaryOrNull();
            
            //set counters
            int workflowsActivated = 0;

            // Ensure job settings aren't null
            if (string.IsNullOrEmpty(query) || workflowTypeGuid == null || sqlToWorkflowAttributeMapping == null)
            {
                throw new Exception("Missing one or more job settings.");
            }

            var rockContext = new RockContext();
            var workflowType = WorkflowTypeCache.Get( workflowTypeGuid.Value );
            if (workflowType == null)
            {
                throw new Exception("Unable to find matching Workflow Type");
            }

            if ( !workflowType.IsActive ?? true  )
            {
                throw new Exception( String.Format( "{0} is not an active workflow type", workflowType.Name ) );
            }

            // Run SQL and launch workflows
            try
            {
                var table = DbService.GetDataTable( query, CommandType.Text, null );
                if (table == null)
                {
                    throw new Exception("No data returned from SQL query");
                }

                var workflowService = new WorkflowService(rockContext);

                foreach (DataRow row in table.Rows)
                {
                    var workflow = Workflow.Activate( workflowType, workflowType.Name );
                    workflow.LoadAttributes( rockContext );

                    foreach (var keyValuePair in sqlToWorkflowAttributeMapping)
                    {
                        string workflowKey = keyValuePair.Value.Replace("|", "");
                        if (row[keyValuePair.Key] != null && workflow.Attributes.ContainsKey(workflowKey))
                        {
                            string value = row[keyValuePair.Key].ToString();
                            workflow.SetAttributeValue(workflowKey, value);
                        }
                        else
                        {
                            throw new Exception("Bad match on SQL column to Workflow Attribute");
                        }
                    }
                    List<string> errorMessages;
                    workflowService.Process(workflow, out errorMessages);
                }

            }
            catch ( Exception ex )
            {
                var httpContext = HttpContext.Current;
                ExceptionLogService.LogException( ex, httpContext );
                throw;
            }
            
            // send results
            context.Result = string.Format("{0} workflows were activated",workflowsActivated);
        }
        /// <summary>
        /// Method to save attendance for use in two separate areas.
        /// </summary>
        protected bool SaveAttendance()
        {
            using (var rockContext = new RockContext())
            {
                var occurrenceService  = new AttendanceOccurrenceService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                AttendanceOccurrence occurrence = null;

                if (_occurrence.Id != 0)
                {
                    occurrence = occurrenceService.Get(_occurrence.Id);
                }

                if (occurrence == null)
                {
                    var existingOccurrence = occurrenceService.Get(_occurrence.OccurrenceDate, _group.Id, _occurrence.LocationId, _occurrence.ScheduleId);
                    if (existingOccurrence != null)
                    {
                        nbNotice.Heading             = "Occurrence Already Exists";
                        nbNotice.Text                = "<p>An occurrence already exists for this group for the selected date, location, and schedule that you've selected. Please return to the list and select that occurrence to update it's attendance.</p>";
                        nbNotice.NotificationBoxType = NotificationBoxType.Danger;
                        nbNotice.Visible             = true;

                        return(false);
                    }
                    else
                    {
                        occurrence                = new AttendanceOccurrence();
                        occurrence.GroupId        = _occurrence.GroupId;
                        occurrence.LocationId     = _occurrence.LocationId;
                        occurrence.ScheduleId     = _occurrence.ScheduleId;
                        occurrence.OccurrenceDate = _occurrence.OccurrenceDate;
                        occurrenceService.Add(occurrence);
                    }
                }

                occurrence.Notes       = GetAttributeValue("ShowNotes").AsBoolean() ? dtNotes.Text : string.Empty;
                occurrence.DidNotOccur = cbDidNotMeet.Checked;

                var existingAttendees = occurrence.Attendees.ToList();

                // 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) ?? _group.CampusId;
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Get(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;
                        }
                    }
                    else
                    {
                        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.PersonAliasId = personAliasId;
                                    attendance.CampusId      = campusId;
                                    attendance.StartDateTime = _occurrence.OccurrenceDate;

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

                                    occurrence.Attendees.Add(attendance);
                                }
                            }

                            if (attendance != null)
                            {
                                attendance.DidAttend = attendee.Attended;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                if (occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Remove(occurrence.LocationId.Value);
                }


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

                            workflow.SetAttributeValue("StartDateTime", _occurrence.OccurrenceDate.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);
                        }
                    }
                }
            }

            return(true);
        }