Exemplo n.º 1
0
    /// <summary>
    /// Handles the Load event of the Page 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 Page_Load( object sender, EventArgs e )
    {
                
        // get error level
        int errorLevel = 0;

        if ( Request["error"] != null )
            errorLevel = Int32.Parse( Request["error"].ToString() );

        if ( errorLevel == 1 )
        {
            // check to see if the user is an admin, if so allow them to view the error details
            var userLogin = Rock.Model.UserLoginService.GetCurrentUser();

            GroupService service = new GroupService();
            Group adminGroup = service.GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_ADMINISTRATORS ) );

            if ( userLogin != null && adminGroup.Members.Where( m => m.PersonId == userLogin.PersonId ).Count() > 0 )
            {
                // is an admin
                lErrorInfo.Text = "<h3>Exception Log:</h3>";

                // get exception from Session
                if ( Session["Exception"] != null )
                {
                    ProcessException( (Exception)Session["Exception"], " " );
                }
            }
        }

        // clear session object
        Session.Remove( "Exception" );
    }
Exemplo n.º 2
0
    /// <summary>
    /// Handles the Click event of the btnSave 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 btnSave_Click( object sender, EventArgs e )
    {
        Group group;
        GroupService groupService = new GroupService();

        int groupId = int.Parse( hfGroupId.Value );

        if ( groupId == 0 )
        {
            group = new Group();
            group.IsSystem = false;
            groupService.Add( group, CurrentPersonId );
        }
        else
        {
            // just in case this group is or was a SecurityRole
            Rock.Security.Role.Flush( groupId );

            group = groupService.Get( groupId );
        }

        group.Name = tbName.Text;
        group.Description = tbDescription.Text;
        group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue );
        group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue );
        group.ParentGroupId = ddlParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlParentGroup.SelectedValue );
        group.IsSecurityRole = cbIsSecurityRole.Checked;

        // check for duplicates within GroupType
        if ( groupService.Queryable().Where( g => g.GroupTypeId.Equals( group.GroupTypeId ) ).Count( a => a.Name.Equals( group.Name, StringComparison.OrdinalIgnoreCase ) && !a.Id.Equals( group.Id ) ) > 0 )
        {
            tbName.ShowErrorMessage( WarningMessage.DuplicateFoundMessage( "name", Group.FriendlyTypeName ) );
            return;
        }

        if ( !group.IsValid )
        {
            // Controls will render the error messages
            return;
        }

        RockTransactionScope.WrapTransaction( () =>
        {
            groupService.Save( group, CurrentPersonId );
        } );

        // just in case this group is or was a SecurityRole
        Rock.Security.Authorization.Flush();

        NavigateToParentPage();
    }
Exemplo n.º 3
0
 public ServiceList(string url, ResponseToken token)
 {
     this.eventService = new EventService(url, token);
     this.categoryService = new CategoryService(url, token);
     this.clubService = new ClubService(url, token);
     this.userService = new UserService(url, token);
     this.ticketService = new TicketService(url, token);
     this.meetingService = new MeetingService(url, token);
     this.invoiceService = new InvoiceService(url, token);
     this.groupService = new GroupService(url, token);
     this.expenseService = new ExpenseService(url, token);
     this.emailService = new EmailService(url, token);
     this.depositService = new DepositService(url, token);
     this.customFieldService = new CustomFieldService(url, token);
     this.taskService = new TaskService(url, token);
     this.contactService = new ContactService(url, token);
 }
Exemplo n.º 4
0
    /// <summary>
    /// Handles the Delete event of the gGroups control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
    protected void gGroups_Delete( object sender, RowEventArgs e )
    {
        RockTransactionScope.WrapTransaction( () =>
            {
                GroupService groupService = new GroupService();
                AuthService authService = new AuthService();
                Group group = groupService.Get( (int)e.RowKeyValue );

                if ( group != null )
                {
                    string errorMessage;
                    if ( !groupService.CanDelete( group, out errorMessage ) )
                    {
                        mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    bool isSecurityRoleGroup = group.IsSecurityRole;
                    if ( isSecurityRoleGroup )
                    {
                        foreach ( var auth in authService.Queryable().Where( a => a.GroupId.Equals( group.Id ) ).ToList() )
                        {
                            authService.Delete( auth, CurrentPersonId );
                            authService.Save( auth, CurrentPersonId );
                        }
                    }

                    groupService.Delete( group, CurrentPersonId );
                    groupService.Save( group, CurrentPersonId );

                    if ( isSecurityRoleGroup )
                    {
                        Rock.Security.Authorization.Flush();
                        Rock.Security.Role.Flush( group.Id );
                    }
                }
            } );

        BindGrid();
    }
Exemplo n.º 5
0
    /// <summary>
    /// Loads the drop downs.
    /// </summary>
    private void LoadDropDowns()
    {
        GroupTypeService groupTypeService = new GroupTypeService();
        var groupTypeQry = groupTypeService.Queryable();

        // limit GroupType selection to what Block Attributes allow
        List<int> groupTypeIds = AttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList();
        if ( groupTypeIds.Count > 0 )
        {
            groupTypeQry = groupTypeQry.Where( a => groupTypeIds.Contains( a.Id ) );
        }

        List<GroupType> groupTypes = groupTypeQry.OrderBy( a => a.Name ).ToList();
        ddlGroupType.DataSource = groupTypes;
        ddlGroupType.DataBind();

        int currentGroupId = int.Parse( hfGroupId.Value );

        // TODO: Only include valid Parent choices (no circular references)
        GroupService groupService = new GroupService();
        List<Group> groups = groupService.Queryable().Where( g => g.Id != currentGroupId ).OrderBy( a => a.Name ).ToList();
        groups.Insert( 0, new Group { Id = None.Id, Name = None.Text } );
        ddlParentGroup.DataSource = groups;
        ddlParentGroup.DataBind();

        CampusService campusService = new CampusService();
        List<Campus> campuses = campusService.Queryable().OrderBy( a => a.Name ).ToList();
        campuses.Insert( 0, new Campus { Id = None.Id, Name = None.Text } );
        ddlCampus.DataSource = campuses;
        ddlCampus.DataBind();
    }
Exemplo n.º 6
0
 public GroupsController()
 {
     GroupService = new GroupService(UnitOfWork);
 }
Exemplo n.º 7
0
 public void SetUp()
 {
     mockRepo = new Mock<IRepository<Group>>();
     testService = new GroupService(mockRepo.Object);
 }
Exemplo n.º 8
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

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

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

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

            if (!(_workflowType.IsActive ?? true))
            {
                ShowNotes(false);
                ShowMessage(NotificationBoxType.Warning, "Sorry", "This type of workflow is not active.");
                return(false);
            }

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

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

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

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

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

                    // Loop through all the query string parameters and try to set any workflow
                    // attributes that might have the same key
                    foreach (var param in RockPage.PageParameters())
                    {
                        if (param.Value != null && param.Value.ToString().IsNotNullOrWhitespace())
                        {
                            _workflow.SetAttributeValue(param.Key, param.Value.ToString());
                        }
                    }

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

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

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

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

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

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

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

                lSummary.Text = string.Empty;
            }
            else
            {
                if (GetAttributeValue("ShowSummaryView").AsBoolean() && !string.IsNullOrWhiteSpace(_workflowType.SummaryViewText))
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("Action", _action);
                    mergeFields.Add("Activity", _activity);
                    mergeFields.Add("Workflow", _workflow);

                    lSummary.Text    = _workflowType.SummaryViewText.ResolveMergeFields(mergeFields, CurrentPerson);
                    lSummary.Visible = true;
                }
            }

            if (lSummary.Text.IsNullOrWhiteSpace())
            {
                if (_workflowType.NoActionMessage.IsNullOrWhiteSpace())
                {
                    ShowMessage(NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information.");
                }
                else
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("Action", _action);
                    mergeFields.Add("Activity", _activity);
                    mergeFields.Add("Workflow", _workflow);
                    ShowMessage(NotificationBoxType.Warning, string.Empty, _workflowType.NoActionMessage.ResolveMergeFields(mergeFields, CurrentPerson));
                }
            }

            ShowNotes(false);
            return(false);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService(rockContext);
            var groupTypeService     = new GroupTypeService(rockContext);
            var groupService         = new GroupService(rockContext);

            IEnumerable <GroupTypePath> groupPaths = new List <GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable();

            List <int> currentAndDescendantGroupTypeIds = new List <int>();
            var        currentGroupTypeIds = this.CurrentGroupTypeIds.ToList();

            currentAndDescendantGroupTypeIds.AddRange(currentGroupTypeIds);
            foreach (var templateGroupType in groupTypeService.Queryable().Where(a => currentGroupTypeIds.Contains(a.Id)))
            {
                foreach (var childGroupType in groupTypeService.GetChildGroupTypes(templateGroupType.Id))
                {
                    currentAndDescendantGroupTypeIds.Add(childGroupType.Id);
                    currentAndDescendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(childGroupType.Id).Select(a => a.Id).ToList());
                }
            }

            groupLocationQry = groupLocationQry.Where(a => currentAndDescendantGroupTypeIds.Contains(a.Group.GroupTypeId));

            groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name);

            List <int> currentDeviceLocationIdList = this.GetGroupTypesLocations(rockContext).Select(a => a.Id).Distinct().ToList();

            var qryList = groupLocationQry
                          .Where(a => currentDeviceLocationIdList.Contains(a.LocationId))
                          .Select(a =>
                                  new
            {
                GroupLocationId = a.Id,
                a.Location,
                GroupId        = a.GroupId,
                GroupName      = a.Group.Name,
                ScheduleIdList = a.Schedules.Select(s => s.Id),
                GroupTypeId    = a.Group.GroupTypeId
            }).ToList();

            var locationService = new LocationService(rockContext);

            // put stuff in a datatable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("GroupLocationId");
            dataTable.Columns.Add("GroupId");
            dataTable.Columns.Add("GroupName");
            dataTable.Columns.Add("GroupPath");
            dataTable.Columns.Add("LocationName");
            dataTable.Columns.Add("LocationPath");
            foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
            {
                dataTable.Columns.Add(field.DataField, typeof(bool));
            }

            var locationPaths = new Dictionary <int, string>();

            foreach (var row in qryList)
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"]       = groupService.GroupAncestorPathName(row.GroupId);
                dataRow["GroupPath"]       = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault();
                dataRow["LocationName"]    = row.Location.Name;

                if (row.Location.ParentLocationId.HasValue)
                {
                    int locationId = row.Location.ParentLocationId.Value;

                    if (!locationPaths.ContainsKey(locationId))
                    {
                        var locationNames  = new List <string>();
                        var parentLocation = locationService.Get(locationId);
                        while (parentLocation != null)
                        {
                            locationNames.Add(parentLocation.Name);
                            parentLocation = parentLocation.ParentLocation;
                        }

                        if (locationNames.Any())
                        {
                            locationNames.Reverse();
                            locationPaths.Add(locationId, locationNames.AsDelimited(" > "));
                        }
                        else
                        {
                            locationPaths.Add(locationId, string.Empty);
                        }
                    }

                    dataRow["LocationPath"] = locationPaths[locationId];
                }

                foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
                {
                    int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty));
                    dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId);
                }

                dataTable.Rows.Add(dataRow);
            }

            gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read <GroupLocation>().Id;
            gGroupLocationSchedule.DataSource   = dataTable;
            gGroupLocationSchedule.DataBind();
        }
        public void Execute(IJobExecutionContext context)
        {
            var rockContext     = new RockContext();
            var dataMap         = context.JobDetail.JobDataMap;
            var systemEmailGuid = dataMap.GetString("Email").AsGuidOrNull();
            var groupFieldGuid  = dataMap.GetString("RootGroup").AsGuidOrNull();

            string appRoot = GlobalAttributesCache.Read().GetValue("ExternalApplicationRoot");

            if (systemEmailGuid == null)
            {
                throw new Exception("A system email template needs to be set.");
            }
            var systemEmailTemplate = new SystemEmailService(rockContext).Get(systemEmailGuid.Value);

            if (systemEmailTemplate == null)
            {
                throw new Exception("The system email template setting is not a valid system email template.");
            }

            if (groupFieldGuid == null)
            {
                throw new Exception("A group must be specified");
            }

            var groupService  = new GroupService(rockContext);
            var rootGroup     = groupService.GetByGuid(groupFieldGuid.Value);
            var validGroupIds = new List <int> {
                rootGroup.Id
            };

            validGroupIds.AddRange(groupService.GetAllDescendents(rootGroup.Id).Select(g => g.Id));

            // Check to see if we should skip this week
            var definedTypeId = new DefinedTypeService(rockContext).Queryable().FirstOrDefault(dt => dt.Name == "Volunteer Reminder Exclusions")?.Id;

            if (definedTypeId == null)
            {
                context.Result = "Could not get Volunteer Reminder Exclusions defined type";
                return;
            }
            var datesToSkip = new DefinedValueService(rockContext).GetByDefinedTypeId(definedTypeId.Value);

            foreach (var dateToSkipValue in datesToSkip)
            {
                dateToSkipValue.LoadAttributes();
                var date = dateToSkipValue.GetAttributeValue("Date").AsDateTime();
                if (date != null && DatesAreInTheSameWeek(date.Value, RockDateTime.Today))
                {
                    context.Result = "This week should be skipped because of the exclusion " + date.Value.ToString("o");
                    return;
                }
            }


            string weekTeam         = "Team " + Utils.ServingWeek.GetTeamNumber();
            var    attributeService = new AttributeService(rockContext);
            var    attributeIds     =
                attributeService.GetByEntityTypeId(
                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id).Where(a => a.Key == "AssignedTeam").Select(a => a.Id);
            var attributeValueService = new AttributeValueService(rockContext);
            var groupMemberIds        = new List <int>();

            foreach (int attributeId in attributeIds)
            {
                var attributeValues = attributeValueService.GetByAttributeId(attributeId).AsQueryable().AsNoTracking().Where(av => av.Value.Contains(weekTeam));
                groupMemberIds.AddRange(attributeValues.Where(av => av.EntityId != null).Select(av => av.EntityId.Value));
            }


            var groupMembers = new GroupMemberService(rockContext).GetListByIds(groupMemberIds).Where(gm => validGroupIds.Contains(gm.GroupId)).Distinct();
            int mailedCount  = 0;

            foreach (var groupMember in groupMembers)
            {
                var mergeFields = new Dictionary <string, object>
                {
                    { "GroupMember", groupMember },
                    { "Person", groupMember.Person },
                    { "Group", groupMember.Group }
                };

                var recipients = new List <string> {
                    groupMember.Person.Email
                };

                Email.Send(systemEmailTemplate.From.ResolveMergeFields(mergeFields), systemEmailTemplate.FromName.ResolveMergeFields(mergeFields), systemEmailTemplate.Subject.ResolveMergeFields(mergeFields), recipients, systemEmailTemplate.Body.ResolveMergeFields(mergeFields), appRoot, null, null);
                mailedCount++;
            }
            context.Result = string.Format("{0} reminders were sent ", mailedCount);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Sets the value on select.
        /// </summary>
        protected override void SetValueOnSelect()
        {
            var group = new GroupService(new RockContext()).Get(int.Parse(ItemId));

            SetValue(group);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            var      rockContext     = ( RockContext )serviceInstance.Context;

            if (selectionValues.Length >= 2)
            {
                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                List <Guid>        groupGuids         = selectionValues[0].Split(',').AsGuidList();
                var groupService = new GroupService(rockContext);
                var groupIds     = groupService.GetByGuids(groupGuids).Select(a => a.Id).Distinct().ToList();

                bool includeChildGroups = false;
                bool includeChildGroupsIncludeSelected = false;
                bool includeChildGroupsPlusDescendants = false;
                bool includeInactiveGroups             = false;
                if (selectionValues.Length >= 3)
                {
                    includeChildGroups = selectionValues[2].AsBooleanOrNull() ?? false;
                }

                if (selectionValues.Length >= 6)
                {
                    includeChildGroupsIncludeSelected = selectionValues[4].AsBooleanOrNull() ?? false;
                    includeChildGroupsPlusDescendants = selectionValues[5].AsBooleanOrNull() ?? false;
                }
                else if (includeChildGroups)
                {
                    // in case the selection was saved before these options where added
                    includeChildGroupsIncludeSelected = true;
                    includeChildGroupsPlusDescendants = true;
                }

                if (selectionValues.Length >= 7)
                {
                    includeInactiveGroups = selectionValues[6].AsBooleanOrNull() ?? true;
                }
                else
                {
                    // if options where saved before this option was added, set to false, even though it would have included inactive before
                    includeInactiveGroups = false;
                }

                GroupMemberStatus?groupMemberStatus = null;
                if (selectionValues.Length >= 4)
                {
                    groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>();
                }

                var groupMemberServiceQry = groupMemberService.Queryable();

                List <int> childGroupIds = new List <int>();

                if (includeChildGroups)
                {
                    foreach (var groupId in groupIds)
                    {
                        if (includeChildGroupsPlusDescendants)
                        {
                            // get all children and descendants of the selected group(s)
                            var descendants = groupService.GetAllDescendents(groupId);
                            if (!includeInactiveGroups)
                            {
                                descendants = descendants.Where(a => a.IsActive == true);
                            }

                            childGroupIds.AddRange(descendants.Select(a => a.Id).Distinct().ToList());
                        }
                        else
                        {
                            // get only immediate children of the selected group(s)
                            var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId);
                            if (!includeInactiveGroups)
                            {
                                childGroups = childGroups.Where(a => a.IsActive == true);
                            }

                            childGroupIds.AddRange(childGroups.Select(a => a.Id));
                        }
                    }

                    if (includeChildGroupsIncludeSelected)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId) || childGroupIds.Contains(xx.GroupId));
                    }
                    else
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => childGroupIds.Contains(xx.GroupId));
                    }
                }
                else
                {
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId));
                }

                if (groupMemberStatus.HasValue)
                {
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.GroupMemberStatus == groupMemberStatus.Value);
                }

                var groupRoleGuids = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => n.AsGuid()).ToList();
                if (groupRoleGuids.Count() > 0)
                {
                    var groupRoleIds = new GroupTypeRoleService(( RockContext )serviceInstance.Context).Queryable().Where(a => groupRoleGuids.Contains(a.Guid)).Select(a => a.Id).ToList();
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupRoleIds.Contains(xx.GroupRoleId));
                }

                if (selectionValues.Length >= 8)
                {
                    string    addedOnSlidingDelimitedValues = selectionValues[7].Replace(',', '|');
                    DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(addedOnSlidingDelimitedValues);
                    if (dateRange.Start.HasValue)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded >= dateRange.Start.Value);
                    }

                    if (dateRange.End.HasValue)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded < dateRange.End.Value);
                    }
                }

                IQueryable <PersonIdFirstAttendance> firstAttendanceDateQry = null;
                IQueryable <PersonIdLastAttendance>  lastAttendanceDateQry  = null;

                if (selectionValues.Length >= 10)
                {
                    List <int> attendanceGroupIds = null;
                    if (includeChildGroups)
                    {
                        if (includeChildGroupsIncludeSelected)
                        {
                            attendanceGroupIds = new List <int>();
                            attendanceGroupIds.AddRange(groupIds);
                            attendanceGroupIds.AddRange(childGroupIds);
                        }
                        else
                        {
                            attendanceGroupIds = childGroupIds;
                        }
                    }
                    else
                    {
                        attendanceGroupIds = groupIds;
                    }

                    var groupAttendanceQuery = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend == true && a.GroupId.HasValue && attendanceGroupIds.Contains(a.GroupId.Value));

                    string    firstAttendanceSlidingDelimitedValues = selectionValues[8].Replace(',', '|');
                    DateRange firstAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(firstAttendanceSlidingDelimitedValues);

                    if (firstAttendanceDateRange.Start.HasValue || firstAttendanceDateRange.End.HasValue)
                    {
                        firstAttendanceDateQry = groupAttendanceQuery
                                                 .GroupBy(xx => xx.PersonAlias.PersonId)
                                                 .Select(ss => new PersonIdFirstAttendance
                        {
                            PersonId = ss.Key,
                            FirstAttendanceSundayDate = ss.Min(a => a.SundayDate)
                        });

                        if (firstAttendanceDateRange.Start.HasValue)
                        {
                            firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate >= firstAttendanceDateRange.Start.Value);
                        }

                        if (firstAttendanceDateRange.End.HasValue)
                        {
                            firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate < firstAttendanceDateRange.End.Value);
                        }
                    }

                    string    lastAttendanceSlidingDelimitedValues = selectionValues[9].Replace(',', '|');
                    DateRange lastAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(lastAttendanceSlidingDelimitedValues);

                    if (lastAttendanceDateRange.Start.HasValue || lastAttendanceDateRange.End.HasValue)
                    {
                        lastAttendanceDateQry = groupAttendanceQuery
                                                .GroupBy(xx => xx.PersonAlias.PersonId)
                                                .Select(ss => new PersonIdLastAttendance
                        {
                            PersonId = ss.Key,
                            LastAttendanceSundayDate = ss.Max(a => a.SundayDate)
                        });

                        if (lastAttendanceDateRange.Start.HasValue)
                        {
                            lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate >= lastAttendanceDateRange.Start.Value);
                        }

                        if (lastAttendanceDateRange.End.HasValue)
                        {
                            lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate < lastAttendanceDateRange.End.Value);
                        }
                    }
                }

                IQueryable <Rock.Model.Person> qry = null;
                if (lastAttendanceDateQry == null && firstAttendanceDateQry == null)
                {
                    qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                          .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id));
                }
                else
                {
                    if (firstAttendanceDateQry != null && lastAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id) && lastAttendanceDateQry.Any(bb => bb.PersonId == p.Id));
                    }
                    else if (firstAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id));
                    }
                    else if (lastAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     lastAttendanceDateQry.Any(aa => aa.PersonId == p.Id));
                    }
                }

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                RockContext rockContext  = new RockContext();
                var         groupService = new GroupService(rockContext);

                Group         group           = null;
                Guid          personGuid      = Guid.Empty;
                GroupTypeRole groupMemberRole = null;

                // get group id from url
                Guid?groupGuid = PageParameter("GroupGuid").AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Guid == groupGuid.Value).FirstOrDefault();
                }

                if (group == null && GetAttributeValue("EnablePassingGroupId").AsBoolean(true))
                {
                    int?groupId = PageParameter("GroupId").AsIntegerOrNull();
                    if (groupId.HasValue)
                    {
                        group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Id == groupId).FirstOrDefault();
                    }
                }

                if (group == null)
                {
                    groupGuid = GetAttributeValue("DefaultGroup").AsGuidOrNull();
                    if (groupGuid.HasValue)
                    {
                        group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Guid == groupGuid.Value).FirstOrDefault();
                    }
                }

                if (group == null)
                {
                    lAlerts.Text = "Could not determine the group to add to.";
                    return;
                }

                // Validate the group type.
                if (!string.IsNullOrEmpty(GetAttributeValue("LimitGroupType")))
                {
                    bool groupTypeMatch = GetAttributeValue("LimitGroupType")
                                          .Split(',')
                                          .Contains(group.GroupType.Guid.ToString(), StringComparer.CurrentCultureIgnoreCase);

                    if (!groupTypeMatch)
                    {
                        lAlerts.Text = "Invalid group specified.";
                        return;
                    }
                }

                // get group role id from url
                if (Request["GroupMemberRoleId"] != null)
                {
                    int groupMemberRoleId = 0;
                    if (Int32.TryParse(Request["GroupMemberRoleId"], out groupMemberRoleId))
                    {
                        groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleId);
                    }
                }
                else if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultGroupMemberRole")))
                {
                    Guid groupMemberRoleGuid = Guid.Empty;
                    if (Guid.TryParse(GetAttributeValue("DefaultGroupMemberRole"), out groupMemberRoleGuid))
                    {
                        groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleGuid);
                    }
                }
                else
                {
                    groupMemberRole = group.GroupType.DefaultGroupRole;
                }

                if (groupMemberRole == null)
                {
                    lAlerts.Text += "Could not determine the group role to use for the add.";
                    return;
                }

                // get person
                if (Request["PersonGuid"] != null)
                {
                    Guid.TryParse(Request["PersonGuid"], out personGuid);
                }

                if (personGuid == Guid.Empty)
                {
                    lAlerts.Text += "A valid person identifier was not found in the page address.";
                    return;
                }

                // ensure that the group type has this role
                if (!group.GroupType.Roles.Contains(groupMemberRole))
                {
                    lAlerts.Text += "The group you have provided does not have the group member role configured.";
                    return;
                }

                // get person
                Person person = new PersonService(rockContext).Get(personGuid);

                if (person == null)
                {
                    lAlerts.Text += "A person could not be found for the identifier provided.";
                    return;
                }

                // hide alert
                divAlert.Visible = false;

                // get status
                var groupMemberStatus = this.GetAttributeValue("GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active);

                // load merge fields
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("GroupMemberStatus", groupMemberStatus.ToString());
                mergeFields.Add("Group", group);
                mergeFields.Add("Person", person);
                mergeFields.Add("Role", groupMemberRole);
                mergeFields.Add("CurrentPerson", CurrentPerson);

                // ensure that the person is not already in the group
                if (group.Members.Where(m => m.PersonId == person.Id && m.GroupRoleId == groupMemberRole.Id).Count() != 0)
                {
                    string templateInGroup = GetAttributeValue("AlreadyInGroupMessage");
                    lContent.Text = templateInGroup.ResolveMergeFields(mergeFields);
                    return;
                }


                // add person to group
                GroupMember groupMember = new GroupMember();
                groupMember.GroupId           = group.Id;
                groupMember.PersonId          = person.Id;
                groupMember.GroupRoleId       = groupMemberRole.Id;
                groupMember.GroupMemberStatus = groupMemberStatus;
                group.Members.Add(groupMember);

                try
                {
                    rockContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    divAlert.Visible = true;
                    lAlerts.Text     = String.Format("An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message);
                }

                string templateSuccess = GetAttributeValue("SuccessMessage");
                lContent.Text = templateSuccess.ResolveMergeFields(mergeFields);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Handles the SelectItem event of the gp 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 gp_SelectItem(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var groupIdList  = gp.SelectedValues.AsIntegerList();
            var groupService = new GroupService(rockContext);

            var qryGroups = groupService.GetByIds(groupIdList);

            if (qryGroups.Any())
            {
                var        groupTypeRoleService = new GroupTypeRoleService(rockContext);
                var        qryGroupTypeRoles    = groupTypeRoleService.Queryable();
                List <int> selectedGroupTypeIds = qryGroups.Select(a => a.GroupTypeId).Distinct().ToList();

                if (cbChildGroups.Checked)
                {
                    List <int> childGroupTypeIds = new List <int>();
                    foreach (var groupId in qryGroups.Select(a => a.Id).ToList())
                    {
                        if (cbChildGroupsPlusDescendants.Checked)
                        {
                            // get all children and descendants of the selected group(s)
                            var descendants = groupService.GetAllDescendents(groupId);
                            if (!cbIncludeInactiveGroups.Checked)
                            {
                                descendants = descendants.Where(a => a.IsActive == true);
                            }

                            childGroupTypeIds.AddRange(descendants.Select(a => a.GroupTypeId).Distinct().ToList());
                        }
                        else
                        {
                            // get only immediate children of the selected group(s)
                            var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId);
                            if (!cbIncludeInactiveGroups.Checked)
                            {
                                childGroups = childGroups.Where(a => a.IsActive == true);
                            }

                            childGroupTypeIds.AddRange(childGroups.Select(a => a.GroupTypeId).Distinct().ToList());
                        }
                    }

                    childGroupTypeIds = childGroupTypeIds.Distinct().ToList();

                    if (cbIncludeSelectedGroup.Checked)
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && (selectedGroupTypeIds.Contains(a.GroupTypeId.Value) || childGroupTypeIds.Contains(a.GroupTypeId.Value)));
                    }
                    else
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && childGroupTypeIds.Contains(a.GroupTypeId.Value));
                    }
                }
                else
                {
                    qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && selectedGroupTypeIds.Contains(a.GroupTypeId.Value));
                }

                var list = qryGroupTypeRoles.OrderBy(a => a.GroupType.Order).ThenBy(a => a.GroupType.Name).ThenBy(a => a.Order).ThenBy(a => a.Name).ToList();
                cblRole.Items.Clear();
                foreach (var item in list)
                {
                    cblRole.Items.Add(new ListItem(string.Format("{0} ({1})", item.Name, item.GroupType.Name), item.Guid.ToString()));
                }

                cblRole.Visible = list.Count > 0;
            }
            else
            {
                cblRole.Visible = false;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            if (controls.Count() < 8)
            {
                return;
            }

            GroupPicker            groupPicker                  = controls[0] as GroupPicker;
            RockCheckBox           cbChildGroups                = controls[1] as RockCheckBox;
            RockCheckBox           cbIncludeSelectedGroup       = controls[2] as RockCheckBox;
            RockCheckBox           cbChildGroupsPlusDescendants = controls[3] as RockCheckBox;
            RockCheckBoxList       cblRoles                       = controls[4] as RockCheckBoxList;
            RockDropDownList       ddlGroupMemberStatus           = controls[5] as RockDropDownList;
            RockCheckBox           cbIncludeInactive              = controls[6] as RockCheckBox;
            SlidingDateRangePicker addedOnDateRangePicker         = controls[7] as SlidingDateRangePicker;
            SlidingDateRangePicker firstAttendanceDateRangePicker = controls[9] as SlidingDateRangePicker;
            SlidingDateRangePicker lastAttendanceDateRangePicker  = controls[10] as SlidingDateRangePicker;

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                List <Guid> groupGuids = selectionValues[0].Split(',').AsGuidList();
                var         groups     = new GroupService(new RockContext()).GetByGuids(groupGuids);
                if (groups != null)
                {
                    groupPicker.SetValues(groups);
                }

                if (selectionValues.Length >= 3)
                {
                    cbChildGroups.Checked = selectionValues[2].AsBooleanOrNull() ?? false;
                }

                if (selectionValues.Length >= 6)
                {
                    cbIncludeSelectedGroup.Checked       = selectionValues[4].AsBooleanOrNull() ?? false;
                    cbChildGroupsPlusDescendants.Checked = selectionValues[5].AsBooleanOrNull() ?? false;
                }
                else
                {
                    cbIncludeSelectedGroup.Checked       = true;
                    cbChildGroupsPlusDescendants.Checked = true;
                }

                if (selectionValues.Length >= 7)
                {
                    cbIncludeInactiveGroups.Checked = selectionValues[6].AsBooleanOrNull() ?? false;
                }
                else
                {
                    // if options where saved before this option was added, set to false, even though it would have included inactive before
                    cbIncludeInactiveGroups.Checked = false;
                }

                gp_SelectItem(this, new EventArgs());

                string[] selectedRoleGuids = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var item in cblRoles.Items.OfType <ListItem>())
                {
                    item.Selected = selectedRoleGuids.Contains(item.Value);
                }

                if (selectionValues.Length >= 4)
                {
                    ddlGroupMemberStatus.SetValue(selectionValues[3]);
                }
                else
                {
                    ddlGroupMemberStatus.SetValue(string.Empty);
                }

                if (selectionValues.Length >= 8)
                {
                    // convert comma delimited to pipe
                    addedOnDateRangePicker.DelimitedValues = selectionValues[7].Replace(',', '|');
                }

                if (selectionValues.Length >= 10)
                {
                    // convert comma delimited to pipe
                    firstAttendanceDateRangePicker.DelimitedValues = selectionValues[8].Replace(',', '|');

                    // convert comma delimited to pipe
                    lastAttendanceDateRangePicker.DelimitedValues = selectionValues[9].Replace(',', '|');
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Formats the selection for the InGroupFilter/NotInGroupFilter based on if we are in "Not" mode
        /// </summary>
        /// <param name="selection">The selection.</param>
        /// <param name="not">if set to <c>true</c> [not].</param>
        /// <returns></returns>
        public virtual string GroupFilterFormatSelection(string selection, bool not)
        {
            string result = "Group Member";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                var rockContext = new RockContext();
                var groupGuids  = selectionValues[0].Split(',').AsGuidList();
                var groups      = new GroupService(rockContext).GetByGuids(groupGuids);

                var groupTypeRoleGuidList = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.AsGuid()).ToList();

                var groupTypeRoles = new GroupTypeRoleService(rockContext).Queryable().Where(a => groupTypeRoleGuidList.Contains(a.Guid)).ToList();

                bool   includeChildGroups = false;
                bool   includeChildGroupsPlusDescendants = false;
                bool   includeChildGroupsIncludeSelected = false;
                bool   includeInactiveGroups             = false;
                string addedOnDateRangeText         = null;
                string firstAttendanceDateRangeText = null;
                string lastAttendanceDateRangeText  = null;
                if (selectionValues.Length >= 3)
                {
                    includeChildGroups = selectionValues[2].AsBooleanOrNull() ?? false;
                    if (selectionValues.Length >= 6)
                    {
                        includeChildGroupsIncludeSelected = selectionValues[4].AsBooleanOrNull() ?? false;
                        includeChildGroupsPlusDescendants = selectionValues[5].AsBooleanOrNull() ?? false;
                    }

                    if (selectionValues.Length >= 7)
                    {
                        includeInactiveGroups = selectionValues[6].AsBooleanOrNull() ?? false;
                    }

                    if (selectionValues.Length >= 8)
                    {
                        // convert comma delimited to pipe then get date range text
                        addedOnDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[7].Replace(',', '|'));
                    }

                    if (selectionValues.Length >= 10)
                    {
                        // convert comma delimited to pipe then get date range text
                        firstAttendanceDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[8].Replace(',', '|'));

                        // convert comma delimited to pipe then get date range text
                        lastAttendanceDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[9].Replace(',', '|'));
                    }
                }

                GroupMemberStatus?groupMemberStatus = null;
                if (selectionValues.Length >= 4)
                {
                    groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>();
                }

                if (groups != null)
                {
                    result = string.Format(not ? "Not in groups: {0}" : "In groups: {0}", groups.Select(a => a.Name).ToList().AsDelimited(", ", " or "));
                    if (includeChildGroups)
                    {
                        if (includeChildGroupsPlusDescendants)
                        {
                            result += " or descendant groups";
                        }
                        else
                        {
                            result += " or child groups";
                        }

                        if (includeInactiveGroups)
                        {
                            result += ", including inactive groups";
                        }

                        if (!includeChildGroupsIncludeSelected)
                        {
                            result += ", not including selected groups";
                        }
                    }

                    if (groupTypeRoles.Count() > 0)
                    {
                        result += string.Format(", with role(s): {0}", groupTypeRoles.Select(a => string.Format("{0} ({1})", a.Name, a.GroupType.Name)).ToList().AsDelimited(","));
                    }

                    if (groupMemberStatus.HasValue)
                    {
                        result += string.Format(", with member status: {0}", groupMemberStatus.ConvertToString());
                    }

                    if (!string.IsNullOrEmpty(addedOnDateRangeText))
                    {
                        result += string.Format(", added to group in Date Range: {0}", addedOnDateRangeText);
                    }

                    if (!string.IsNullOrEmpty(firstAttendanceDateRangeText))
                    {
                        result += string.Format(", first attendance to group in Date Range: {0}", firstAttendanceDateRangeText);
                    }

                    if (!string.IsNullOrEmpty(lastAttendanceDateRangeText))
                    {
                        result += string.Format(", last attendance to  group in Date Range: {0}", lastAttendanceDateRangeText);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 17
0
 public MemberController()
 {
     groupService = new GroupService();
     mgrService   = new MemberGroupService();
 }
        /// <summary>
        /// Displays the edit group panel.
        /// </summary>
        private void DisplayEditGroup()
        {
            this.IsEditingGroup = true;

            if (_groupId != -1)
            {
                RockContext  rockContext  = new RockContext();
                GroupService groupService = new GroupService(rockContext);

                var qry = groupService
                          .Queryable("GroupLocations,GroupType,Schedule")
                          .Where(g => g.Id == _groupId);

                var group = qry.FirstOrDefault();

                if (group.IsAuthorized(Authorization.EDIT, CurrentPerson))
                {
                    tbName.Text        = group.Name;
                    tbDescription.Text = group.Description;
                    cbIsActive.Checked = group.IsActive;
                    cbIsPublic.Checked = group.IsPublic;

                    if ((group.GroupType.AllowedScheduleTypes & ScheduleType.Weekly) == ScheduleType.Weekly)
                    {
                        pnlSchedule.Visible = group.Schedule == null || group.Schedule.ScheduleType == ScheduleType.Weekly;
                        if (group.Schedule != null)
                        {
                            dowWeekly.SelectedDayOfWeek = group.Schedule.WeeklyDayOfWeek;
                            timeWeekly.SelectedTime     = group.Schedule.WeeklyTimeOfDay;
                        }
                        else
                        {
                            dowWeekly.SelectedDayOfWeek = null;
                            timeWeekly.SelectedTime     = null;
                        }
                    }
                    else
                    {
                        pnlSchedule.Visible = false;
                    }

                    nbGroupCapacity.Text = group.GroupCapacity.ToString();
                    bool enableGroupCapacityEdit = this.GetAttributeValue("EnableGroupCapacityEdit").AsBooleanOrNull() ?? false;
                    if (enableGroupCapacityEdit)
                    {
                        nbGroupCapacity.Visible = group.GroupType.GroupCapacityRule != GroupCapacityRule.None;
                    }

                    group.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(group, phAttributes, true, BlockValidationGroup);

                    // enable editing location
                    pnlGroupEditLocations.Visible = GetAttributeValue("EnableLocationEdit").AsBoolean();
                    if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                    {
                        ConfigureGroupLocationControls(group);

                        // set location tabs
                        rptLocationTypes.DataSource = _tabs;
                        rptLocationTypes.DataBind();
                    }
                }
                else
                {
                    lContent.Text = "<div class='alert alert-warning'>You do not have permission to edit this group.</div>";
                }
            }
            else
            {
                lContent.Text = "<div class='alert alert-warning'>No group was available from the querystring.</div>";
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSaveGroup 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 btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

            if (group != null && group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                group.Name        = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive    = cbIsActive.Checked;
                group.IsPublic    = cbIsPublic.Checked;

                if (pnlSchedule.Visible)
                {
                    if (group.Schedule == null)
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }

                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                if (nbGroupCapacity.Visible)
                {
                    group.GroupCapacity = nbGroupCapacity.Text.AsIntegerOrNull();
                }

                // set attributes
                group.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, group);

                // configure locations
                if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                {
                    // get selected location
                    Location location            = null;
                    int?     memberPersonAliasId = null;

                    if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
                    {
                        if (ddlMember.SelectedValue != null)
                        {
                            var ids = ddlMember.SelectedValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length == 2)
                            {
                                var dbLocation = new LocationService(rockContext).Get(int.Parse(ids[0]));
                                if (dbLocation != null)
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(int.Parse(ids[1]));
                            }
                        }
                    }
                    else
                    {
                        if (locpGroupLocation.Location != null)
                        {
                            location = new LocationService(rockContext).Get(locpGroupLocation.Location.Id);
                        }
                    }

                    if (location != null)
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location   = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

                rockContext.SaveChanges();
                group.SaveAttributeValues(rockContext);
            }

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
Exemplo n.º 20
0
 public ActivityScheduleController(RasporedContext context, ScheduleService scheduleService, GroupService groupService)
 {
     this._context        = context;
     this.scheduleService = scheduleService;
     this.groupService    = groupService;
 }
Exemplo n.º 21
0
    /// <summary>
    /// Binds the grid.
    /// </summary>
    private void BindGrid()
    {
        GroupService groupService = new GroupService();
        SortProperty sortProperty = gGroups.SortProperty;
        var qry = groupService.Queryable();

        List<int> groupTypeIds = AttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList();
        if ( groupTypeIds.Count > 0 )
        {
            qry = qry.Where( a => groupTypeIds.Contains( a.GroupTypeId ) );
        }

        if ( AttributeValue( "LimittoSecurityRoleGroups" ).FromTrueFalse() )
        {
            qry = qry.Where( a => a.IsSecurityRole );
        }

        if ( ContextEntities.ContainsKey( "Rock.Model.Group" ) )
        {
            Group parentGroup = ContextEntities["Rock.Model.Group"] as Group;
            if ( parentGroup != null )
            {
                qry = qry.Where( a => a.IsAncestorOfGroup( parentGroup.Id ) );
            }
        }

        if ( sortProperty != null )
        {
            gGroups.DataSource = qry.Sort( sortProperty ).ToList();
        }
        else
        {
            gGroups.DataSource = qry.OrderBy( p => p.Name ).ToList();
        }

        gGroups.DataBind();
    }
Exemplo n.º 22
0
        /// <summary>
        /// Handles the Click event of the lbMerge 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 lbMerge_Click(object sender, EventArgs e)
        {
            if (MergeData.People.Count < 2)
            {
                nbPeople.Visible = true;
                return;
            }

            bool reconfirmRequired = (MergeData.People.Select(p => p.Email).Distinct().Count() > 1 && MergeData.People.Where(p => p.HasLogins).Any());

            GetValuesSelection();

            int?primaryPersonId = null;

            var oldPhotos = new List <int>();

            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService       = new PersonService(rockContext);
                var userLoginService    = new UserLoginService(rockContext);
                var familyService       = new GroupService(rockContext);
                var familyMemberService = new GroupMemberService(rockContext);
                var binaryFileService   = new BinaryFileService(rockContext);
                var phoneNumberService  = new PhoneNumberService(rockContext);

                Person primaryPerson = personService.Get(MergeData.PrimaryPersonId ?? 0);
                if (primaryPerson != null)
                {
                    primaryPersonId = primaryPerson.Id;

                    var changes = new List <string>();

                    foreach (var p in MergeData.People.Where(p => p.Id != primaryPerson.Id))
                    {
                        changes.Add(string.Format("Merged <span class='field-value'>{0} [ID: {1}]</span> with this record.", p.FullName, p.Id));
                    }

                    // Photo Id
                    int?newPhotoId = MergeData.GetSelectedValue(MergeData.GetProperty("Photo")).Value.AsIntegerOrNull();
                    if (!primaryPerson.PhotoId.Equals(newPhotoId))
                    {
                        changes.Add("Modified the photo.");
                        primaryPerson.PhotoId = newPhotoId;
                    }

                    primaryPerson.TitleValueId              = GetNewIntValue("Title", changes);
                    primaryPerson.FirstName                 = GetNewStringValue("FirstName", changes);
                    primaryPerson.NickName                  = GetNewStringValue("NickName", changes);
                    primaryPerson.MiddleName                = GetNewStringValue("MiddleName", changes);
                    primaryPerson.LastName                  = GetNewStringValue("LastName", changes);
                    primaryPerson.SuffixValueId             = GetNewIntValue("Suffix", changes);
                    primaryPerson.RecordTypeValueId         = GetNewIntValue("RecordType", changes);
                    primaryPerson.RecordStatusValueId       = GetNewIntValue("RecordStatus", changes);
                    primaryPerson.RecordStatusReasonValueId = GetNewIntValue("RecordStatusReason", changes);
                    primaryPerson.ConnectionStatusValueId   = GetNewIntValue("ConnectionStatus", changes);
                    primaryPerson.IsDeceased                = GetNewBoolValue("Deceased", changes);
                    primaryPerson.Gender = (Gender)GetNewEnumValue("Gender", typeof(Gender), changes);
                    primaryPerson.MaritalStatusValueId = GetNewIntValue("MaritalStatus", changes);
                    primaryPerson.SetBirthDate(GetNewDateTimeValue("BirthDate", changes));
                    primaryPerson.AnniversaryDate = GetNewDateTimeValue("AnniversaryDate", changes);
                    primaryPerson.GraduationYear  = GetNewIntValue("GraduationYear", changes);
                    primaryPerson.Email           = GetNewStringValue("Email", changes);
                    primaryPerson.IsEmailActive   = GetNewBoolValue("EmailActive", changes);
                    primaryPerson.EmailNote       = GetNewStringValue("EmailNote", changes);
                    primaryPerson.EmailPreference = (EmailPreference)GetNewEnumValue("EmailPreference", typeof(EmailPreference), changes);
                    primaryPerson.SystemNote      = GetNewStringValue("InactiveReasonNote", changes);
                    primaryPerson.SystemNote      = GetNewStringValue("SystemNote", changes);

                    // Update phone numbers
                    var phoneTypes = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE.AsGuid()).DefinedValues;
                    foreach (var phoneType in phoneTypes)
                    {
                        var phoneNumber = primaryPerson.PhoneNumbers.Where(p => p.NumberTypeValueId == phoneType.Id).FirstOrDefault();
                        string oldValue = phoneNumber != null ? phoneNumber.Number : string.Empty;

                        string key      = "phone_" + phoneType.Id.ToString();
                        string newValue = GetNewStringValue(key, changes);

                        if (!oldValue.Equals(newValue, StringComparison.OrdinalIgnoreCase))
                        {
                            // New phone doesn't match old

                            if (!string.IsNullOrWhiteSpace(newValue))
                            {
                                // New value exists
                                if (phoneNumber == null)
                                {
                                    // Old value didn't exist... create new phone record
                                    phoneNumber = new PhoneNumber {
                                        NumberTypeValueId = phoneType.Id
                                    };
                                    primaryPerson.PhoneNumbers.Add(phoneNumber);
                                }

                                // Update phone number
                                phoneNumber.Number = newValue;
                            }
                            else
                            {
                                // New value doesn't exist
                                if (phoneNumber != null)
                                {
                                    // old value existed.. delete it
                                    primaryPerson.PhoneNumbers.Remove(phoneNumber);
                                    phoneNumberService.Delete(phoneNumber);
                                }
                            }
                        }
                    }

                    // Save the new record
                    rockContext.SaveChanges();

                    // Update the attributes
                    primaryPerson.LoadAttributes(rockContext);
                    foreach (var property in MergeData.Properties.Where(p => p.Key.StartsWith("attr_")))
                    {
                        string attributeKey = property.Key.Substring(5);
                        string oldValue     = primaryPerson.GetAttributeValue(attributeKey) ?? string.Empty;
                        string newValue     = GetNewStringValue(property.Key, changes) ?? string.Empty;

                        if (!oldValue.Equals(newValue))
                        {
                            var attribute = primaryPerson.Attributes[attributeKey];
                            Rock.Attribute.Helper.SaveAttributeValue(primaryPerson, attribute, newValue, rockContext);
                        }
                    }

                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                               primaryPerson.Id, changes);

                    // Delete the unselected photos
                    string photoKeeper = primaryPerson.PhotoId.HasValue ? primaryPerson.PhotoId.Value.ToString() : string.Empty;
                    foreach (var photoValue in MergeData.Properties
                             .Where(p => p.Key == "Photo")
                             .SelectMany(p => p.Values)
                             .Where(v => v.Value != "" && v.Value != photoKeeper)
                             .Select(v => v.Value))
                    {
                        int photoId = 0;
                        if (int.TryParse(photoValue, out photoId))
                        {
                            var photo = binaryFileService.Get(photoId);
                            if (photo != null)
                            {
                                string errorMessages;
                                if (binaryFileService.CanDelete(photo, out errorMessages))
                                {
                                    binaryFileService.Delete(photo);
                                }
                            }
                        }
                    }
                    rockContext.SaveChanges();

                    // Delete merged person's family records and any families that would be empty after merge
                    foreach (var p in MergeData.People.Where(p => p.Id != primaryPersonId.Value))
                    {
                        // Delete the merged person's phone numbers (we've already updated the primary persons values)
                        foreach (var phoneNumber in phoneNumberService.GetByPersonId(p.Id))
                        {
                            phoneNumberService.Delete(phoneNumber);
                        }

                        // If there was more than one email address and user has logins, then set any of the local
                        // logins ( database & AD ) to require a reconfirmation
                        if (reconfirmRequired)
                        {
                            foreach (var login in userLoginService.GetByPersonId(p.Id))
                            {
                                var component = Rock.Security.AuthenticationContainer.GetComponent(login.EntityType.Name);
                                if (!component.RequiresRemoteAuthentication)
                                {
                                    login.IsConfirmed = false;
                                }
                            }
                        }

                        rockContext.SaveChanges();

                        // Delete the merged person's other family member records and the family if they were the only one in the family
                        Guid familyGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        foreach (var familyMember in familyMemberService.Queryable().Where(m => m.PersonId == p.Id && m.Group.GroupType.Guid == familyGuid))
                        {
                            familyMemberService.Delete(familyMember);

                            rockContext.SaveChanges();

                            // Get the family
                            var family = familyService.Queryable("Members").Where(f => f.Id == familyMember.GroupId).FirstOrDefault();
                            if (!family.Members.Any())
                            {
                                // If there are not any other family members, delete the family record.

                                var oldFamilyChanges = new List <string>();
                                History.EvaluateChange(oldFamilyChanges, "Family", family.Name, string.Empty);
                                HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                           primaryPersonId.Value, oldFamilyChanges, family.Name, typeof(Group), family.Id);

                                // If theres any people that have this group as a giving group, set it to null (the person being merged should be the only one)
                                foreach (Person gp in personService.Queryable().Where(g => g.GivingGroupId == family.Id))
                                {
                                    gp.GivingGroupId = null;
                                }

                                // Delete the family
                                familyService.Delete(family);

                                rockContext.SaveChanges();
                            }
                        }
                    }
                }
            });

            foreach (var p in MergeData.People.Where(p => p.Id != primaryPersonId.Value))
            {
                // Run merge proc to merge all associated data
                var parms = new Dictionary <string, object>();
                parms.Add("OldId", p.Id);
                parms.Add("NewId", primaryPersonId.Value);
                DbService.ExecuteCommand("spCrm_PersonMerge", CommandType.StoredProcedure, parms);
            }

            NavigateToLinkedPage("PersonDetailPage", "PersonId", primaryPersonId.Value);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Updates Group Historical for any groups that have data group history enabled
        /// </summary>
        /// <param name="context">The context.</param>
        public void UpdateGroupHistorical(IJobExecutionContext context)
        {
            var rockContext            = new RockContext();
            var groupHistoricalService = new GroupHistoricalService(rockContext);
            var groupService           = new GroupService(rockContext);

            // Note that this query utilizes .AsNoFilter() to avoid having archived groups filtered out by the GroupConfiguration class.
            var groupsWithHistoryEnabledQuery = groupService.AsNoFilter()
                                                .Where(a => a.GroupType.EnableGroupHistory == true)
                                                .AsNoTracking();

            var groupHistoricalsCurrentQuery = groupHistoricalService.Queryable().Where(a => a.CurrentRowIndicator == true).AsNoTracking();

            // Mark GroupHistorical Rows as History ( CurrentRowIndicator = false, etc ) if any of the tracked field values change
            var groupHistoricalNoLongerCurrent = groupHistoricalsCurrentQuery.Join(
                groupsWithHistoryEnabledQuery,
                gh => gh.GroupId,
                g => g.Id, (gh, g) => new
            {
                Group           = g,
                GroupHistorical = gh
            })
                                                 .Where(a =>
                                                        a.Group.Name != a.GroupHistorical.GroupName ||
                                                        a.Group.GroupType.Name != a.GroupHistorical.GroupTypeName ||
                                                        a.Group.CampusId != a.GroupHistorical.CampusId ||
                                                        a.Group.ParentGroupId != a.GroupHistorical.ParentGroupId ||
                                                        a.Group.ScheduleId != a.GroupHistorical.ScheduleId ||
                                                        (a.Group.ScheduleId.HasValue && (a.Group.Schedule.ModifiedDateTime != a.GroupHistorical.ScheduleModifiedDateTime)) ||
                                                        a.Group.Description != a.GroupHistorical.Description ||
                                                        a.Group.StatusValueId != a.GroupHistorical.StatusValueId ||
                                                        a.Group.IsArchived != a.GroupHistorical.IsArchived ||
                                                        a.Group.ArchivedDateTime != a.GroupHistorical.ArchivedDateTime ||
                                                        a.Group.ArchivedByPersonAliasId != a.GroupHistorical.ArchivedByPersonAliasId ||
                                                        a.Group.IsActive != a.GroupHistorical.IsActive ||
                                                        a.Group.InactiveDateTime != a.GroupHistorical.InactiveDateTime
                                                        ).Select(a => a.GroupHistorical).AsNoTracking();

            var effectiveExpireDateTime = RockDateTime.Now;

            int groupsLoggedToHistory      = 0;
            int groupsSaveToHistoryCurrent = 0;

            if (groupHistoricalNoLongerCurrent.Any())
            {
                groupsLoggedToHistory = rockContext.BulkUpdate(groupHistoricalNoLongerCurrent, gh => new GroupHistorical
                {
                    CurrentRowIndicator = false,
                    ExpireDateTime      = effectiveExpireDateTime
                });
            }

            // Insert Groups (that have GroupType.EnableGroupHistory) that don't have a CurrentRowIndicator row yet ( or don't have a CurrentRowIndicator because it was stamped with CurrentRowIndicator=false )
            var groupsToAddToHistoricalCurrentsQuery = groupsWithHistoryEnabledQuery.Where(g => !groupHistoricalsCurrentQuery.Any(gh => gh.GroupId == g.Id)).AsNoTracking();

            if (groupsToAddToHistoricalCurrentsQuery.Any())
            {
                List <GroupHistorical> groupHistoricalCurrentsToInsert = groupsToAddToHistoricalCurrentsQuery
                                                                         .Include(a => a.GroupType)
                                                                         .Include(a => a.Schedule)
                                                                         .ToList()
                                                                         .Select(g => GroupHistorical.CreateCurrentRowFromGroup(g, effectiveExpireDateTime)).ToList();

                groupsSaveToHistoryCurrent = groupHistoricalCurrentsToInsert.Count();

                rockContext.BulkInsert(groupHistoricalCurrentsToInsert);
            }

            if (groupsLoggedToHistory > 0)
            {
                _jobStatusMessages.Add($"Logged {groupsLoggedToHistory} {"group history snapshot".PluralizeIf( groupsLoggedToHistory != 0 )}");
            }

            if (groupsSaveToHistoryCurrent > 0)
            {
                int newGroupsAddedToHistory = groupsSaveToHistoryCurrent - groupsLoggedToHistory;
                if (newGroupsAddedToHistory > 0)
                {
                    _jobStatusMessages.Add($"Added {newGroupsAddedToHistory} new {"group history snapshot".PluralizeIf( newGroupsAddedToHistory != 0 )}");
                }
            }
        }
Exemplo n.º 24
0
        private void ShowReadonlyDetails()
        {
            hfMode.Value = "View";

            HideSecondaryBlocks(false);

            if (Workflow != null)
            {
                if (_canView)
                {
                    if (Workflow.WorkflowType != null)
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                        mergeFields.Add("Workflow", Workflow);
                        lSummary.Text = Workflow.WorkflowType.SummaryViewText.ResolveMergeFields(mergeFields, CurrentPerson);
                    }

                    tdName.Description   = Workflow.Name;
                    tdStatus.Description = Workflow.Status;

                    if (Workflow.InitiatorPersonAlias != null && Workflow.InitiatorPersonAlias.Person != null)
                    {
                        var person = Workflow.InitiatorPersonAlias.Person;
                        tdInitiator.Description = string.Format("<a href='{0}{1}'>{2}</a>",
                                                                ResolveRockUrl("~/Person/"), person.Id, person.FullName);
                    }
                    else
                    {
                        tdInitiator.Description = string.Empty;
                    }

                    if (Workflow.ActivatedDateTime.HasValue)
                    {
                        tdActivatedWhen.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.ActivatedDateTime.Value.ToShortDateString(),
                                                                    Workflow.ActivatedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.ActivatedDateTime.Value.ToRelativeDateString());
                    }

                    if (Workflow.LastProcessedDateTime.HasValue)
                    {
                        tdLastProcessed.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.LastProcessedDateTime.Value.ToShortDateString(),
                                                                    Workflow.LastProcessedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.LastProcessedDateTime.Value.ToRelativeDateString());
                    }

                    if (Workflow.CompletedDateTime.HasValue)
                    {
                        tdCompletedWhen.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.CompletedDateTime.Value.ToShortDateString(),
                                                                    Workflow.CompletedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.CompletedDateTime.Value.ToRelativeDateString());
                    }

                    ShowAttributeValues();

                    var rockContext = new RockContext();
                    _personAliasService       = new PersonAliasService(rockContext);
                    _groupService             = new GroupService(rockContext);
                    rptrActivities.DataSource = Workflow.Activities.OrderBy(a => a.ActivatedDateTime).ToList();
                    rptrActivities.DataBind();

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

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

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }
                }
            }

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

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

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

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

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

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

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

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

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

            return(true);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var rockContext = new RockContext();

            var communicationTemplateService           = new CommunicationTemplateService(rockContext);
            var communicationTemplateAttachmentService = new CommunicationTemplateAttachmentService(rockContext);
            var binaryFileService = new BinaryFileService(rockContext);

            CommunicationTemplate communicationTemplate = null;
            var communicationTemplateId = hfCommunicationTemplateId.Value.AsIntegerOrNull();

            if (communicationTemplateId.HasValue)
            {
                communicationTemplate = communicationTemplateService.Get(communicationTemplateId.Value);
            }

            var newTemplate = false;

            if (communicationTemplate == null)
            {
                newTemplate           = true;
                communicationTemplate = new CommunicationTemplate();
                communicationTemplateService.Add(communicationTemplate);
            }

            communicationTemplate.Name        = tbName.Text;
            communicationTemplate.IsActive    = cbIsActive.Checked;
            communicationTemplate.Description = tbDescription.Text;

            if (communicationTemplate.ImageFileId != imgTemplatePreview.BinaryFileId)
            {
                var oldImageTemplatePreview = binaryFileService.Get(communicationTemplate.ImageFileId ?? 0);
                if (oldImageTemplatePreview != null)
                {
                    // the old image template preview won't be needed anymore, so make it IsTemporary and have it get cleaned up later
                    oldImageTemplatePreview.IsTemporary = true;
                }
            }

            communicationTemplate.ImageFileId = imgTemplatePreview.BinaryFileId;

            // Ensure that the ImagePreview is not set as IsTemporary=True
            if (communicationTemplate.ImageFileId.HasValue)
            {
                var imageTemplatePreview = binaryFileService.Get(communicationTemplate.ImageFileId.Value);
                if (imageTemplatePreview != null && imageTemplatePreview.IsTemporary)
                {
                    imageTemplatePreview.IsTemporary = false;
                }
            }

            // Note: If the Logo has changed, we can't get rid of it since existing communications might use it
            communicationTemplate.LogoBinaryFileId = imgTemplateLogo.BinaryFileId;

            // Ensure that the ImagePreview is not set as IsTemporary=True
            if (communicationTemplate.LogoBinaryFileId.HasValue)
            {
                var newImageTemplateLogo = binaryFileService.Get(communicationTemplate.LogoBinaryFileId.Value);
                if (newImageTemplateLogo != null && newImageTemplateLogo.IsTemporary)
                {
                    newImageTemplateLogo.IsTemporary = false;
                }
            }

            communicationTemplate.FromName           = tbFromName.Text;
            communicationTemplate.FromEmail          = tbFromAddress.Text;
            communicationTemplate.ReplyToEmail       = tbReplyToAddress.Text;
            communicationTemplate.CCEmails           = tbCCList.Text;
            communicationTemplate.BCCEmails          = tbBCCList.Text;
            communicationTemplate.LavaFields         = kvlMergeFields.Value.AsDictionaryOrNull();
            communicationTemplate.CssInliningEnabled = cbCssInliningEnabled.Checked;

            var binaryFileIds = hfAttachedBinaryFileIds.Value.SplitDelimitedValues().AsIntegerList();

            // delete any attachments that are no longer included
            foreach (var attachment in communicationTemplate.Attachments
                     .Where(a => !binaryFileIds.Contains(a.BinaryFileId)).ToList())
            {
                communicationTemplate.Attachments.Remove(attachment);
                communicationTemplateAttachmentService.Delete(attachment);
            }

            // add any new attachments that were added
            foreach (var attachmentBinaryFileId in binaryFileIds.Where(a => communicationTemplate.Attachments.All(x => x.BinaryFileId != a)))
            {
                communicationTemplate.Attachments.Add(new CommunicationTemplateAttachment {
                    BinaryFileId = attachmentBinaryFileId, CommunicationType = CommunicationType.Email
                });
            }

            communicationTemplate.Subject = tbEmailSubject.Text;
            communicationTemplate.Message = ceEmailTemplate.Text;

            communicationTemplate.SMSFromDefinedValueId = dvpSMSFrom.SelectedValue.AsIntegerOrNull();
            communicationTemplate.SMSMessage            = tbSMSTextMessage.Text;

            communicationTemplate.CategoryId = cpCategory.SelectedValueAsInt();

            rockContext.SaveChanges();

            var personalView = GetAttributeValue("PersonalTemplatesView").AsBoolean();

            if (newTemplate)
            {
                communicationTemplate = communicationTemplateService.Get(communicationTemplate.Id);
                if (communicationTemplate != null)
                {
                    if (personalView)
                    {
                        // If editing personal templates, make the new template is private/personal to current user
                        communicationTemplate.MakePrivate(Authorization.VIEW, CurrentPerson);
                        communicationTemplate.MakePrivate(Authorization.EDIT, CurrentPerson);
                        communicationTemplate.MakePrivate(Authorization.ADMINISTRATE, CurrentPerson);
                    }
                    else
                    {
                        // Otherwise, make sure user can view and edit the new template.
                        if (!communicationTemplate.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            communicationTemplate.AllowPerson(Authorization.VIEW, CurrentPerson);
                        }

                        // Make sure user can edit the new template.
                        if (!communicationTemplate.IsAuthorized(Authorization.EDIT, CurrentPerson))
                        {
                            communicationTemplate.AllowPerson(Authorization.EDIT, CurrentPerson);
                        }
                    }

                    // Always make sure RSR-Admin and Communication Admin can see
                    var groupService = new GroupService(rockContext);
                    var communicationAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_COMMUNICATION_ADMINISTRATORS.AsGuid());
                    if (communicationAdministrators != null)
                    {
                        communicationTemplate.AllowSecurityRole(Authorization.VIEW, communicationAdministrators, rockContext);
                        communicationTemplate.AllowSecurityRole(Authorization.EDIT, communicationAdministrators, rockContext);
                        communicationTemplate.AllowSecurityRole(Authorization.ADMINISTRATE, communicationAdministrators, rockContext);
                    }

                    var rockAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                    if (rockAdministrators != null)
                    {
                        communicationTemplate.AllowSecurityRole(Authorization.VIEW, rockAdministrators, rockContext);
                        communicationTemplate.AllowSecurityRole(Authorization.EDIT, rockAdministrators, rockContext);
                        communicationTemplate.AllowSecurityRole(Authorization.ADMINISTRATE, rockAdministrators, rockContext);
                    }
                }
            }

            NavigateToParentPage();
        }
Exemplo n.º 27
0
        public Group_ElectionViewModel(Election election, Guid?userId)
        {
            if (election != null)
            {
                Id               = election.Id;
                Title            = election.Title;
                Stage            = (ElectionStage)election.Stage;
                Quorum           = election.Quorum;
                Turnout          = election.Turnout;
                GroupModersCount = election.Group.ModeratorsCount;
                About            = new Group_Election_AboutViewModel(election);

                GroupMember gm = null;
                if (userId.HasValue && election.GroupId.HasValue)
                {
                    gm = GroupService.UserInGroup(userId.Value, election.GroupId.Value);
                }

                IEnumerable <Candidate> candidates = election.Candidates.Where(x => x.Petition != null).OrderByDescending(x => x.Petition.Signers.Count);
                candidates = candidates.Union(election.Candidates.Where(x => x.Petition == null));
                if (election.Stage != (byte)ElectionStage.Agitation)
                {
                    candidates = candidates.Where(x => x.Status == (byte)CandidateStatus.Confirmed);
                }
                Candidates = candidates.Select(x => new Group_Election_CandidateViewModel(x, gm)).ToList();
                Winners    = election.Candidates
                             .Where(x => x.Status == (byte)CandidateStatus.Winner)
                             .OrderByDescending(x => x.Electorate.Count)
                             .Select(x => new Group_Election_CandidateViewModel(x, gm))
                             .ToList();

                switch (Stage)
                {
                case ElectionStage.Agitation: ElectionCandidates = new Group_ElectionCandidatesViewModel(election, userId); break;

                case ElectionStage.Voting: ElectionVoting = new Group_ElectionVotingViewModel(election, userId); break;
                }
            }
            else
            {
                Candidates         = new List <Group_Election_CandidateViewModel>();
                Winners            = new List <Group_Election_CandidateViewModel>();
                About              = new Group_Election_AboutViewModel();
                ElectionCandidates = new Group_ElectionCandidatesViewModel();
                ElectionVoting     = new Group_ElectionVotingViewModel();
            }

            if (UserContext.Current != null)
            {
                var candidate = Candidates.FirstOrDefault(x => x.UserId == UserContext.Current.Id);
                if (candidate != null)
                {
                    IsCandidate = true;
                    CandidateId = candidate.Id;
                }
                else
                {
                    CandidateId = null;
                }
            }
        }
Exemplo n.º 28
0
        public static List <CheckInLabel> GenerateLabels(List <Person> people, Device kioskDevice, Guid?aggregateLabelGuid)
        {
            var labels            = new List <CheckInLabel>();
            var globalAttributes  = Rock.Web.Cache.GlobalAttributesCache.Get();
            var globalMergeValues = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            RockContext       rockContext       = new RockContext();
            AttendanceService attendanceService = new AttendanceService(rockContext);

            foreach (var person in people)
            {
                var attendances = AttendanceCache.All()
                                  .Where(a => a.PersonId == person.Id && a.AttendanceState != AttendanceState.CheckedOut)
                                  .ToList();

                if (!attendances.Any())
                {
                    continue;
                }

                var groupIds = attendances.Select(a => a.GroupId).Distinct().ToList();

                GroupService groupService = new GroupService(new RockContext());
                var          groupTypeIds = groupService.Queryable()
                                            .Where(g => groupIds.Contains(g.Id))
                                            .Select(g => g.GroupTypeId)
                                            .Distinct()
                                            .ToList();

                var groupTypes = groupTypeIds
                                 .Select(i => GroupTypeCache.Get(i))
                                 .OrderBy(gt => gt.Order)
                                 .ToList();

                List <Guid> labelGuids = new List <Guid>();

                var mergeObjects = new Dictionary <string, object>();
                foreach (var keyValue in globalMergeValues)
                {
                    mergeObjects.Add(keyValue.Key, keyValue.Value);
                }

                var checkinPerson = new CheckInPerson
                {
                    Person       = person,
                    SecurityCode = attendances.OrderByDescending(a => a.CreatedDateTime).FirstOrDefault().Code
                };

                mergeObjects.Add("Person", checkinPerson);
                mergeObjects.Add("GroupTypes", groupTypes);
                List <Rock.Model.Group> mergeGroups    = new List <Rock.Model.Group>();
                List <Location>         mergeLocations = new List <Location>();
                List <Schedule>         mergeSchedules = new List <Schedule>();

                var sets = attendanceService
                           .Queryable().AsNoTracking().Where(a =>
                                                             a.PersonAlias.Person.Id == person.Id &&
                                                             a.StartDateTime >= Rock.RockDateTime.Today &&
                                                             a.EndDateTime == null &&
                                                             a.Occurrence.Group != null &&
                                                             a.Occurrence.Schedule != null &&
                                                             a.Occurrence.Location != null
                                                             )
                           .Select(a =>
                                   new
                {
                    Group          = a.Occurrence.Group,
                    Location       = a.Occurrence.Location,
                    Schedule       = a.Occurrence.Schedule,
                    AttendanceGuid = a.Guid
                }
                                   )
                           .ToList()
                           .OrderBy(a => a.Schedule.StartTimeOfDay);

                //Load breakout group
                var breakoutGroupItems = GetBreakoutGroupItems(person);

                //Add in an empty object as a placeholder for our breakout group
                mergeObjects.Add("BreakoutGroup", "");

                //Add in GUID for QR code
                if (sets.Any())
                {
                    mergeObjects.Add("AttendanceGuid", sets.FirstOrDefault().AttendanceGuid.ToString());
                }

                foreach (var set in sets)
                {
                    mergeGroups.Add(set.Group);
                    mergeLocations.Add(set.Location);
                    mergeSchedules.Add(set.Schedule);

                    //Add the breakout group mergefield
                    if (breakoutGroupItems.Any())
                    {
                        var breakoutGroupItem = breakoutGroupItems.Where(g => g.ScheduleId == set.Schedule.Id).FirstOrDefault();
                        if (breakoutGroupItem != null)
                        {
                            mergeObjects["BreakoutGroup"] = breakoutGroupItem.Letter;
                        }
                    }
                }
                mergeObjects.Add("Groups", mergeGroups);
                mergeObjects.Add("Locations", mergeLocations);
                mergeObjects.Add("Schedules", mergeSchedules);

                foreach (var groupType in groupTypes)
                {
                    var groupTypeLabels = new List <CheckInLabel>();

                    GetGroupTypeLabels(groupType, groupTypeLabels, mergeObjects, labelGuids);

                    var PrinterIPs = new Dictionary <int, string>();

                    foreach (var label in groupTypeLabels)
                    {
                        label.PrintFrom = kioskDevice.PrintFrom;
                        label.PrintTo   = kioskDevice.PrintToOverride;

                        if (label.PrintTo == PrintTo.Default)
                        {
                            label.PrintTo = groupType.AttendancePrintTo;
                        }

                        if (label.PrintTo == PrintTo.Kiosk)
                        {
                            var device = kioskDevice;
                            if (device != null)
                            {
                                label.PrinterDeviceId = device.PrinterDeviceId;
                            }
                        }

                        if (label.PrinterDeviceId.HasValue)
                        {
                            if (PrinterIPs.ContainsKey(label.PrinterDeviceId.Value))
                            {
                                label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value];
                            }
                            else
                            {
                                var printerDevice = new DeviceService(rockContext).Get(label.PrinterDeviceId.Value);
                                if (printerDevice != null)
                                {
                                    PrinterIPs.Add(printerDevice.Id, printerDevice.IPAddress);
                                    label.PrinterAddress = printerDevice.IPAddress;
                                }
                            }
                        }
                        labels.Add(label);
                    }
                }
            }
            if (aggregateLabelGuid.HasValue)
            {
                labels.AddRange(GenerateAggregateLabel(aggregateLabelGuid.Value, kioskDevice, people));
            }

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

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

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

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

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

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

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("Provided group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

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

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

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

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

            return(true);
        }
Exemplo n.º 30
0
        public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            var settings = new ParticipationRateSelectSettings(selection);

            if (!settings.IsValid())
            {
                return(this.GetDefaultSelectExpression(context, entityIdProperty));
            }

            // Get the Person Data View that defines the set of candidates from which matching Group Members can be selected.
            DataView dataView = null;

            if (settings.DataViewGuid.HasValue)
            {
                var dsService = new DataViewService(context);

                dataView = dsService.Get(settings.DataViewGuid.Value);

                // Verify that there is not a child filter that uses this view (would result in stack-overflow error)
                if (dsService.IsViewInFilter(dataView.Id, dataView.DataViewFilter))
                {
                    throw new Exception("Filter issue(s): One of the filters contains a circular reference to the Data View itself.");
                }
            }

            if (dataView == null ||
                dataView.DataViewFilter == null)
            {
                return(this.GetDefaultSelectExpression(context, entityIdProperty));
            }

            // Evaluate the Data View that defines the candidate population.
            List <string> errorMessages;

            var personService = new PersonService(context);

            var personQuery = personService.Queryable();

            var paramExpression = personService.ParameterExpression;

            var whereExpression = dataView.GetExpression(personService, paramExpression, out errorMessages);

            if (errorMessages.Any())
            {
                throw new Exception("Filter issue(s): " + errorMessages.AsDelimited("; "));
            }

            personQuery = personQuery.Where(paramExpression, whereExpression, null);

            var populationIds = personQuery.Select(x => x.Id);

            // Construct the Query to return the measure of matches for each Group.
            IQueryable <decimal> resultQuery;

            switch (settings.MeasureType)
            {
            case MeasureTypeSpecifier.ParticipationRateOfGroup:
            {
                // Percentage of Group Members that are also in the candidate population.
                resultQuery = new GroupService(context).Queryable()
                              .Select(p => (p.Members.Count == 0) ? 0 : ((decimal)p.Members.Count(a => (populationIds.Contains(a.PersonId))) / (decimal)p.Members.Count) * 100);
            }
            break;

            case MeasureTypeSpecifier.ParticipationRateOfCandidates:
            {
                // Percentage of candidate population that are also Group Members.
                decimal populationCount = populationIds.Count();

                resultQuery = new GroupService(context).Queryable()
                              .Select(p => (p.Members.Count == 0) ? 0 : ((decimal)p.Members.Count(a => (populationIds.Contains(a.PersonId))) / populationCount) * 100);
            }
            break;

            case MeasureTypeSpecifier.NumberOfParticipants:
            default:
            {
                // Number
                resultQuery = new GroupService(context).Queryable()
                              .Select(p => (decimal)p.Members.Count(a => populationIds.Contains(a.PersonId)));
            }
            break;
            }

            var selectExpression = SelectExpressionExtractor.Extract <Rock.Model.Group>(resultQuery, entityIdProperty, "p");

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

            // get person
            Person person = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

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

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

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorkflowAttributeValue(GetAttributeValue(action, "LocationTypeAttribute").AsGuid());

            if (locationTypeAttributeValue != null)
            {
                locationType = DefinedValueCache.Get(locationTypeAttributeValue.AsGuid());
            }
            if (locationType == null)
            {
                locationType = DefinedValueCache.Get(GetAttributeValue(action, "LocationType").AsGuid());
            }
            if (locationType == null)
            {
                errorMessages.Add("The location type to be updated was not selected.");
                return(false);
            }

            // get the new phone number value
            Location location      = null;
            string   locationValue = GetAttributeValue(action, "Location");
            Guid?    locationGuid  = locationValue.AsGuidOrNull();

            if (!locationGuid.HasValue || locationGuid.Value.IsEmpty())
            {
                string locationAttributeValue     = GetAttributeValue(action, "LocationAttribute");
                Guid?  locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if (locationAttributeValueGuid.HasValue)
                {
                    locationGuid = action.GetWorkflowAttributeValue(locationAttributeValueGuid.Value).AsGuidOrNull();
                }
            }

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

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

            // gets value indicating if location is a mailing location
            string mailingValue     = GetAttributeValue(action, "IsMailing");
            Guid?  mailingValueGuid = mailingValue.AsGuidOrNull();

            if (mailingValueGuid.HasValue)
            {
                mailingValue = action.GetWorkflowAttributeValue(mailingValueGuid.Value);
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue     = GetAttributeValue(action, "IsMapped");
            Guid?  mappedValueGuid = mappedValue.AsGuidOrNull();

            if (mappedValueGuid.HasValue)
            {
                mappedValue = action.GetWorkflowAttributeValue(mappedValueGuid.Value);
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mapped = mappedValue.AsBooleanOrNull();

            var savePreviousAddress = GetAttributeValue(action, "SavePreviousAddress").AsBoolean();

            var locationService = new LocationService(rockContext);

            locationService.Verify(location, false);

            var groupLocationService = new GroupLocationService(rockContext);

            foreach (var family in person.GetFamilies(rockContext).ToList())
            {
                bool locationUpdated = false;

                if (savePreviousAddress)
                {
                    // Get all existing addresses of the specified type
                    var groupLocations = family.GroupLocations.Where(l => l.GroupLocationTypeValueId == locationType.Id).ToList();

                    // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                    // Use the specified Is Mailing and Is Mapped values from the action's parameters if they are set,
                    // otherwise set them to true if any of the existing addresses of that type have those values set to true
                    GroupService.AddNewGroupAddress(rockContext, family, locationType.Guid.ToString(), location.Id, true,
                                                    $"the {action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow",
                                                    mailing ?? groupLocations.Any(x => x.IsMailingLocation),
                                                    mapped ?? groupLocations.Any(x => x.IsMappedLocation));
                }
                else
                {
                    var    groupLocation = family.GroupLocations.FirstOrDefault(l => l.GroupLocationTypeValueId == locationType.Id);
                    string oldValue      = string.Empty;
                    if (groupLocation == null)
                    {
                        groupLocation         = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocation.GroupLocationTypeValueId = locationType.Id;
                        groupLocationService.Add(groupLocation);
                    }
                    else
                    {
                        oldValue = groupLocation.Location.ToString();
                    }

                    locationUpdated = oldValue != location.ToString();

                    groupLocation.Location = location;

                    if (mailing.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMailingLocation.ToString()) != mailing.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMailingLocation = mailing.Value;
                    }

                    if (mapped.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMappedLocation.ToString()) != mapped.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMappedLocation = mapped.Value;
                    }
                }

                if (locationUpdated)
                {
                    var groupChanges = new History.HistoryChangeList();
                    groupChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Location").SourceOfChange = $"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow";

                    foreach (var fm in family.Members)
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(Person),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof(Group),
                            family.Id,
                            false,
                            null,
                            rockContext.SourceOfChange);
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry(string.Format("Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString()));
            }

            return(true);
        }
Exemplo n.º 32
0
    private void ShowException()
    {
        pnlException.Visible = true;

        // get error level
        int errorLevel = 0;

        if ( Request["error"] != null )
        {
            errorLevel = Int32.Parse( Request["error"].ToString() );
        }
        else
        {
            if (Request.RequestContext.HttpContext.Items["error"] != null)
            {
                errorLevel = Int32.Parse( Request.RequestContext.HttpContext.Items["error"].ToString() );
            }
        }

        switch ( errorLevel )
        {
            case 1:
                // check to see if the user is an admin, if so allow them to view the error details
                var userLogin = Rock.Model.UserLoginService.GetCurrentUser();

                try
                {
                    GroupService service = new GroupService( new RockContext() );
                    Group adminGroup = service.GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_ADMINISTRATORS ) );

                    if ( userLogin != null && adminGroup.Members.Where( m => m.PersonId == userLogin.PersonId ).Count() > 0 )
                    {
                        // get exception from Session
                        if ( Session["Exception"] != null )
                        {
                            // is an admin
                            lErrorInfo.Text = "<h3>Exception Log:</h3>";

                            ProcessException( (Exception)Session["Exception"], " " );
                        }
                    }
                }
                catch { }

                break;

            case 66: // massive errors from global.asax.cs or routehandler

                if ( Session["Exception"] != null )
                {
                    lErrorInfo.Text = "<h3>Exception Log:</h3>";
                    ProcessException( (Exception)Session["Exception"], " " );
                }
                else
                {
                    if (Request.RequestContext.HttpContext.Items["Exception"] != null)
                    {
                        lErrorInfo.Text = "<h3>Exception Log:</h3>";
                        ProcessException( (Exception)Request.RequestContext.HttpContext.Items["Exception"], " " );
                    }
                }
                break;
        }

        // clear session object
        Session.Remove( "Exception" );
    }
Exemplo n.º 33
0
    /// <summary>
    /// Shows the detail.
    /// </summary>
    /// <param name="groupId">The group id.</param>
    protected void ShowDetail( int groupId )
    {
        GroupService groupService = new GroupService();
        Group group = groupService.Get( groupId );
        bool readOnly = false;

        hfGroupId.Value = groupId.ToString();
        LoadDropDowns();

        if ( group != null )
        {
            iconIsSystem.Visible = group.IsSystem;
            hfGroupId.Value = group.Id.ToString();
            tbName.Text = group.Name;
            tbDescription.Text = group.Description;
            ddlGroupType.SelectedValue = group.GroupTypeId.ToString();
            ddlParentGroup.SelectedValue = ( group.ParentGroupId ?? None.Id ).ToString();
            ddlCampus.SelectedValue = ( group.CampusId ?? None.Id ).ToString();
            cbIsSecurityRole.Checked = group.IsSecurityRole;

            readOnly = group.IsSystem;

            if ( group.IsSystem )
            {
                lActionTitle.Text = ActionTitle.View( Group.FriendlyTypeName );
                btnCancel.Text = "Close";
            }
            else
            {
                lActionTitle.Text = ActionTitle.Edit( Group.FriendlyTypeName );
                btnCancel.Text = "Cancel";
            }
        }
        else
        {
            lActionTitle.Text = ActionTitle.Add( Group.FriendlyTypeName );
            iconIsSystem.Visible = false;
            hfGroupId.Value = 0.ToString();
            tbName.Text = string.Empty;
            tbDescription.Text = string.Empty;
            ddlGroupType.SelectedValue = null;
            ddlParentGroup.SelectedValue = None.IdValue;
            ddlCampus.SelectedValue = None.IdValue;
            cbIsSecurityRole.Checked = false;
        }

        ddlGroupType.Enabled = !readOnly;
        ddlParentGroup.Enabled = !readOnly;
        ddlCampus.Enabled = !readOnly;
        cbIsSecurityRole.Enabled = !readOnly;

        tbName.ReadOnly = readOnly;
        tbDescription.ReadOnly = readOnly;
        btnSave.Visible = !readOnly;

        // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
        if ( AttributeValue( "LimittoSecurityRoleGroups" ).FromTrueFalse() )
        {
            cbIsSecurityRole.Enabled = false;
            cbIsSecurityRole.Checked = true;
        }
    }
Exemplo n.º 34
0
 public GroupsController(IUnitOfWork unitOfWork)
     : base(unitOfWork)
 {
     GroupService = new GroupService(UnitOfWork);
 }
Exemplo n.º 35
0
        private static List <BreakoutGroupItem> GetBreakoutGroupItems(Person person)
        {
            List <BreakoutGroupItem> allBreakoutGroupItems = RockCache.Get(cacheKey) as List <BreakoutGroupItem>;

            if (allBreakoutGroupItems == null || !allBreakoutGroupItems.Any())
            {
                allBreakoutGroupItems = new List <BreakoutGroupItem>();
                RockContext rockContext = new RockContext();

                var attributeService      = new AttributeService(rockContext);
                var attributeValueService = new AttributeValueService(rockContext);

                var groupEntityTypeId        = EntityTypeCache.GetId(typeof(Rock.Model.Group));
                var breakoutGroupGroupTypeId = GroupTypeCache.GetId(Constants.GROUP_TYPE_BREAKOUT_GROUPS.AsGuid());

                if (groupEntityTypeId == null || breakoutGroupGroupTypeId == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout groups due to missing breakoutgroup type"));
                    return(new List <BreakoutGroupItem>());
                }

                var letterAttribute = attributeService.GetByEntityTypeQualifier(groupEntityTypeId, "GroupTypeId", breakoutGroupGroupTypeId.Value.ToString(), false)
                                      .Where(a => a.Key == Constants.GROUP_ATTRIBUTE_KEY_LETTER)
                                      .FirstOrDefault();

                if (letterAttribute == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout group letter attribute."));
                    return(new List <BreakoutGroupItem>());
                }

                var attributeQueryable = attributeValueService.Queryable().AsNoTracking()
                                         .Where(av => letterAttribute.Id == av.AttributeId);

                //Get all the data in one go
                var breakoutData = new GroupService(rockContext)
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(g => g.GroupTypeId == breakoutGroupGroupTypeId && g.IsActive && !g.IsArchived)
                                   .Join(attributeQueryable,
                                         g => g.Id,
                                         av => av.EntityId,
                                         (g, av) => new
                {
                    ScheduleId = g.ScheduleId ?? 0,
                    PersonIds  = g.Members.Where(gm => gm.IsArchived == false && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.PersonId),
                    Letter     = av.Value
                })
                                   .ToList();

                foreach (var item in breakoutData)
                {
                    foreach (var personId in item.PersonIds)
                    {
                        allBreakoutGroupItems.Add(new BreakoutGroupItem
                        {
                            Letter     = item.Letter,
                            PersonId   = personId,
                            ScheduleId = item.ScheduleId
                        });
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroupItems, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }

            return(allBreakoutGroupItems.Where(i => i.PersonId == person.Id).ToList());
        }
Exemplo n.º 36
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var rockContext = new RockContext();

                GroupMemberService            groupMemberService            = new GroupMemberService(rockContext);
                GroupMemberRequirementService groupMemberRequirementService = new GroupMemberRequirementService(rockContext);
                GroupMember groupMember;

                int groupMemberId = int.Parse(hfGroupMemberId.Value);

                GroupTypeRole role = new GroupTypeRoleService(rockContext).Get(ddlGroupRole.SelectedValueAsInt() ?? 0);

                // check to see if the user selected a role
                if (role == null)
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                // if adding a new group member
                if (groupMemberId.Equals(0))
                {
                    groupMember = new GroupMember {
                        Id = 0
                    };
                    groupMember.GroupId = hfGroupId.ValueAsInt();
                }
                else
                {
                    // load existing group member
                    groupMember = groupMemberService.Get(groupMemberId);
                }

                groupMember.PersonId          = ppGroupMemberPerson.PersonId.Value;
                groupMember.GroupRoleId       = role.Id;
                groupMember.Note              = tbNote.Text;
                groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum <GroupMemberStatus>();

                if (cbIsNotified.Visible)
                {
                    groupMember.IsNotified = cbIsNotified.Checked;
                }

                if (pnlRequirements.Visible)
                {
                    foreach (var checkboxItem in cblManualRequirements.Items.OfType <ListItem>())
                    {
                        int  groupRequirementId     = checkboxItem.Value.AsInteger();
                        var  groupMemberRequirement = groupMember.GroupMemberRequirements.FirstOrDefault(a => a.GroupRequirementId == groupRequirementId);
                        bool metRequirement         = checkboxItem.Selected;
                        if (metRequirement)
                        {
                            if (groupMemberRequirement == null)
                            {
                                groupMemberRequirement = new GroupMemberRequirement();
                                groupMemberRequirement.GroupRequirementId = groupRequirementId;

                                groupMember.GroupMemberRequirements.Add(groupMemberRequirement);
                            }

                            // set the RequirementMetDateTime if it hasn't been set already
                            groupMemberRequirement.RequirementMetDateTime = groupMemberRequirement.RequirementMetDateTime ?? RockDateTime.Now;

                            groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                        }
                        else
                        {
                            if (groupMemberRequirement != null)
                            {
                                // doesn't meets the requirement
                                groupMemberRequirement.RequirementMetDateTime       = null;
                                groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                            }
                        }
                    }
                }

                groupMember.LoadAttributes();

                Rock.Attribute.Helper.GetEditValues(phAttributes, groupMember);

                if (!Page.IsValid)
                {
                    return;
                }

                // if the groupMember IsValue is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
                // So, make sure a message is displayed in the validation summary
                cvGroupMember.IsValid = groupMember.IsValid;

                if (!cvGroupMember.IsValid)
                {
                    cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

                // using WrapTransaction because there are three Saves
                rockContext.WrapTransaction(() =>
                {
                    if (groupMember.Id.Equals(0))
                    {
                        groupMemberService.Add(groupMember);
                    }

                    rockContext.SaveChanges();
                    groupMember.SaveAttributeValues(rockContext);
                });

                groupMember.CalculateRequirements(rockContext, true);

                Group group = new GroupService(rockContext).Get(groupMember.GroupId);
                if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                {
                    Rock.Security.Role.Flush(group.Id);
                    Rock.Security.Authorization.Flush();
                }
            }

            Dictionary <string, string> qryString = new Dictionary <string, string>();

            qryString["GroupId"] = hfGroupId.Value;
            NavigateToParentPage(qryString);
        }
Exemplo n.º 37
0
 public SubscribersController(IUnitOfWork unitOfWork)
     : base(unitOfWork)
 {
     SubscriberService = new SubscriberService(UnitOfWork);
     GroupService = new GroupService(UnitOfWork);
 }
Exemplo n.º 38
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");
        }
Exemplo n.º 39
0
        private List<string> GetRole( string role )
        {
            Dictionary<string, List<string>> applicationRoles = GetRoles();

            if ( applicationRoles == null )
            {
                applicationRoles = new Dictionary<string, List<string>>();

                GroupService GroupService = new GroupService();

                Rock.Models.Groups.Group groupModel = GroupService.GetGroupByGuid( new Guid( role ) );
                if (groupModel != null)
                {
                    List<string> usernames = new List<string>();

                    foreach ( Rock.Models.Groups.Member member in groupModel.Members)
                        foreach ( Rock.Models.Cms.User userModel in member.Person.Users)
                            usernames.Add( userModel.Username );

                    applicationRoles.Add( groupModel.Name, usernames );
                }
            }

            if ( applicationRoles.ContainsKey( role ) )
                return applicationRoles[role];
            else
                return null;
        }
Exemplo n.º 40
0
        /// <summary>
        /// Handles the SaveClick event of the mdLinkConversation 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 mdLinkConversation_SaveClick(object sender, EventArgs e)
        {
            // Do some validation on entering a new person/family first
            if (hfActiveTab.Value != "Existing")
            {
                var  validationMessages = new List <string>();
                bool isValid            = true;

                DateTime?birthdate = dpNewPersonBirthDate.SelectedDate;
                if (!dpNewPersonBirthDate.IsValid)
                {
                    validationMessages.Add("Birthdate is not valid.");
                    isValid = false;
                }

                if (!isValid)
                {
                    if (validationMessages.Any())
                    {
                        nbAddPerson.Text    = "<ul><li>" + validationMessages.AsDelimited("</li><li>") + "</li></lu>";
                        nbAddPerson.Visible = true;
                    }

                    return;
                }
            }

            using (var rockContext = new RockContext())
            {
                int mobilePhoneTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                if (hfActiveTab.Value == "Existing")
                {
                    if (ppPerson.PersonId.HasValue)
                    {
                        // All we need to do here is add the mobile phone number and save
                        var  personService = new PersonService(rockContext);
                        var  person        = personService.Get(ppPerson.PersonId.Value);
                        bool hasSmsNumber  = person.PhoneNumbers.Where(p => p.IsMessagingEnabled).Any();
                        var  phoneNumber   = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == mobilePhoneTypeId);

                        if (phoneNumber == null)
                        {
                            phoneNumber = new PhoneNumber
                            {
                                NumberTypeValueId  = mobilePhoneTypeId,
                                IsMessagingEnabled = !hasSmsNumber,
                                Number             = hfSelectedMessageKey.Value
                            };

                            person.PhoneNumbers.Add(phoneNumber);
                        }
                        else
                        {
                            phoneNumber.Number = hfSelectedMessageKey.Value;
                            if (!hasSmsNumber)
                            {
                                // If they don't have a number then use this one, otherwise don't do anything
                                phoneNumber.IsMessagingEnabled = true;
                            }
                        }

                        rockContext.SaveChanges();
                        hfSelectedRecipientId.Value = person.PrimaryAliasId.ToString();
                    }
                }
                else
                {
                    // new Person and new family
                    var person = new Person();

                    person.TitleValueId         = dvpNewPersonTitle.SelectedValueAsId();
                    person.FirstName            = tbNewPersonFirstName.Text;
                    person.NickName             = tbNewPersonFirstName.Text;
                    person.LastName             = tbNewPersonLastName.Text;
                    person.SuffixValueId        = dvpNewPersonSuffix.SelectedValueAsId();
                    person.Gender               = rblNewPersonGender.SelectedValueAsEnum <Gender>();
                    person.MaritalStatusValueId = dvpNewPersonMaritalStatus.SelectedValueAsInt();

                    person.PhoneNumbers = new List <PhoneNumber>();
                    var phoneNumber = new PhoneNumber
                    {
                        NumberTypeValueId  = mobilePhoneTypeId,
                        IsMessagingEnabled = true,
                        Number             = hfSelectedMessageKey.Value
                    };

                    person.PhoneNumbers.Add(phoneNumber);

                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;

                    var birthday = dpNewPersonBirthDate.SelectedDate;
                    if (birthday.HasValue)
                    {
                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    person.GradeOffset             = ddlGradePicker.SelectedValueAsInt();
                    person.ConnectionStatusValueId = dvpNewPersonConnectionStatus.SelectedValueAsId();

                    var groupMember = new GroupMember();
                    groupMember.GroupRoleId = rblNewPersonRole.SelectedValueAsInt() ?? 0;
                    groupMember.Person      = person;

                    var groupMembers = new List <GroupMember>();
                    groupMembers.Add(groupMember);

                    Group group = GroupService.SaveNewFamily(rockContext, groupMembers, null, true);
                    hfSelectedRecipientId.Value = person.PrimaryAliasId.ToString();
                }

                new CommunicationResponseService(rockContext).UpdatePersonAliasByMessageKey(hfSelectedRecipientId.ValueAsInt(), hfSelectedMessageKey.Value, PersonAliasType.FromPersonAlias);
            }

            ppPerson.Required                     = false;
            tbNewPersonFirstName.Required         = false;
            tbNewPersonLastName.Required          = false;
            rblNewPersonRole.Required             = false;
            rblNewPersonGender.Required           = false;
            dvpNewPersonConnectionStatus.Required = false;

            hfActiveTab.Value = string.Empty;

            mdLinkConversation.Hide();
            HideDialog();
            LoadResponseListing();
        }
Exemplo n.º 41
0
        public ActionResult GroupView(int id)
        {
            GroupService service = new GroupService();
            var group = service.GetById(id);

            GMRService<Module> moduleSvc = new GMRService<Module>();

            ViewGroupPermissionModel model = new ViewGroupPermissionModel()
            {

                GroupId = id,
                Name = group.GroupName,
                Modules = moduleSvc.GetPaged(p => p.Keys != "SA", new IOrderByClause<Module>[] { new OrderByClause<Module, string>(p => p.Name, SortDirection.Ascending) }, 1, int.MaxValue)

            };

            return View(model);
        }
Exemplo n.º 42
0
        public void Remove(string gid)
        {
            GroupService.Remove(gid.ToLong(0));

            Response.Redirect("/Group/");
        }
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFirstName.Text) ||
                string.IsNullOrWhiteSpace(txtLastName.Text) ||
                string.IsNullOrWhiteSpace(txtEmail.Text))
            {
                ShowError("Missing Information", "Please enter a value for First Name, Last Name, and Email");
            }
            else
            {
                var rockContext = new RockContext();
                var person      = GetPerson(rockContext);
                if (person != null)
                {
                    Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        var groupService       = new GroupService(rockContext);
                        var groupMemberService = new GroupMemberService(rockContext);

                        var group = groupService.Get(groupGuid.Value);
                        if (group != null && group.GroupType.DefaultGroupRoleId.HasValue)
                        {
                            string linkedPage = GetAttributeValue("ConfirmationPage");
                            if (!string.IsNullOrWhiteSpace(linkedPage))
                            {
                                var member = group.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                // If person has not registered or confirmed their registration
                                if (member == null || member.GroupMemberStatus != GroupMemberStatus.Active)
                                {
                                    Guid confirmationEmailTemplateGuid = Guid.Empty;
                                    if (!Guid.TryParse(GetAttributeValue("ConfirmationEmail"), out confirmationEmailTemplateGuid))
                                    {
                                        confirmationEmailTemplateGuid = Guid.Empty;
                                    }

                                    if (member == null)
                                    {
                                        member             = new GroupMember();
                                        member.GroupId     = group.Id;
                                        member.PersonId    = person.Id;
                                        member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                        // If a confirmation email is configured, set status to Pending otherwise set it to active
                                        member.GroupMemberStatus = confirmationEmailTemplateGuid != Guid.Empty ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                        groupMemberService.Add(member);
                                        rockContext.SaveChanges();

                                        member = groupMemberService.Get(member.Id);
                                    }

                                    // Send the confirmation
                                    if (confirmationEmailTemplateGuid != Guid.Empty)
                                    {
                                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                                        mergeFields.Add("Member", member);

                                        var pageParams = new Dictionary <string, string>();
                                        pageParams.Add("GM", member.UrlEncodedKey);
                                        var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                        mergeFields.Add("ConfirmationPage", pageReference.BuildUrl());

                                        var emailMessage = new RockEmailMessage(confirmationEmailTemplateGuid);
                                        emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                                        emailMessage.AppRoot   = ResolveRockUrl("~/");
                                        emailMessage.ThemeRoot = ResolveRockUrl("~~/");
                                        emailMessage.Send();
                                    }

                                    ShowSuccess(GetAttributeValue("SuccessMessage"));
                                }
                                else
                                {
                                    var pageParams = new Dictionary <string, string>();
                                    pageParams.Add("GM", member.UrlEncodedKey);
                                    var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                    Response.Redirect(pageReference.BuildUrl(), false);
                                }
                            }
                            else
                            {
                                ShowError("Configuration Error", "Invalid Confirmation Page setting");
                            }
                        }
                        else
                        {
                            ShowError("Configuration Error", "The configured group does not exist, or its group type does not have a default role configured.");
                        }
                    }
                    else
                    {
                        ShowError("Configuration Error", "Invalid Group setting");
                    }
                }
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Handles the Click event of the btnMoveGroupMember 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 btnMoveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var groupMember        = groupMemberService.Get(hfGroupMemberId.Value.AsInteger());

            groupMember.LoadAttributes();
            int destGroupId = gpMoveGroupMember.SelectedValue.AsInteger();
            var destGroup   = new GroupService(rockContext).Get(destGroupId);

            var destGroupMember = groupMemberService.Queryable().Where(a =>
                                                                       a.GroupId == destGroupId &&
                                                                       a.PersonId == groupMember.PersonId &&
                                                                       a.GroupRoleId == grpMoveGroupMember.GroupRoleId).FirstOrDefault();

            if (destGroupMember != null)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("{0} is already in {1}", groupMember.Person, destGroupMember.Group);
                return;
            }

            if (!grpMoveGroupMember.GroupRoleId.HasValue)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Please select a Group Role");
                return;
            }

            string canDeleteWarning;

            if (!groupMemberService.CanDelete(groupMember, out canDeleteWarning))
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Unable to remove {0} from {1}: {2}", groupMember.Person, groupMember.Group, canDeleteWarning);
                return;
            }

            destGroupMember             = new GroupMember();
            destGroupMember.GroupId     = destGroupId;
            destGroupMember.GroupRoleId = grpMoveGroupMember.GroupRoleId.Value;
            destGroupMember.PersonId    = groupMember.PersonId;
            destGroupMember.LoadAttributes();

            foreach (var attribute in groupMember.Attributes)
            {
                if (destGroupMember.Attributes.Any(a => a.Key == attribute.Key && a.Value.FieldTypeId == attribute.Value.FieldTypeId))
                {
                    destGroupMember.SetAttributeValue(attribute.Key, groupMember.GetAttributeValue(attribute.Key));
                }
            }

            // Un-link any registrant records that point to this group member.
            foreach (var registrant in new RegistrationRegistrantService(rockContext).Queryable()
                     .Where(r => r.GroupMemberId == groupMember.Id))
            {
                registrant.GroupMemberId = null;
            }

            rockContext.WrapTransaction(() =>
            {
                groupMemberService.Add(destGroupMember);
                rockContext.SaveChanges();
                destGroupMember.SaveAttributeValues(rockContext);

                // move any Note records that were associated with the old groupMember to the new groupMember record
                if (cbMoveGroupMemberMoveNotes.Checked)
                {
                    destGroupMember.Note        = groupMember.Note;
                    int groupMemberEntityTypeId = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
                    var noteService             = new NoteService(rockContext);
                    var groupMemberNotes        = noteService.Queryable().Where(a => a.NoteType.EntityTypeId == groupMemberEntityTypeId && a.EntityId == groupMember.Id);
                    foreach (var note in groupMemberNotes)
                    {
                        note.EntityId = destGroupMember.Id;
                    }

                    rockContext.SaveChanges();
                }

                groupMemberService.Delete(groupMember);
                rockContext.SaveChanges();

                destGroupMember.CalculateRequirements(rockContext, true);
            });

            var queryString = new Dictionary <string, string>();

            queryString.Add("GroupMemberId", destGroupMember.Id.ToString());
            this.NavigateToPage(this.RockPage.Guid, queryString);
        }