Exemplo n.º 1
0
        /// <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 )
            {
                string groupId = PageParameter( "GroupId" );
                string groupMemberId = PageParameter( "GroupMemberId" );
                if ( !string.IsNullOrWhiteSpace( groupMemberId ) )
                {
                    if ( string.IsNullOrWhiteSpace( groupId ) )
                    {
                        ShowDetail( "GroupMemberId", int.Parse( groupMemberId ) );
                    }
                    else
                    {
                        ShowDetail( "GroupMemberId", int.Parse( groupMemberId ), int.Parse( groupId ) );
                    }
                }
                else
                {
                    upDetail.Visible = false;
                }
            }
            else
            {
                var groupMember = new GroupMember { GroupId = hfGroupId.ValueAsInt() };
                if ( groupMember != null )
                {
                    groupMember.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( groupMember, phAttributes, false );
                }
            }
        }
        /// <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)
            {
                string groupId       = PageParameter("groupId");
                string groupMemberId = PageParameter("groupMemberId");
                if (!string.IsNullOrWhiteSpace(groupMemberId))
                {
                    if (string.IsNullOrWhiteSpace(groupId))
                    {
                        ShowDetail("groupMemberId", int.Parse(groupMemberId));
                    }
                    else
                    {
                        ShowDetail("groupMemberId", int.Parse(groupMemberId), int.Parse(groupId));
                    }
                }
                else
                {
                    pnlDetails.Visible = false;
                }
            }

            var groupMember = new GroupMember {
                GroupId = hfGroupId.ValueAsInt()
            };

            groupMember.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, false);
        }
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            CommunicationMembershipIds = (List <int>)ViewState["CommunicationMembershipIds"];
            CommunicationGroupIds      = (List <int>)ViewState["CommunicationGroupIds"];

            RockContext        rockContext        = new RockContext();
            GroupService       groupService       = new GroupService(rockContext);
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            var tempCommunicationGroups = groupService.Queryable().Where(g => CommunicationGroupIds.Contains(g.Id)).ToList();

            CommunicationGroups = new List <Group>();
            foreach (var id in CommunicationGroupIds)
            {
                CommunicationGroups.AddRange(tempCommunicationGroups.Where(g => g.Id == id));
            }

            CommunicationMembership = groupMemberService.Queryable().Where(m => CommunicationMembershipIds.Contains(m.Id)).ToList();

            if (ViewState["KeywordGroupId"] != null && ViewState["KeywordGroupId"] is int)
            {
                var groupMember = new GroupMember {
                    GroupId = ( int )ViewState["KeywordGroupId"]
                };
                groupMember.LoadAttributes();
                groupMember.Attributes = groupMember.Attributes.Where(a => a.Value.IsGridColumn).ToDictionary(a => a.Key, a => a.Value);
                Rock.Attribute.Helper.AddEditControls(groupMember, phGroupAttributes, false);
            }

            BindGroups(false);
        }
Exemplo n.º 4
0
        private GroupMembershipStatus GroupMembershipExpired(GroupMember groupMember)
        {
            if (groupMember.Person.ConnectionStatusValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid())
            {
                return(GroupMembershipStatus.Member);
            }

            var person = groupMember.Person;

            person.LoadAttributes();
            if (person.GetAttributeValue("Employer") == "Southeast Christian Church")
            {
                return(GroupMembershipStatus.Member);
            }

            groupMember.LoadAttributes();
            var expirationDate = groupMember.GetAttributeValue(_expirationDateKey).AsDateTime() ?? Rock.RockDateTime.Today.AddDays(-1);

            if (expirationDate < Rock.RockDateTime.Today)
            {
                return(GroupMembershipStatus.Expired);
            }
            else if (expirationDate < Rock.RockDateTime.Today.AddDays(30))
            {
                return(GroupMembershipStatus.NearExpired);
            }
            else
            {
                return(GroupMembershipStatus.NotExpired);
            }
        }
        /// <summary>
        /// Creates the dynamic controls.
        /// </summary>
        /// <param name="groupMember">The group member.</param>
        private void CreateDynamicControls(GroupMember groupMember)
        {
            groupMember.LoadAttributes();
            // GroupMember Attributes (all of them)
            phGroupMemberAttributes.Controls.Clear();

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

            if (!groupMember.Group.GetAttributeValue("AllowIndividualDisablingofContributionRequests").AsBoolean())
            {
                excludes.Add("DisablePublicContributionRequests");
            }

            if (!groupMember.Group.GetAttributeValue("AllowIndividualEditingofFundraisingGoal").AsBoolean())
            {
                excludes.Add("IndividualFundraisingGoal");
            }

            Rock.Attribute.Helper.AddEditControls(groupMember, phGroupMemberAttributes, true, "vgProfileEdit", excludes, true);

            // Person Attributes (the ones they picked in the Block Settings)
            phPersonAttributes.Controls.Clear();

            var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Read(a));

            if (personAttributes.Any())
            {
                var person = groupMember.Person;
                person.LoadAttributes();
                foreach (var personAttribute in personAttributes.OrderBy(a => a.Order))
                {
                    personAttribute.AddControl(phPersonAttributes.Controls, person.GetAttributeValue(personAttribute.Key), "vgProfileEdit", true, true);
                }
            }
        }
Exemplo n.º 6
0
        private void AddGroupMemberAttributes(RockContext rockContext = null)
        {
            // Group
            if (RoleRequests.Count > 0 && rptGroupRoleAttributes.Items.Count > 0)
            {
                if (rockContext == null)
                {
                    rockContext = new RockContext();
                }
                var viewStateAttributes = new List <Dictionary <string, string> >();
                var RepeaterIndex       = 0;
                foreach (var roleRequest in RoleRequests)
                {
                    var hdnGroupId   = (( HiddenField )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("hdnGroupId")));
                    var phAttributes = (( PlaceHolder )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("phAttributes")));
                    hdnGroupId.Value = roleRequest.GroupId.ToString();

                    var group = new GroupService(rockContext).Get(hdnGroupId.Value.AsInteger());
                    if (group != null)
                    {
                        // Group Attributes
                        var formKeys = GetAttributeValues("FormKeys");
                        var urlKeys  = GetAttributeValues("UrlKeys");

                        AttributeService attributeService = new AttributeService(rockContext);

                        string groupQualifierValue     = group.Id.ToString();
                        string groupTypeQualifierValue = group.GroupTypeId.ToString();

                        // Make a fake group member so we can load some attributes.
                        GroupMember groupMember = new GroupMember();
                        groupMember.Group   = group;
                        groupMember.GroupId = group.Id;
                        groupMember.LoadAttributes();

                        // Store URL Keys into the ViewState
                        var viewStateAttribute = new Dictionary <string, string>();
                        foreach (string urlKey in urlKeys)
                        {
                            if (roleRequest.Attributes != null && roleRequest.Attributes.ContainsKey(urlKey) && !string.IsNullOrEmpty(roleRequest.Attributes[urlKey]) && groupMember.Attributes.ContainsKey(urlKey))
                            {
                                groupMember.SetAttributeValue(urlKey, roleRequest.Attributes[urlKey]);
                                viewStateAttribute.Add(urlKey, roleRequest.Attributes[urlKey]);
                            }
                        }
                        viewStateAttributes.Add(viewStateAttribute);

                        Helper.AddDisplayControls(groupMember, phAttributes, groupMember.Attributes.Where(a => !urlKeys.Contains(a.Key)).Select(a => a.Key).ToList(), true, false);
                        Helper.AddEditControls("", formKeys, groupMember, phAttributes, tbLastName.ValidationGroup, false, new List <String>());
                    }
                    RepeaterIndex++;
                }
                ViewState.Add("SelectedAttributes", viewStateAttributes);
                SaveViewState();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GroupMemberPlacedElsewhereTransaction" /> class.
 /// </summary>
 /// <param name="groupMember">The group member of the current group they are in (before being deleted and processed) </param>
 /// <param name="note">The note.</param>
 /// <param name="trigger">The GroupMemberWorkflowTrigger.</param>
 public GroupMemberPlacedElsewhereTransaction( GroupMember groupMember, string note, GroupMemberWorkflowTrigger trigger )
 {
     this.Trigger = trigger;
     this.GroupId = groupMember.GroupId;
     this.PersonId = groupMember.PersonId;
     this.GroupMemberStatusName = groupMember.GroupMemberStatus.ConvertToString();
     this.GroupMemberRoleName = groupMember.GroupRole.ToString();
     groupMember.LoadAttributes();
     this.GroupMemberAttributeValues = groupMember.AttributeValues.ToDictionary( k => k.Key, v => v.Value.Value );
     this.Note = note;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GroupMemberPlacedElsewhereTransaction" /> class.
 /// </summary>
 /// <param name="groupMember">The group member of the current group they are in (before being deleted and processed) </param>
 /// <param name="note">The note.</param>
 /// <param name="trigger">The GroupMemberWorkflowTrigger.</param>
 public GroupMemberPlacedElsewhereTransaction(GroupMember groupMember, string note, GroupMemberWorkflowTrigger trigger)
 {
     this.Trigger  = trigger;
     this.GroupId  = groupMember.GroupId;
     this.PersonId = groupMember.PersonId;
     this.GroupMemberStatusName = groupMember.GroupMemberStatus.ConvertToString();
     this.GroupMemberRoleName   = groupMember.GroupRole.ToString();
     groupMember.LoadAttributes();
     this.GroupMemberAttributeValues = groupMember.AttributeValues.ToDictionary(k => k.Key, v => v.Value.Value);
     this.Note = note;
 }
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (ViewState["GroupId"] != null && ViewState["GroupId"] is int)
            {
                var groupMember = new GroupMember {
                    GroupId = ( int )ViewState["GroupId"]
                };
                groupMember.LoadAttributes();
                BindFilter(groupMember);
            }
        }
        protected void gList_RowSelected(object sender, RowEventArgs e)
        {
            var groupId     = e.RowKeyId;
            var groupMember = new GroupMember {
                GroupId = groupId
            };

            groupMember.LoadAttributes();

            pnlFilter.Visible    = true;
            pnlGrid.Visible      = false;
            ViewState["GroupId"] = groupId;

            BindFilter(groupMember);
        }
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="groupMember">The group member.</param>
        private void ShowReadonlyDetails(GroupMember groupMember)
        {
            SetEditMode(false);

            ClearErrorMessage();

            string groupIconHtml = string.Empty;
            var    group         = groupMember.Group;

            if (!string.IsNullOrWhiteSpace(group.GroupType.IconCssClass))
            {
                groupIconHtml = string.Format("<i class='{0} icon-large' ></i>", group.GroupType.IconCssClass);
            }
            else
            {
                var    appPath        = System.Web.VirtualPathUtility.ToAbsolute("~");
                string imageUrlFormat = "<img src='" + appPath + "GetImage.ashx?id={0}&width=50&height=50' />";
                if (group.GroupType.IconLargeFileId != null)
                {
                    groupIconHtml = string.Format(imageUrlFormat, group.GroupType.IconLargeFileId);
                }
                else if (group.GroupType.IconSmallFileId != null)
                {
                    groupIconHtml = string.Format(imageUrlFormat, group.GroupType.IconSmallFileId);
                }
            }

            hfGroupId.SetValue(group.Id);
            hfGroupMemberId.SetValue(groupMember.Id);

            lGroupIconHtml.Text = groupIconHtml;
            lReadOnlyTitle.Text = groupMember.Person.FullName;

            lblMainDetails.Text = new DescriptionList()
                                  .Add("Group Member", groupMember.Person)
                                  .Add("Member's Role", groupMember.GroupRole.Name)
                                  .Add("Member's Status", groupMember.GroupMemberStatus.ConvertToString())
                                  .Add("Group Name", group.Name)
                                  .Add("Group Description", group.Description)

                                  .Html;

            groupMember.LoadAttributes();
            Rock.Attribute.Helper.AddDisplayControls(groupMember, phGroupMemberAttributesReadOnly);
        }
Exemplo n.º 12
0
        protected void btnSelect_Click(object sender, EventArgs e)
        {
            var groupId = ( int )ViewState["GroupId"];

            //Make a fake group member so we can get the attributes to filter by
            var groupMember = new GroupMember {
                GroupId = groupId
            };

            groupMember.LoadAttributes();

            var attributes = groupMember.Attributes.Select(a => a.Value).Where(a => a.IsGridColumn).ToList();

            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            var qry = groupMemberService.Queryable()
                      .Where(gm => gm.GroupId == groupId);

            foreach (var attribute in attributes)
            {
                var filterControl = phFilter.FindControl("filter_" + attribute.Id.ToString());
                qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, groupMemberService, Rock.Reporting.FilterMode.SimpleFilter);
            }

            if (dvDataView.SelectedValueAsId().HasValue)
            {
                var dataviewId = dvDataView.SelectedValueAsId().Value;

                DataViewService dataViewService = new DataViewService(rockContext);
                var             dataView        = dataViewService.Get(dataviewId);

                if (dataView != null && dataView.IsAuthorized(Authorization.VIEW, CurrentPerson))
                {
                    var dvQuery = dataView.GetQuery(new DataViewGetQueryArgs {
                        DbContext = rockContext, DatabaseTimeoutSeconds = 60
                    });
                    qry = qry.Where(m => dvQuery.Select(p => p.Id).Contains(m.PersonId));
                }
            }

            BuildCommunication(qry.ToList());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates the dynamic controls.
        /// </summary>
        /// <param name="groupMember">The group member.</param>
        private void CreateDynamicControls(GroupMember groupMember)
        {
            groupMember.LoadAttributes();
            groupMember.Group.LoadAttributes();
            // GroupMember Attributes (all of them)
            phGroupMemberAttributes.Controls.Clear();

            // Exclude any attributes for which the current person has NO EDIT access.
            // But skip these three special member attributes since they are handled in a special way.
            List <string> excludes = groupMember.Attributes.Where(
                a => !a.Value.IsAuthorized(Rock.Security.Authorization.EDIT, this.CurrentPerson) &&
                a.Key != "IndividualFundraisingGoal" &&
                a.Key != "DisablePublicContributionRequests" &&
                a.Key != "PersonalOpportunityIntroduction")
                                     .Select(a => a.Key).ToList();

            if (!groupMember.Group.GetAttributeValue("AllowIndividualDisablingofContributionRequests").AsBoolean())
            {
                excludes.Add("DisablePublicContributionRequests");
            }

            if (!groupMember.Group.GetAttributeValue("AllowIndividualEditingofFundraisingGoal").AsBoolean())
            {
                excludes.Add("IndividualFundraisingGoal");
            }

            Rock.Attribute.Helper.AddEditControls(groupMember, phGroupMemberAttributes, true, "vgProfileEdit", excludes, true);

            // Person Attributes (the ones they picked in the Block Settings)
            phPersonAttributes.Controls.Clear();

            var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Get(a));

            if (personAttributes.Any())
            {
                var person = groupMember.Person;
                person.LoadAttributes();
                foreach (var personAttribute in personAttributes.OrderBy(a => a.Order))
                {
                    personAttribute.AddControl(phPersonAttributes.Controls, person.GetAttributeValue(personAttribute.Key), "vgProfileEdit", true, true);
                }
            }
        }
Exemplo n.º 14
0
        private Dictionary <string, AttributeValueCache> GetGroupMemberAttributes(RockContext rockContext = null, int RepeaterIndex = 0)
        {
            // Group
            if (RoleRequests.Count > 0)
            {
                if (rockContext == null)
                {
                    rockContext = new RockContext();
                }

                var hdnGroupId   = (( HiddenField )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("hdnGroupId")));
                var phAttributes = (( PlaceHolder )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("phAttributes")));
                hdnGroupId.Value = RoleRequests[RepeaterIndex].GroupId.ToString();

                var group = new GroupService(rockContext).Get(hdnGroupId.Value.AsInteger());
                if (group != null)
                {
                    // Make a fake group member so we can load some attributes.
                    GroupMember groupMember = new GroupMember();
                    groupMember.Group   = group;
                    groupMember.GroupId = group.Id;
                    groupMember.LoadAttributes();

                    Helper.GetEditValues(phAttributes, groupMember);

                    var readonlyAttributes = (List <Dictionary <string, string> >)ViewState["SelectedAttributes"];
                    if (readonlyAttributes != null && readonlyAttributes.Count > RepeaterIndex && readonlyAttributes[RepeaterIndex].Keys.Count > 0)
                    {
                        foreach (var kvp in readonlyAttributes[RepeaterIndex])
                        {
                            if (groupMember.AttributeValues.ContainsKey(kvp.Key))
                            {
                                groupMember.AttributeValues[kvp.Key].Value = kvp.Value;
                            }
                        }
                    }
                    return(groupMember.AttributeValues);
                }
            }
            return(null);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Handles the SelectItem event of the gpMoveGroupMember 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 gpMoveGroupMember_SelectItem(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            var destGroup   = new GroupService(rockContext).Get(gpMoveGroupMember.SelectedValue.AsInteger());

            if (destGroup != null)
            {
                var destTempGroupMember = new GroupMember {
                    Group = destGroup, GroupId = destGroup.Id
                };
                destTempGroupMember.LoadAttributes(rockContext);
                var destGroupMemberAttributes = destTempGroupMember.Attributes;
                var groupMember = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger());
                groupMember.LoadAttributes();
                var currentGroupMemberAttributes = groupMember.Attributes;

                var lostAttributes = currentGroupMemberAttributes.Where(a => !destGroupMemberAttributes.Any(d => d.Key == a.Key && d.Value.FieldTypeId == a.Value.FieldTypeId));
                nbMoveGroupMemberWarning.Visible = lostAttributes.Any();
                nbMoveGroupMemberWarning.Text    = "The destination group does not have the same group member attributes as the source. Some loss of data may occur";

                if (destGroup.Id == groupMember.GroupId)
                {
                    grpMoveGroupMember.Visible       = false;
                    nbMoveGroupMemberWarning.Visible = true;
                    nbMoveGroupMemberWarning.Text    = "The destination group is the same as the current group";
                }
                else
                {
                    grpMoveGroupMember.Visible     = true;
                    grpMoveGroupMember.GroupTypeId = destGroup.GroupTypeId;
                    grpMoveGroupMember.GroupRoleId = destGroup.GroupType.DefaultGroupRoleId;
                }
            }
            else
            {
                nbMoveGroupMemberWarning.Visible = false;
                grpMoveGroupMember.Visible       = false;
            }
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="groupMember">The group member.</param>
        private void ShowEditDetails(GroupMember groupMember)
        {
            if (groupMember.Id.Equals(0))
            {
                lActionTitle.Text = ActionTitle.Add("Group Member to " + groupMember.Group.Name);
            }
            else
            {
                lActionTitle.Text = ActionTitle.Edit("Group Member for " + groupMember.Group.Name);
            }

            SetEditMode(true);

            LoadDropDowns();

            ppGroupMemberPerson.SetValue(groupMember.Person);
            ddlGroupRole.SetValue(groupMember.GroupRoleId);
            ddlGroupMemberStatus.SetValue((int)groupMember.GroupMemberStatus);

            phAttributes.Controls.Clear();
            groupMember.LoadAttributes();
            Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, true);
        }
        /// <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);

            ClearErrorMessage();

            if (!Page.IsPostBack)
            {
                ShowDetail(PageParameter("GroupMemberId").AsInteger(), PageParameter("GroupId").AsIntegerOrNull());
            }
            else
            {
                var groupMember = new GroupMember {
                    GroupId = hfGroupId.ValueAsInt()
                };
                if (groupMember != null)
                {
                    groupMember.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, false);
                }
            }
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
        private void BuildGroupControls( bool setValues )
        {
            ddlGroupRole.Items.Clear();
            ddlGroupMemberStatus.Items.Clear();
            phAttributes.Controls.Clear();

            if ( bddlGroupAction.SelectedValue == "Remove" )
            {
                ddlGroupMemberStatus.Visible = false;
                ddlGroupRole.Visible = false;
            }
            else
            {
                ddlGroupRole.Visible = true;
                ddlGroupMemberStatus.Visible = true;

                var rockContext = new RockContext();
                Group group = null;

                int? groupId = gpGroup.SelectedValueAsId();
                if ( groupId.HasValue )
                {
                    group = new GroupService( rockContext ).Get( groupId.Value );
                }

                if ( group != null )
                {
                    var groupType = GroupTypeCache.Read( group.GroupTypeId );
                    ddlGroupRole.DataSource = groupType.Roles.OrderBy( r => r.Order ).ToList();
                    ddlGroupRole.DataBind();

                    ddlGroupMemberStatus.Items.Add( new ListItem( "Active", "1" ) );
                    ddlGroupMemberStatus.Items.Add( new ListItem( "Pending", "2" ) );
                    ddlGroupMemberStatus.Items.Add( new ListItem( "Inactive", "0" ) );

                    var groupMember = new GroupMember();
                    groupMember.Group = group;
                    groupMember.GroupId = group.Id;
                    groupMember.LoadAttributes( rockContext );
                    Rock.Attribute.Helper.AddEditControls( groupMember, phAttributes, setValues, "", true );
                }
                else
                {
                    ddlGroupRole.Items.Add( new ListItem( string.Empty, string.Empty ) );
                    ddlGroupMemberStatus.Items.Add( new ListItem( string.Empty, string.Empty ) );
                }
            }
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="item">The item.</param>
        protected void SaveChanges(RepeaterItem item)
        {
            var hfGroupId = item.FindControl("hfGroupId") as HiddenField;
            var cbCommunicationListIsSubscribed = item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox;
            var tglCommunicationPreference      = item.FindControl("tglCommunicationPreference") as Toggle;
            var nbGroupNotification             = item.FindControl("nbGroupNotification") as NotificationBox;

            nbGroupNotification.Visible = false;

            using (var rockContext = new RockContext())
            {
                int groupId            = hfGroupId.Value.AsInteger();
                var groupMemberService = new GroupMemberService(rockContext);
                var group = new GroupService(rockContext).Get(groupId);
                var groupMemberRecordsForPerson = groupMemberService.Queryable().Where(a => a.GroupId == groupId && a.PersonId == this.CurrentPersonId).ToList();
                if (groupMemberRecordsForPerson.Any())
                {
                    // normally there would be at most 1 group member record for the person, but just in case, mark them all
                    foreach (var groupMember in groupMemberRecordsForPerson)
                    {
                        if (cbCommunicationListIsSubscribed.Checked)
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Inactive)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                if (groupMember.Note == "Unsubscribed")
                                {
                                    groupMember.Note = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                                if (groupMember.Note.IsNullOrWhiteSpace())
                                {
                                    groupMember.Note = "Unsubscribed";
                                }
                            }
                        }

                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());
                        groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                    }
                }
                else
                {
                    // they are not currently in the Group
                    if (cbCommunicationListIsSubscribed.Checked)
                    {
                        var groupMember = new GroupMember();
                        groupMember.PersonId = this.CurrentPersonId.Value;
                        groupMember.GroupId  = group.Id;
                        int?defaultGroupRoleId = GroupTypeCache.Get(group.GroupTypeId).DefaultGroupRoleId;
                        if (defaultGroupRoleId.HasValue)
                        {
                            groupMember.GroupRoleId = defaultGroupRoleId.Value;
                        }
                        else
                        {
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = "Group has no default group role";
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }

                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());

                        if (groupMember.IsValidGroupMember(rockContext))
                        {
                            groupMemberService.Add(groupMember);
                            rockContext.SaveChanges();
                            groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                        }
                        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
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }
                    }
                }

                rockContext.SaveChanges();
            }
        }
        /// <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 );

            ClearErrorMessage();

            if ( !Page.IsPostBack )
            {
                ShowDetail( PageParameter( "GroupMemberId" ).AsInteger(), PageParameter( "GroupId" ).AsIntegerOrNull() );
            }
            else
            {
                var groupMember = new GroupMember { GroupId = hfGroupId.ValueAsInt() };
                if ( groupMember != null )
                {
                    groupMember.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( groupMember, phAttributes, false );
                }
            }
        }
        /// <summary>
        /// Shows the form field edit.
        /// </summary>
        /// <param name="formGuid">The form unique identifier.</param>
        /// <param name="formFieldGuid">The form field unique identifier.</param>
        private void ShowFormFieldEdit( Guid formGuid, Guid formFieldGuid )
        {
            if ( FormFieldsState.ContainsKey( formGuid ) )
            {
                ShowDialog( "Attributes" );

                var fieldList = FormFieldsState[formGuid];

                RegistrationTemplateFormField formField = fieldList.FirstOrDefault( a => a.Guid.Equals( formFieldGuid ) );
                if ( formField == null )
                {
                    formField = new RegistrationTemplateFormField();
                    formField.Guid = formFieldGuid;
                    formField.FieldSource = RegistrationFieldSource.PersonAttribute;
                }

                ceAttributePreText.Text = formField.PreText;
                ceAttributePostText.Text = formField.PostText;
                ddlFieldSource.SetValue( formField.FieldSource.ConvertToInt() );
                ddlPersonField.SetValue( formField.PersonFieldType.ConvertToInt() );
                lPersonField.Text = formField.PersonFieldType.ConvertToString();

                ddlPersonAttributes.Items.Clear();
                var person = new Person();
                person.LoadAttributes();
                foreach ( var attr in person.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlPersonAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                ddlGroupTypeAttributes.Items.Clear();
                var group = new Group();
                group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
                var groupMember = new GroupMember();
                groupMember.Group = group;
                groupMember.LoadAttributes();
                foreach ( var attr in groupMember.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlGroupTypeAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                var attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;

                if ( formField.FieldSource == RegistrationFieldSource.PersonAttribute )
                {
                    ddlPersonAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.GroupMemberAttribute )
                {
                    ddlGroupTypeAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.RegistrationAttribute )
                {
                    if ( formField.Attribute != null )
                    {
                        attribute = formField.Attribute;
                    }
                }

                edtRegistrationAttribute.SetAttributeProperties( attribute, typeof( RegistrationTemplate ) );

                cbInternalField.Checked = formField.IsInternal;
                cbShowOnGrid.Checked = formField.IsGridField;
                cbRequireInInitialEntry.Checked = formField.IsRequired;
                cbUsePersonCurrentValue.Checked = formField.ShowCurrentValue;
                cbCommonValue.Checked = formField.IsSharedValue;

                hfFormGuid.Value = formGuid.ToString();
                hfAttributeGuid.Value = formFieldGuid.ToString();

                lPersonField.Visible = formField.FieldSource == RegistrationFieldSource.PersonField && (
                    formField.PersonFieldType == RegistrationPersonFieldType.FirstName ||
                    formField.PersonFieldType == RegistrationPersonFieldType.LastName );

                SetFieldDisplay();
            }

            BuildControls( true );
        }
Exemplo n.º 23
0
        protected void btnMoveRegistration_Click( object sender, EventArgs e )
        {
            // set the new registration id
            using ( var rockContext = new RockContext() )
            {
                var registrationService = new RegistrationService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );

                var registration = registrationService.Get( Registration.Id );
                registration.RegistrationInstanceId = ddlNewRegistrationInstance.SelectedValue.AsInteger();

                // Move registrants to new group
                int? groupId = ddlMoveGroup.SelectedValueAsInt();
                if ( groupId.HasValue )
                {
                    registration.GroupId = groupId;
                    rockContext.SaveChanges();

                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        int? groupRoleId = null;
                        var template = registration.RegistrationInstance.RegistrationTemplate;
                        if ( group.GroupTypeId == template.GroupTypeId && template.GroupMemberRoleId.HasValue )
                        {
                            groupRoleId = template.GroupMemberRoleId.Value;
                        }
                        if ( !groupRoleId.HasValue )
                        {
                            groupRoleId = group.GroupType.DefaultGroupRoleId;
                        }
                        if ( !groupRoleId.HasValue )
                        {
                            groupRoleId = group.GroupType.Roles.OrderBy( r => r.Order ).Select( r => r.Id ).FirstOrDefault();
                        }

                        if ( groupRoleId.HasValue )
                        {
                            foreach ( var registrant in registration.Registrants.Where( r => r.PersonAlias != null ) )
                            {
                                var newGroupMembers = groupMemberService.GetByGroupIdAndPersonId( groupId.Value, registrant.PersonAlias.PersonId );
                                if ( !newGroupMembers.Any() )
                                {
                                    // Get any existing group member attribute values
                                    var existingAttributeValues = new Dictionary<string, string>();
                                    if ( registrant.GroupMemberId.HasValue )
                                    {
                                        var existingGroupMember = groupMemberService.Get( registrant.GroupMemberId.Value );
                                        if ( existingGroupMember != null )
                                        {
                                            existingGroupMember.LoadAttributes( rockContext );
                                            foreach ( var attributeValue in existingGroupMember.AttributeValues )
                                            {
                                                existingAttributeValues.Add( attributeValue.Key, attributeValue.Value.Value );
                                            }
                                        }

                                        registrant.GroupMember = null;
                                        groupMemberService.Delete( existingGroupMember );
                                    }

                                    var newGroupMember = new GroupMember();
                                    groupMemberService.Add( newGroupMember );
                                    newGroupMember.Group = group;
                                    newGroupMember.PersonId = registrant.PersonAlias.PersonId;
                                    newGroupMember.GroupRoleId = groupRoleId.Value;
                                    rockContext.SaveChanges();

                                    newGroupMember = groupMemberService.Get( newGroupMember.Id );
                                    newGroupMember.LoadAttributes();

                                    foreach( var attr in newGroupMember.Attributes )
                                    {
                                        if ( existingAttributeValues.ContainsKey( attr.Key ) )
                                        {
                                            newGroupMember.SetAttributeValue( attr.Key, existingAttributeValues[attr.Key] );
                                        }
                                    }
                                    newGroupMember.SaveAttributeValues( rockContext );

                                    registrant.GroupMember = newGroupMember;
                                    rockContext.SaveChanges();

                                }
                            }
                        }
                    }
                }

                // Reload registration
                Registration = GetRegistration( Registration.Id );

                lWizardInstanceName.Text = Registration.RegistrationInstance.Name;
                ShowReadonlyDetails( Registration );
            }

            mdMoveRegistration.Hide();
        }
Exemplo n.º 24
0
        private void BuildGroupMemberAttributes( int? groupId, int? groupMemberRoleId, GroupMemberStatus? groupMemberStatus, bool setValues )
        {
            phGroupMemberAttributes.Controls.Clear();
            phGroupMemberAttributesView.Controls.Clear();

            if ( groupId.HasValue && groupMemberRoleId.HasValue && groupMemberStatus != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    var role = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId.Value );
                    if ( group != null && role != null )
                    {
                        var groupMember = new GroupMember();
                        groupMember.Group = group;
                        groupMember.GroupId = group.Id;
                        groupMember.GroupRole = role;
                        groupMember.GroupRoleId = role.Id;
                        groupMember.GroupMemberStatus = groupMemberStatus.Value;

                        groupMember.LoadAttributes();

                        if ( setValues && !string.IsNullOrWhiteSpace( hfGroupMemberAttributeValues.Value ) )
                        {
                            var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( hfGroupMemberAttributeValues.Value );
                            if ( savedValues != null )
                            {
                                foreach( var item in savedValues )
                                {
                                    groupMember.SetAttributeValue( item.Key, item.Value );
                                }
                            }
                        }

                        Rock.Attribute.Helper.AddEditControls( groupMember, phGroupMemberAttributes, setValues, BlockValidationGroup, 2 );
                        Rock.Attribute.Helper.AddDisplayControls( groupMember, phGroupMemberAttributesView, null, false, false );
                    }
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Handles the Click event of the lbConnect 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 lbConnect_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );
                var connectionActivityTypeService = new ConnectionActivityTypeService( rockContext );
                var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext );
                var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() );

                if ( connectionRequest != null &&
                    connectionRequest.PersonAlias != null &&
                    connectionRequest.ConnectionOpportunity != null )
                {
                    bool okToConnect = true;

                    GroupMember groupMember = null;

                    // Only do group member placement if the request has an assigned placement group, role, and status
                    if ( connectionRequest.AssignedGroupId.HasValue &&
                        connectionRequest.AssignedGroupMemberRoleId.HasValue &&
                        connectionRequest.AssignedGroupMemberStatus.HasValue )
                    {
                        var group = new GroupService( rockContext ).Get( connectionRequest.AssignedGroupId.Value );
                        if ( group != null )
                        {
                            // Only attempt the add if person does not already exist in group with same role
                            groupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( connectionRequest.AssignedGroupId.Value,
                                connectionRequest.PersonAlias.PersonId, connectionRequest.AssignedGroupMemberRoleId.Value );
                            if ( groupMember == null )
                            {
                                groupMember = new GroupMember();
                                groupMember.PersonId = connectionRequest.PersonAlias.PersonId;
                                groupMember.GroupId = connectionRequest.AssignedGroupId.Value;
                                groupMember.GroupRoleId = connectionRequest.AssignedGroupMemberRoleId.Value;
                                groupMember.GroupMemberStatus = connectionRequest.AssignedGroupMemberStatus.Value;

                                foreach ( ListItem item in cblManualRequirements.Items )
                                {
                                    if ( !item.Selected && group.MustMeetRequirementsToAddMember.HasValue && group.MustMeetRequirementsToAddMember.Value )
                                    {
                                        okToConnect = false;
                                        nbRequirementsErrors.Text = "Group Requirements have not been met. Please verify all of the requirements.";
                                        nbRequirementsErrors.Visible = true;
                                        break;
                                    }
                                    else
                                    {
                                        groupMember.GroupMemberRequirements.Add( new GroupMemberRequirement
                                        {
                                            GroupRequirementId = item.Value.AsInteger(),
                                            RequirementMetDateTime = RockDateTime.Now,
                                            LastRequirementCheckDateTime = RockDateTime.Now
                                        } );
                                    }
                                }

                                if ( okToConnect )
                                {
                                    groupMemberService.Add( groupMember );
                                    if ( !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                                    {
                                        var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( connectionRequest.AssignedGroupMemberAttributeValues );
                                        if ( savedValues != null )
                                        {
                                            groupMember.LoadAttributes();
                                            foreach ( var item in savedValues )
                                            {
                                                groupMember.SetAttributeValue( item.Key, item.Value );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if ( okToConnect )
                    {
                        // ... but always record the connection activity and change the state to connected.
                        var guid = Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid();
                        var connectedActivityId = connectionActivityTypeService.Queryable()
                            .Where( t => t.Guid == guid )
                            .Select( t => t.Id )
                            .FirstOrDefault();
                        if ( connectedActivityId > 0 )
                        {
                            var connectionRequestActivity = new ConnectionRequestActivity();
                            connectionRequestActivity.ConnectionRequestId = connectionRequest.Id;
                            connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId;
                            connectionRequestActivity.ConnectionActivityTypeId = connectedActivityId;
                            connectionRequestActivity.ConnectorPersonAliasId = CurrentPersonAliasId;
                            connectionRequestActivityService.Add( connectionRequestActivity );
                        }

                        connectionRequest.ConnectionState = ConnectionState.Connected;

                        rockContext.SaveChanges();
                        if ( groupMember != null && !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                        {
                            groupMember.SaveAttributeValues( rockContext );
                        }

                        ShowDetail( connectionRequest.Id, connectionRequest.ConnectionOpportunityId );
                    }
                }
            }
        }
        private PanelWidget AddCommunicationPanel(Group group, GroupMember member, bool insertValues)
        {
            PanelWidget panelWidget = new PanelWidget
            {
                ID    = "pnl+" + group.Id.ToString() + "panel",
                Title = group.Name
            };

            phGroups.Controls.Add(panelWidget);

            group.LoadAttributes();

            if (group.GetAttributeValue("PublicName").IsNotNullOrWhiteSpace())
            {
                panelWidget.Title = group.GetAttributeValue("PublicName");
            }

            var type = group.GetAttributeValue(GetAttributeValue("AttributeKey"));

            if (type.IsNullOrWhiteSpace())
            {
                type = "Text Message,Email";
            }

            type = string.Join(", ", type.SplitDelimitedValues(false));

            var text = string.Format("<small>{0}</small><p>{1}</p>",
                                     type,
                                     group.Description
                                     );


            Literal literal = new Literal
            {
                Text = text
            };

            panelWidget.Controls.Add(literal);

            var showAttributes = false;

            Panel pnlToggle = new Panel
            {
                ID       = "pnlToggle_" + panelWidget.ID,
                CssClass = "btn-group btn-toggle"
            };

            panelWidget.Controls.Add(pnlToggle);

            if (member.PersonId == Person.Id)
            {
                showAttributes = true;
                LinkButton off = new LinkButton
                {
                    ID               = "btnOff" + panelWidget.ID,
                    CssClass         = "btn btn-default btn-xs",
                    Text             = "Unsubscribe",
                    CausesValidation = false
                };
                pnlToggle.Controls.Add(off);
                off.Click += (s, e) => { Unsubscribe(group.Id); };

                HtmlGenericContainer on = new HtmlGenericContainer
                {
                    TagName   = "div",
                    CssClass  = "btn btn-success btn-xs",
                    InnerText = "Subscribed"
                };
                pnlToggle.Controls.Add(on);
            }
            else
            {
                HtmlGenericContainer off = new HtmlGenericContainer
                {
                    TagName   = "div",
                    CssClass  = "btn btn-danger btn-xs",
                    InnerText = "Unsubscribed"
                };
                pnlToggle.Controls.Add(off);

                LinkButton on = new LinkButton
                {
                    ID               = "btnOn" + panelWidget.ID,
                    CssClass         = "btn btn-default btn-xs",
                    Text             = "Subscribe",
                    CausesValidation = false
                };
                pnlToggle.Controls.Add(on);
                on.Click += (s, e) => { Subscribe(group.Id); };
            }

            member.LoadAttributes();

            member.Attributes = member.Attributes.Where(a => a.Value.IsGridColumn).ToDictionary(a => a.Key, a => a.Value);

            if (member.Attributes.Any())
            {
                Literal attributeTitle = new Literal
                {
                    ID      = "ltAttTitle_" + panelWidget.ID,
                    Text    = "<h3>Subscription Settings</h3>",
                    Visible = showAttributes
                };

                panelWidget.Controls.Add(attributeTitle);

                var attributePlaceholder = new PlaceHolder
                {
                    ID      = "phAtt_" + panelWidget.ID,
                    Visible = showAttributes
                };
                panelWidget.Controls.Add(attributePlaceholder);

                Rock.Attribute.Helper.AddEditControls(member, attributePlaceholder, insertValues);

                BootstrapButton btnSave = new BootstrapButton
                {
                    ID       = "btnSave_" + panelWidget.ID,
                    Text     = "Update Settings",
                    CssClass = "btn btn-primary btn-xs",
                    Visible  = showAttributes
                };
                panelWidget.Controls.Add(btnSave);
                btnSave.Click += (s, e) =>
                {
                    UpdateSettings(member, attributePlaceholder);
                    btnSave.Text = "Saved";
                };
            }
            return(panelWidget);
        }
Exemplo n.º 27
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 )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new RegistrationTemplateService( rockContext );

            RegistrationTemplate RegistrationTemplate = null;

            int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull();
            if ( RegistrationTemplateId.HasValue )
            {
                RegistrationTemplate = service.Get( RegistrationTemplateId.Value );
            }

            if ( RegistrationTemplate == null )
            {
                RegistrationTemplate = new RegistrationTemplate();
            }

            RegistrationNotify notify = RegistrationNotify.None;
            foreach( ListItem li in cblNotify.Items )
            {
                if ( li.Selected )
                {
                    notify = notify | (RegistrationNotify)li.Value.AsInteger();
                }
            }

            RegistrationTemplate.IsActive = cbIsActive.Checked;
            RegistrationTemplate.Name = tbName.Text;
            RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId;
            RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId;
            RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();
            RegistrationTemplate.Notify = notify;
            RegistrationTemplate.LoginRequired = cbLoginRequired.Checked;
            RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked;
            RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger();
            RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>();
            RegistrationTemplate.Cost = cbCost.Text.AsDecimal();
            RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull();
            RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt();

            RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text;
            RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text;
            RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text;
            RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text;

            RegistrationTemplate.ReminderFromName = tbReminderFromName.Text;
            RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text;
            RegistrationTemplate.ReminderSubject = tbReminderSubject.Text;
            RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text;

            RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text;
            RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text;
            RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text;
            RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text;
            RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text;
            RegistrationTemplate.SuccessText = ceSuccessText.Text;

            if ( !Page.IsValid || !RegistrationTemplate.IsValid )
            {
                return;
            }

            foreach ( var form in FormState )
            {
                if ( !form.IsValid )
                {
                    return;
                }

                if ( FormFieldsState.ContainsKey( form.Guid ) )
                {
                    foreach( var formField in FormFieldsState[ form.Guid ])
                    {
                        if ( !formField.IsValid )
                        {
                            return;
                        }
                    }
                }
            }

            // Get the valid group member attributes
            var group = new Group();
            group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
            var groupMember = new GroupMember();
            groupMember.Group = group;
            groupMember.LoadAttributes();
            var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList();

            // Remove any group member attributes that are not valid based on selected group type
            foreach( var fieldList in FormFieldsState.Select( s => s.Value ) )
            {
                foreach( var formField in fieldList
                    .Where( a =>
                        a.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                        a.AttributeId.HasValue &&
                        !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) )
                    .ToList() )
                {
                    fieldList.Remove( formField );
                }
            }

            // Perform Validation
            var validationErrors = new List<string>();
            if ( ( RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue )
            {
                validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees." );
            }

            if ( validationErrors.Any() )
            {
                nbValidationError.Visible = true;
                nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
            }
            else
            {
                rockContext.WrapTransaction( () =>
                {
                    // Save the entity field changes to registration template
                    if ( RegistrationTemplate.Id.Equals( 0 ) )
                    {
                        service.Add( RegistrationTemplate );
                    }
                    rockContext.SaveChanges();

                    var attributeService = new AttributeService( rockContext );
                    var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext );
                    var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext );
                    var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext );
                    var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );

                    // delete forms that aren't assigned in the UI anymore
                    var formUiGuids = FormState.Select( f => f.Guid ).ToList();
                    foreach ( var form in registrationTemplateFormService
                        .Queryable()
                        .Where( f =>
                            f.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !formUiGuids.Contains( f.Guid ) ) )
                    {
                        registrationTemplateFormService.Delete( form );
                    }

                    // delete discounts that aren't assigned in the UI anymore
                    var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList();
                    foreach ( var discount in registrationTemplateDiscountService
                        .Queryable()
                        .Where( d =>
                            d.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !discountUiGuids.Contains( d.Guid ) ) )
                    {
                        registrationTemplateDiscountService.Delete( discount );
                    }

                    // delete fees that aren't assigned in the UI anymore
                    var feeUiGuids = FeeState.Select( u => u.Guid ).ToList();
                    foreach ( var fee in registrationTemplateFeeService
                        .Queryable()
                        .Where( d =>
                            d.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !feeUiGuids.Contains( d.Guid ) ) )
                    {
                        registrationTemplateFeeService.Delete( fee );
                    }

                    var attributesUI = FormFieldsState
                        .SelectMany( s =>
                            s.Value.Where( a =>
                                a.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                a.Attribute != null ) )
                        .Select( f => f.Attribute );

                    int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                    var qualifierColumn = "RegistrationTemplateId";
                    var qualifierValue = RegistrationTemplate.Id.ToString();

                    // Get the existing registration attributes for this entity type and qualifier value
                    var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

                    // Delete any of the registration attributes that were removed in the UI
                    var selectedAttributeGuids = attributesUI.Select( a => a.Guid );
                    foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                    {
                        attributeService.Delete( attr );
                        rockContext.SaveChanges();
                        Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                    }

                    // Update the registration attributes that were assigned in the UI
                    foreach ( var attr in attributesUI )
                    {
                        Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                    }

                    // add/updated forms/fields
                    foreach ( var formUI in FormState )
                    {
                        var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) );
                        if ( form == null )
                        {
                            form = new RegistrationTemplateForm();
                            form.Guid = formUI.Guid;
                            RegistrationTemplate.Forms.Add( form );
                        }
                        form.Name = formUI.Name;
                        form.Order = formUI.Order;

                        if ( FormFieldsState.ContainsKey( form.Guid ) )
                        {
                            var fieldUiGuids = FormFieldsState[form.Guid].Select( a => a.Guid ).ToList();
                            foreach ( var formField in registrationTemplateFormFieldService
                                .Queryable()
                                .Where( a =>
                                    a.RegistrationTemplateForm.Guid.Equals( form.Guid ) &&
                                    !fieldUiGuids.Contains( a.Guid ) ) )
                            {
                                registrationTemplateFormFieldService.Delete( formField );
                            }

                            foreach ( var formFieldUI in FormFieldsState[form.Guid] )
                            {
                                var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) );
                                if ( formField == null )
                                {
                                    formField = new RegistrationTemplateFormField();
                                    formField.Guid = formFieldUI.Guid;
                                    form.Fields.Add( formField );
                                }

                                formField.AttributeId = formFieldUI.AttributeId;
                                if ( !formField.AttributeId.HasValue &&
                                    formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                    formFieldUI.Attribute != null )
                                {
                                    var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext );
                                    if ( attr != null )
                                    {
                                        formField.AttributeId = attr.Id;
                                    }
                                }

                                formField.FieldSource = formFieldUI.FieldSource;
                                formField.PersonFieldType = formFieldUI.PersonFieldType;
                                formField.IsSharedValue = formFieldUI.IsSharedValue;
                                formField.ShowCurrentValue = formFieldUI.ShowCurrentValue;
                                formField.PreText = formFieldUI.PreText;
                                formField.PostText = formFieldUI.PostText;
                                formField.IsGridField = formFieldUI.IsGridField;
                                formField.IsRequired = formFieldUI.IsRequired;
                                formField.Order = formFieldUI.Order;
                            }
                        }
                    }

                    // add/updated discounts
                    foreach ( var discountUI in DiscountState )
                    {
                        var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) );
                        if ( discount == null )
                        {
                            discount = new RegistrationTemplateDiscount();
                            discount.Guid = discountUI.Guid;
                            RegistrationTemplate.Discounts.Add( discount );
                        }
                        discount.Code = discountUI.Code;
                        discount.DiscountPercentage = discountUI.DiscountPercentage;
                        discount.DiscountAmount = discountUI.DiscountAmount;
                        discount.Order = discountUI.Order;
                    }

                    // add/updated fees
                    foreach ( var feeUI in FeeState )
                    {
                        var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) );
                        if ( fee == null )
                        {
                            fee = new RegistrationTemplateFee();
                            fee.Guid = feeUI.Guid;
                            RegistrationTemplate.Fees.Add( fee );
                        }
                        fee.Name = feeUI.Name;
                        fee.FeeType = feeUI.FeeType;
                        fee.CostValue = feeUI.CostValue;
                        fee.DiscountApplies = feeUI.DiscountApplies;
                        fee.AllowMultiple = feeUI.AllowMultiple;
                        fee.Order = feeUI.Order;
                    }

                    rockContext.SaveChanges();

                } );

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Exemplo n.º 28
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 ) );
                }
            }

            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 );
        }
        protected void btnRunSync_Click(object sender, EventArgs e)
        {
            var kvList = GetAttributeValue("ColumnMapping").ToKeyValuePairList();

            RockContext   rockContext   = new RockContext();
            GroupService  groupService  = new GroupService(rockContext);
            PersonService personService = new PersonService(rockContext);

            Group group = groupService.Get(GetAttributeValue("Group").AsGuid());

            foreach (GroupMember gm in group.Members)
            {
                gm.LoadAttributes();
                litSuccess.Text += "Clearing attributes for " + gm.Person + "<br />";
                foreach (var kvp in kvList)
                {
                    gm.SetAttributeValue(kvp.Value.ToString(), "");
                }

                gm.SaveAttributeValues();
            }

            GoogleCredential credential = GoogleCredential.FromJson(GetAttributeValue("ServiceAccountKey"));

            credential = credential.CreateScoped(Scopes);

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = BlockName
            });

            // Define request parameters.
            String spreadsheetId = GetAttributeValue("SpreadsheetId");

            var allPersonIds = new ValueRange()
            {
                Values = new List <IList <object> >()
            };

            litErrors.Text         = "";
            litErrorsSummary.Text  = "";
            litOutput.Text         = "";
            litOutputSummary.Text  = "";
            litSuccess.Text        = "";
            litSuccessSummary.Text = "";
            int errorCount   = 0;
            int successCount = 0;


            foreach (String sheetName in GetAttributeValue("SheetName").SplitDelimitedValues(false))
            {
                if (string.IsNullOrWhiteSpace(sheetName))
                {
                    continue;
                }

                SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, "'" + sheetName + "'!" + GetAttributeValue("StartColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("EndColumn"));
                IList <IList <Object> > data = request.Execute().Values;


                // Prints the names and majors of students in a sample spreadsheet:
                // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
                if (data != null)
                {
                    var personIds = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var phoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent1Names = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent1PhoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent2Names = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent2PhoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    for (var i = 0; i < data.Count; i++)
                    {
                        if (data[i].Count == 0)
                        {
                            continue;
                        }
                        try
                        {
                            string firstName = data[i][GetAttributeValue("FirstNameColumn").AsInteger()].ToString();
                            string lastName  = data[i][GetAttributeValue("LastNameColumn").AsInteger()].ToString();
                            string grade     = data[i][GetAttributeValue("GradeColumn").AsInteger()].ToString();
                            string role      = data[i][GetAttributeValue("RoleColumn").AsInteger()].ToString();
                            string campus    = "";
                            if (!string.IsNullOrEmpty(GetAttributeValue("CampusColumn")))
                            {
                                campus = data[i][GetAttributeValue("CampusColumn").AsInteger()].ToString();
                            }
                            string campusShortCode = "";
                            if (!string.IsNullOrEmpty(GetAttributeValue("Campus")))
                            {
                                campusShortCode = CampusCache.Read(GetAttributeValue("Campus").AsGuid()).ShortCode;
                                if (campusShortCode == "920")
                                {
                                    campusShortCode = "BL";
                                }
                            }


                            string personId           = "";
                            string phone              = "";
                            string parent1Name        = "";
                            string parent1PhoneNumber = "";
                            string parent2Name        = "";
                            string parent2PhoneNumber = "";
                            if (GetAttributeValue("PersonIdColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("PersonIdColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    if (System.Text.RegularExpressions.Regex.IsMatch(data[i][columnIndex].ToString(), "^\\d+$"))
                                    {
                                        personId = data[i][columnIndex].ToString();
                                    }
                                }
                            }

                            if (GetAttributeValue("PersonPhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("PersonPhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    phone = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent1Column") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent1Column").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent1Name = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent1PhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent1PhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent1PhoneNumber = data[i][columnIndex].ToString();
                                }
                            }
                            if (GetAttributeValue("Parent2Column") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent2Column").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent2Name = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent2PhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent2PhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent2PhoneNumber = data[i][columnIndex].ToString();
                                }
                            }

                            // If the role or the campus short code don't match, just skip this
                            if ((GetAttributeValue("Role").ToLower() == "other" && role.ToLower() != "student" || role.ToLower() == GetAttributeValue("Role").ToLower()) && (string.IsNullOrEmpty(campus) || campus == campusShortCode) && firstName != "" && lastName != "")
                            {
                                var members = group.Members.Where(m => (m.Person.NickName.ToLower() == firstName.ToLower().Trim(' ') || m.Person.FirstName.ToLower() == firstName.ToLower().Trim(' ')) && (m.Person.LastName.ToLower() == lastName.ToLower().Trim(' ') || m.Person.LastName.ToLower() == lastName.ToLower().Replace("jr.", "").Trim(' ')));

                                if (members.Count() > 1)
                                {
                                    litErrors.Text += "Matched more than one matching Group Member: " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                    errorCount++;
                                }
                                else if (members.Count() == 1)
                                {
                                    GroupMember member = members.FirstOrDefault();
                                    if (allPersonIds.Values.Select(v => v[0]).Contains(member.PersonId))
                                    {
                                        litErrors.Text += "Duplicate person " + firstName + " " + lastName + " (Sheet: \"" + sheetName + "\" PersonId: " + member.PersonId + " Row: " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + " Duplicate Row: " + (personIds.Values.Select(v => v[0]).ToList().IndexOf(member.PersonId) + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                        errorCount++;
                                    }
                                    else
                                    {
                                        personId = member.PersonId.ToString();
                                        phone    = member.Person.PhoneNumbers.Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault();

                                        var parent1 = member.Person.GetFamilyMembers().Where(fm => fm.GroupRole.Guid.ToString() == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT).Select(fm => fm.Person).FirstOrDefault();

                                        if (parent1 != null)
                                        {
                                            parent1Name        = parent1.NickName + " " + parent1.LastName;
                                            parent1PhoneNumber = personService.Get(parent1.Id).PhoneNumbers.Where(pn => pn.NumberTypeValueId == 12).Select(pn => pn.NumberFormatted).FirstOrDefault();
                                            var parent2 = member.Person.GetFamilyMembers().Where(fm => fm.GroupRole.Guid.ToString() == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT && fm.PersonId != parent1.Id).Select(fm => fm.Person).FirstOrDefault();

                                            if (parent2 != null)
                                            {
                                                parent2Name        = parent2.NickName + " " + parent2.LastName;
                                                parent2PhoneNumber = personService.Get(parent2.Id).PhoneNumbers.Where(pn => pn.NumberTypeValueId == 12).Select(pn => pn.NumberFormatted).FirstOrDefault();
                                            }
                                        }

                                        member.LoadAttributes();

                                        foreach (var kvp in kvList)
                                        {
                                            string value     = "";
                                            var    separator = "";
                                            foreach (var index in kvp.Key.ToString().Replace("%2C", ",").Split(','))
                                            {
                                                if (data[i].Count >= index.AsInteger() + 1 && !string.IsNullOrWhiteSpace(data[i][index.AsInteger()].ToString()))
                                                {
                                                    value    += separator + data[i][index.AsInteger()].ToString();
                                                    separator = "-";
                                                }
                                            }
                                            member.SetAttributeValue(kvp.Value.ToString(), value);
                                        }
                                        member.SaveAttributeValues();

                                        litSuccess.Text += "Updated " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                        successCount++;
                                    }
                                }
                                else
                                {
                                    litErrors.Text += "Unable to find Group Member for " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                    errorCount++;
                                }
                            }

                            personIds.Values.Add(new List <object>()
                            {
                                personId
                            });
                            allPersonIds.Values.Add(new List <object>()
                            {
                                personId
                            });
                            phoneNumbers.Values.Add(new List <object>()
                            {
                                phone
                            });
                            parent1Names.Values.Add(new List <object>()
                            {
                                parent1Name
                            });
                            parent1PhoneNumbers.Values.Add(new List <object>()
                            {
                                parent1PhoneNumber
                            });
                            parent2Names.Values.Add(new List <object>()
                            {
                                parent2Name
                            });
                            parent2PhoneNumbers.Values.Add(new List <object>()
                            {
                                parent2PhoneNumber
                            });
                        }
                        catch (Exception exception)
                        {
                            litErrors.Text += "Error: " + exception.Message + " - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + "<br />";
                        }
                    }

                    if (GetAttributeValue("PersonIdColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(personIds, spreadsheetId, sheetName + "!" + GetAttributeValue("PersonIdColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("PersonIdColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += (litOutput.Text.Length > 0 ? "<br />" : "") + "Updated " + (personIds.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Person Id's on Sheet " + sheetName + " in Column " + GetAttributeValue("PersonIdColumn");
                    }
                    if (GetAttributeValue("PersonPhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(phoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("PersonPhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("PersonPhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (phoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("PersonPhoneColumn");
                    }
                    if (GetAttributeValue("Parent1Column") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent1Names, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent1Column") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent1Column"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent1Names.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 1 Names on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent1Column");
                    }
                    if (GetAttributeValue("Parent1PhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent1PhoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent1PhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent1PhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent1PhoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 1 Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent1PhoneColumn");
                    }
                    if (GetAttributeValue("Parent2Column") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent2Names, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent2Column") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent2Column"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent2Names.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 2 Names on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent2Column");
                    }
                    if (GetAttributeValue("Parent2PhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent2PhoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent2PhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent2PhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent2PhoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 2 Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent2PhoneColumn");
                    }
                }
            }

            var missedPeople = group.Members.Where(gm => !allPersonIds.Values.Select(v => v[0]).Contains(gm.PersonId.ToString()) && gm.GroupMemberStatus == GroupMemberStatus.Active);

            foreach (var person in missedPeople)
            {
                litErrors.Text += "Unable to find entry in Google Sheet for " + person.Person + "<br />";
                errorCount++;
            }

            litErrorsSummary.Text  += errorCount + " Record Errors<br />";
            litSuccessSummary.Text += successCount + " Records Updated";
            litOutputSummary.Text   = "General Information";

            mdShowOutput.Show();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Handles the SelectItem event of the gpMoveGroupMember 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 gpMoveGroupMember_SelectItem( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var destGroup = new GroupService( rockContext ).Get( gpMoveGroupMember.SelectedValue.AsInteger() );
            if ( destGroup != null )
            {
                var destTempGroupMember = new GroupMember { Group = destGroup, GroupId = destGroup.Id };
                destTempGroupMember.LoadAttributes( rockContext );
                var destGroupMemberAttributes = destTempGroupMember.Attributes;
                var groupMember = new GroupMemberService( rockContext ).Get( hfGroupMemberId.Value.AsInteger() );
                groupMember.LoadAttributes();
                var currentGroupMemberAttributes = groupMember.Attributes;

                var lostAttributes = currentGroupMemberAttributes.Where( a => !destGroupMemberAttributes.Any( d => d.Key == a.Key && d.Value.FieldTypeId == a.Value.FieldTypeId ) );
                nbMoveGroupMemberWarning.Visible = lostAttributes.Any();
                nbMoveGroupMemberWarning.Text = "The destination group does not have the same group member attributes as the source. Some loss of data may occur";

                if ( destGroup.Id == groupMember.GroupId )
                {
                    grpMoveGroupMember.Visible = false;
                    nbMoveGroupMemberWarning.Visible = true;
                    nbMoveGroupMemberWarning.Text = "The destination group is the same as the current group";
                }
                else
                {
                    grpMoveGroupMember.Visible = true;
                    grpMoveGroupMember.GroupTypeId = destGroup.GroupTypeId;
                    grpMoveGroupMember.GroupRoleId = destGroup.GroupType.DefaultGroupRoleId;
                }
            }
            else
            {
                nbMoveGroupMemberWarning.Visible = false;
                grpMoveGroupMember.Visible = false;
            }
        }
Exemplo n.º 31
0
        private string GetGroupMemberAttributeValues()
        {
            var groupId = ddlPlacementGroup.SelectedValueAsInt();
            var groupMemberRoleId = ddlPlacementGroupRole.SelectedValueAsInt();
            var groupMemberStatus = ddlPlacementGroupStatus.SelectedValueAsEnumOrNull<GroupMemberStatus>();

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

            if ( groupId.HasValue && groupMemberRoleId.HasValue && groupMemberStatus != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    var role = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId.Value );
                    if ( group != null && role != null )
                    {
                        var groupMember = new GroupMember();
                        groupMember.Group = group;
                        groupMember.GroupId = group.Id;
                        groupMember.GroupRole = role;
                        groupMember.GroupRoleId = role.Id;
                        groupMember.GroupMemberStatus = groupMemberStatus.Value;

                        groupMember.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues( phGroupMemberAttributes, groupMember );

                        foreach( var attrValue in groupMember.AttributeValues )
                        {
                            values.Add( attrValue.Key, attrValue.Value.Value );
                        }

                        return JsonConvert.SerializeObject( values, Formatting.None );
                    }
                }
            }

            return string.Empty;
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnComplete_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                #region Individual Details Updates

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

                var changes = new List<string>();

                if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                {
                    int? newTitleId = ddlTitle.SelectedValueAsInt();
                    EvaluateChange( changes, "Title", DefinedValueCache.GetName( newTitleId ) );
                }

                if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                {
                    int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                    EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( newSuffixId ) );
                }

                if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                {
                    int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                    EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( newConnectionStatusId ) );
                }

                if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                {
                    int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                    EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( newRecordStatusId ) );

                    if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                    {
                        int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                        EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( newInactiveReasonId ) );

                        string newInactiveReasonNote = tbInactiveReasonNote.Text;
                        if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                        {
                            EvaluateChange( changes, "Inactive Reason Note", newInactiveReasonNote );
                        }
                    }
                }

                if ( SelectedFields.Contains( ddlGender.ClientID ) )
                {
                    Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                    EvaluateChange( changes, "Gender", newGender );
                }

                if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                {
                    int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( newMaritalStatusId ) );
                }

                if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                {
                    int? newGraduationYear = null;
                    if ( ypGraduation.SelectedYear.HasValue )
                    {
                        newGraduationYear = ypGraduation.SelectedYear.Value;
                    }
                    EvaluateChange( changes, "Graduation Year", newGraduationYear );
                }

                if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                {
                    bool? newEmailActive = null;
                    if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                    {
                        newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                    }
                    EvaluateChange( changes, "Email Is Active", newEmailActive );
                }

                if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                {
                    EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();
                    EvaluateChange( changes, "Email Preference", newEmailPreference );
                }

                if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                {
                    string newEmailNote = tbEmailNote.Text;
                    EvaluateChange( changes, "Email Note", newEmailNote );
                }

                if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                {
                    string newSystemNote = tbSystemNote.Text;
                    EvaluateChange( changes, "System Note", newSystemNote );
                }

                if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                {
                    int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                    EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( newReviewReason ) );
                }

                if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                {
                    string newReviewReasonNote = tbReviewReasonNote.Text;
                    EvaluateChange( changes, "Review Reason Note", newReviewReasonNote );
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) )
                {
                    int? newCampusId = cpCampus.SelectedCampusId;
                    if ( newCampusId.HasValue )
                    {
                        var campus = CampusCache.Read(newCampusId.Value);
                        if ( campus != null )
                        {
                            EvaluateChange( changes, "Campus (for all family members)", campus.Name );
                        }
                    }
                }

                // following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    bool follow = true;
                    if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                    {
                        follow = ddlFollow.SelectedValue == "Add";
                    }

                    if ( follow )
                    {
                        changes.Add( "Add to your Following list." );
                    }
                    else
                    {
                        changes.Add( "Remove from your Following list." );
                    }
                }

                #endregion

                #region Attributes

                var rockContext = new RockContext();

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    EvaluateChange( changes, attributeCache.Name, attributeCache.FieldType.Field.FormatValue( null, newValue, attributeCache.QualifierValues, false ) );
                                }
                            }
                        }
                    }
                }

                #endregion

                #region Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    changes.Add( string.Format( "Add a <span class='field-name'>{0}Note{1}</span> of <p><span class='field-value'>{2}</span></p>.",
                        ( cbIsPrivate.Checked ? "Private " : "" ), ( cbIsAlert.Checked ? " (Alert)" : "" ), tbNote.Text.ConvertCrLfToHtmlBr() ) );
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue && groupId > 0 )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            changes.Add( string.Format( "Remove from <span class='field-name'>{0}</span> group.", group.Name ) );
                        }
                        else if ( action == "Add")
                        {
                            changes.Add( string.Format( "Add to <span class='field-name'>{0}</span> group.", group.Name ) );
                        }
                        else // Update
                        {
                            if ( SelectedFields.Contains( ddlGroupRole.ClientID ) )
                            {
                                var roleId = ddlGroupRole.SelectedValueAsInt();
                                if ( roleId.HasValue )
                                {
                                    var groupType = GroupTypeCache.Read( group.GroupTypeId );
                                    var role = groupType.Roles.Where( r => r.Id == roleId.Value ).FirstOrDefault();
                                    if ( role != null )
                                    {
                                        string field = string.Format( "{0} Role", group.Name );
                                        EvaluateChange( changes, field, role.Name );
                                    }
                                }
                            }

                            if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                            {
                                string field = string.Format( "{0} Member Status", group.Name );
                                EvaluateChange( changes, field, ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>().ToString() );
                            }

                            var groupMember = new GroupMember();
                            groupMember.Group = group;
                            groupMember.GroupId = group.Id;
                            groupMember.LoadAttributes( rockContext );

                            foreach ( var attributeCache in groupMember.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string field = string.Format( "{0}: {1}", group.Name, attributeCache.Name );
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    EvaluateChange( changes, field, attributeCache.FieldType.Field.FormatValue( null, newValue, attributeCache.QualifierValues, false ) );
                                }
                            }
                        }
                    }
                }

                #endregion

                StringBuilder sb = new StringBuilder();
                sb.AppendFormat( "<p>You are about to make the following updates to {0} individuals:</p>", Individuals.Count().ToString( "N0" ) );
                sb.AppendLine();

                sb.AppendLine( "<ul>" );
                changes.ForEach( c => sb.AppendFormat("<li>{0}</li>\n", c));
                sb.AppendLine( "</ul>" );

                sb.AppendLine( "<p>Please confirm that you want to make these updates.</p>");

                phConfirmation.Controls.Add( new LiteralControl( sb.ToString() ) );

                pnlEntry.Visible = false;
                pnlConfirm.Visible = true;

            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                Guid checkinGroupAttributeGuid = GetAttributeValue(action, "CheckinGroupAttribute").AsGuid();
                if (checkinGroupAttributeGuid == Guid.Empty)
                {
                    throw new Exception("CheckInGroupAttribute not set. Set attribute to continue.");
                }
                string checkinGroupAttributeKey = AttributeCache.Read(checkinGroupAttributeGuid, rockContext).Key;

                string sessionAttributeKey = GetAttributeValue(action, "SessionAttributeKey");

                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = RockDateTime.Now;

                bool reuseCodeForFamily = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;

                AttendanceCodeService attendanceCodeService = new AttendanceCodeService(rockContext);
                AttendanceService     attendanceService     = new AttendanceService(rockContext);
                GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
                PersonAliasService    personAliasService    = new PersonAliasService(rockContext);
                GroupService          groupService          = new GroupService(rockContext);

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    foreach (var person in family.GetPeople(true))
                    {
                        if (reuseCodeForFamily && attendanceCode != null)
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode      = AttendanceCodeService.GetNew(securityCodeLength);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GetGroupTypes(true))
                        {
                            foreach (var group in groupType.GetGroups(true))
                            {
                                var referenceGroupGuid = group.Group.GetAttributeValue(checkinGroupAttributeKey).AsGuid();
                                var referenceGroup     = groupService.Get(referenceGroupGuid);
                                if (referenceGroup == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                GroupMember groupMember = groupMemberService.GetByGroupIdAndPersonId(referenceGroup.Id, person.Person.Id).FirstOrDefault();
                                if (groupMember == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                groupMember.LoadAttributes();
                                int sessions = groupMember.GetAttributeValue(sessionAttributeKey).AsInteger();

                                foreach (var location in group.GetLocations(true))
                                {
                                    foreach (var schedule in location.GetSchedules(true))
                                    {
                                        if (sessions == 0)
                                        {
                                            continue;
                                        }

                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get(startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id);
                                        if (attendance == null)
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                            if (primaryAlias != null)
                                            {
                                                attendance                   = rockContext.Attendances.Create();
                                                attendance.LocationId        = location.Location.Id;
                                                attendance.CampusId          = location.CampusId;
                                                attendance.ScheduleId        = schedule.Schedule.Id;
                                                attendance.GroupId           = group.Group.Id;
                                                attendance.PersonAlias       = primaryAlias;
                                                attendance.PersonAliasId     = primaryAlias.Id;
                                                attendance.DeviceId          = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendanceService.Add(attendance);
                                            }

                                            //decrement sessions and save
                                            sessions--;
                                            groupMember.SetAttributeValue(sessionAttributeKey, sessions);
                                            groupMember.SaveAttributeValues();
                                        }
                                        else
                                        {
                                            foreach (var cPerson in checkInState.CheckIn.Families.SelectMany(f => f.People))
                                            {
                                                cPerson.Selected = false;
                                                cPerson.GroupTypes.ForEach(gt => gt.Selected = false);
                                            }
                                            return(true);
                                        }

                                        attendance.AttendanceCodeId = attendanceCode.Id;
                                        attendance.StartDateTime    = startDateTime;
                                        attendance.EndDateTime      = null;
                                        attendance.DidAttend        = true;

                                        KioskLocationAttendance.AddAttendance(attendance);
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.SaveChanges();
                return(true);
            }
            return(false);
        }
        private void BuildGroupAttributes( Group group, RockContext rockContext, bool setValues )
        {
            if (group != null)
            {
                string action = ddlGroupAction.SelectedValue;

                var groupMember = new GroupMember();
                groupMember.Group = group;
                groupMember.GroupId = group.Id;
                groupMember.LoadAttributes( rockContext );

                foreach ( var attributeCache in groupMember.Attributes.Select( a => a.Value ) )
                {
                    string labelText = attributeCache.Name;
                    bool controlEnabled = true;
                    if ( action == "Update" )
                    {
                        string clientId = string.Format( "{0}_attribute_field_{1}", phAttributes.NamingContainer.ClientID, attributeCache.Id );
                        controlEnabled = SelectedFields.Contains( clientId, StringComparer.OrdinalIgnoreCase );

                        string iconCss = controlEnabled ? "fa-check-circle-o" : "fa-circle-o";
                        labelText = string.Format( "<span class='js-select-item'><i class='fa {0}'></i></span> {1}", iconCss, attributeCache.Name );
                    }

                    Control control = attributeCache.AddControl( phAttributes.Controls, attributeCache.DefaultValue, string.Empty, setValues, true, attributeCache.IsRequired, labelText );

                    if ( action == "Update" && !( control is RockCheckBox ) )
                    {
                        var webControl = control as WebControl;
                        if ( webControl != null )
                        {
                            webControl.Enabled = controlEnabled;
                        }
                    }
                }
            }
        }
        /// <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 )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new RegistrationTemplateService( rockContext );

            RegistrationTemplate RegistrationTemplate = null;

            int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull();
            if ( RegistrationTemplateId.HasValue )
            {
                RegistrationTemplate = service.Get( RegistrationTemplateId.Value );
            }

            bool newTemplate = false;
            if ( RegistrationTemplate == null )
            {
                newTemplate = true;
                RegistrationTemplate = new RegistrationTemplate();
            }

            RegistrationNotify notify = RegistrationNotify.None;
            foreach( ListItem li in cblNotify.Items )
            {
                if ( li.Selected )
                {
                    notify = notify | (RegistrationNotify)li.Value.AsInteger();
                }
            }

            RegistrationTemplate.IsActive = cbIsActive.Checked;
            RegistrationTemplate.Name = tbName.Text;
            RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId;
            RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId;
            RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();
            RegistrationTemplate.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt();
            RegistrationTemplate.SignatureDocumentAction = cbDisplayInLine.Checked ? SignatureDocumentAction.Embed : SignatureDocumentAction.Email;

            RegistrationTemplate.RegistrationWorkflowTypeId = wtpRegistrationWorkflow.SelectedValueAsInt();
            RegistrationTemplate.Notify = notify;
            RegistrationTemplate.AddPersonNote = cbAddPersonNote.Checked;
            RegistrationTemplate.LoginRequired = cbLoginRequired.Checked;
            RegistrationTemplate.AllowExternalRegistrationUpdates = cbAllowExternalUpdates.Checked;
            RegistrationTemplate.AllowGroupPlacement = cbAllowGroupPlacement.Checked;
            RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked;
            RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger();
            RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>();
            RegistrationTemplate.ShowCurrentFamilyMembers = cbShowCurrentFamilyMembers.Checked;
            RegistrationTemplate.SetCostOnInstance = !tglSetCostOnTemplate.Checked;
            RegistrationTemplate.Cost = cbCost.Text.AsDecimal();
            RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull();
            RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt();
            RegistrationTemplate.BatchNamePrefix = txtBatchNamePrefix.Text;

            RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text;
            RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text;
            RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text;
            RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text;

            RegistrationTemplate.ReminderFromName = tbReminderFromName.Text;
            RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text;
            RegistrationTemplate.ReminderSubject = tbReminderSubject.Text;
            RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text;

            RegistrationTemplate.PaymentReminderFromName = tbPaymentReminderFromName.Text;
            RegistrationTemplate.PaymentReminderFromEmail = tbPaymentReminderFromEmail.Text;
            RegistrationTemplate.PaymentReminderSubject = tbPaymentReminderSubject.Text;
            RegistrationTemplate.PaymentReminderEmailTemplate = cePaymentReminderEmailTemplate.Text;
            RegistrationTemplate.PaymentReminderTimeSpan = nbPaymentReminderTimeSpan.Text.AsInteger();

            RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text;
            RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text;
            RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text;
            RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text;
            RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text;
            RegistrationTemplate.SuccessText = ceSuccessText.Text;

            if ( !Page.IsValid || !RegistrationTemplate.IsValid )
            {
                return;
            }

            foreach ( var form in FormState )
            {
                if ( !form.IsValid )
                {
                    return;
                }

                if ( FormFieldsState.ContainsKey( form.Guid ) )
                {
                    foreach( var formField in FormFieldsState[ form.Guid ])
                    {
                        if ( !formField.IsValid )
                        {
                            return;
                        }
                    }
                }
            }

            // Get the valid group member attributes
            var group = new Group();
            group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
            var groupMember = new GroupMember();
            groupMember.Group = group;
            groupMember.LoadAttributes();
            var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList();

            // Remove any group member attributes that are not valid based on selected group type
            foreach( var fieldList in FormFieldsState.Select( s => s.Value ) )
            {
                foreach( var formField in fieldList
                    .Where( a =>
                        a.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                        a.AttributeId.HasValue &&
                        !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) )
                    .ToList() )
                {
                    fieldList.Remove( formField );
                }
            }

            // Perform Validation
            var validationErrors = new List<string>();
            if ( ( ( RegistrationTemplate.SetCostOnInstance ?? false ) || RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue )
            {
                validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees or is configured to allow instances to set a cost." );
            }

            if ( validationErrors.Any() )
            {
                nbValidationError.Visible = true;
                nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
            }
            else
            {
                // Save the entity field changes to registration template
                if ( RegistrationTemplate.Id.Equals( 0 ) )
                {
                    service.Add( RegistrationTemplate );
                }
                rockContext.SaveChanges();

                var attributeService = new AttributeService( rockContext );
                var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext );
                var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext );
                var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext );
                var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );
                var registrationRegistrantFeeService = new RegistrationRegistrantFeeService( rockContext );

                var groupService = new GroupService( rockContext );

                // delete forms that aren't assigned in the UI anymore
                var formUiGuids = FormState.Select( f => f.Guid ).ToList();
                foreach ( var form in registrationTemplateFormService
                    .Queryable()
                    .Where( f =>
                        f.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !formUiGuids.Contains( f.Guid ) ) )
                {
                    foreach( var formField in form.Fields.ToList() )
                    {
                        form.Fields.Remove( formField );
                        registrationTemplateFormFieldService.Delete( formField );
                    }
                    registrationTemplateFormService.Delete( form );
                }

                // delete fields that aren't assigned in the UI anymore
                var fieldUiGuids = FormFieldsState.SelectMany( a => a.Value).Select( f => f.Guid ).ToList();
                foreach ( var formField in registrationTemplateFormFieldService
                    .Queryable()
                    .Where( a =>
                        formUiGuids.Contains( a.RegistrationTemplateForm.Guid ) &&
                        !fieldUiGuids.Contains( a.Guid ) ) )
                {
                    registrationTemplateFormFieldService.Delete( formField );
                }

                // delete discounts that aren't assigned in the UI anymore
                var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList();
                foreach ( var discount in registrationTemplateDiscountService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !discountUiGuids.Contains( d.Guid ) ) )
                {
                    registrationTemplateDiscountService.Delete( discount );
                }

                // delete fees that aren't assigned in the UI anymore
                var feeUiGuids = FeeState.Select( u => u.Guid ).ToList();
                var deletedfees = registrationTemplateFeeService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !feeUiGuids.Contains( d.Guid ) )
                    .ToList();

                var deletedFeeIds = deletedfees.Select( f => f.Id ).ToList();
                foreach ( var registrantFee in registrationRegistrantFeeService
                    .Queryable()
                    .Where( f => deletedFeeIds.Contains( f.RegistrationTemplateFeeId ) )
                    .ToList() )
                {
                    registrationRegistrantFeeService.Delete( registrantFee );
                }

                foreach ( var fee in deletedfees )
                {
                    registrationTemplateFeeService.Delete( fee );
                }

                int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                var qualifierColumn = "RegistrationTemplateId";
                var qualifierValue = RegistrationTemplate.Id.ToString();

                // Get the registration attributes still in the UI
                var attributesUI = FormFieldsState
                    .SelectMany( s =>
                        s.Value.Where( a =>
                            a.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                            a.Attribute != null ) )
                    .Select( f => f.Attribute )
                    .ToList();
                var selectedAttributeGuids = attributesUI.Select( a => a.Guid );

                // Delete the registration attributes that were removed from the UI
                var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );
                foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ).ToList() )
                {
                    attributeService.Delete( attr );
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                }

                rockContext.SaveChanges();

                // Save all of the registration attributes still in the UI
                foreach ( var attr in attributesUI )
                {
                    Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

                // add/updated forms/fields
                foreach ( var formUI in FormState )
                {
                    var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) );
                    if ( form == null )
                    {
                        form = new RegistrationTemplateForm();
                        form.Guid = formUI.Guid;
                        RegistrationTemplate.Forms.Add( form );
                    }
                    form.Name = formUI.Name;
                    form.Order = formUI.Order;

                    if ( FormFieldsState.ContainsKey( form.Guid ) )
                    {
                        foreach ( var formFieldUI in FormFieldsState[form.Guid] )
                        {
                            var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) );
                            if ( formField == null )
                            {
                                formField = new RegistrationTemplateFormField();
                                formField.Guid = formFieldUI.Guid;
                                form.Fields.Add( formField );
                            }

                            formField.AttributeId = formFieldUI.AttributeId;
                            if ( !formField.AttributeId.HasValue &&
                                formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                formFieldUI.Attribute != null )
                            {
                                var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext );
                                if ( attr != null )
                                {
                                    formField.AttributeId = attr.Id;
                                }
                            }

                            formField.FieldSource = formFieldUI.FieldSource;
                            formField.PersonFieldType = formFieldUI.PersonFieldType;
                            formField.IsInternal = formFieldUI.IsInternal;
                            formField.IsSharedValue = formFieldUI.IsSharedValue;
                            formField.ShowCurrentValue = formFieldUI.ShowCurrentValue;
                            formField.PreText = formFieldUI.PreText;
                            formField.PostText = formFieldUI.PostText;
                            formField.IsGridField = formFieldUI.IsGridField;
                            formField.IsRequired = formFieldUI.IsRequired;
                            formField.Order = formFieldUI.Order;
                        }
                    }
                }

                // add/updated discounts
                foreach ( var discountUI in DiscountState )
                {
                    var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) );
                    if ( discount == null )
                    {
                        discount = new RegistrationTemplateDiscount();
                        discount.Guid = discountUI.Guid;
                        RegistrationTemplate.Discounts.Add( discount );
                    }
                    discount.Code = discountUI.Code;
                    discount.DiscountPercentage = discountUI.DiscountPercentage;
                    discount.DiscountAmount = discountUI.DiscountAmount;
                    discount.Order = discountUI.Order;
                }

                // add/updated fees
                foreach ( var feeUI in FeeState )
                {
                    var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) );
                    if ( fee == null )
                    {
                        fee = new RegistrationTemplateFee();
                        fee.Guid = feeUI.Guid;
                        RegistrationTemplate.Fees.Add( fee );
                    }
                    fee.Name = feeUI.Name;
                    fee.FeeType = feeUI.FeeType;
                    fee.CostValue = feeUI.CostValue;
                    fee.DiscountApplies = feeUI.DiscountApplies;
                    fee.AllowMultiple = feeUI.AllowMultiple;
                    fee.Order = feeUI.Order;
                }

                rockContext.SaveChanges();

                AttributeCache.FlushEntityAttributes();

                // If this is a new template, give the current user and the Registration Administrators role administrative
                // rights to this template, and staff, and staff like roles edit rights
                if ( newTemplate )
                {
                    RegistrationTemplate.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );

                    var registrationAdmins = groupService.Get( Rock.SystemGuid.Group.GROUP_EVENT_REGISTRATION_ADMINISTRATORS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.ADMINISTRATE, registrationAdmins, rockContext );

                    var staffLikeUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_LIKE_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffLikeUsers, rockContext );

                    var staffUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffUsers, rockContext );
                }

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnConfirm_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                #region Individual Details Updates

                int? newTitleId = ddlTitle.SelectedValueAsInt();
                int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                string newInactiveReasonNote = tbInactiveReasonNote.Text;
                Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                int? newGraduationYear = null;
                if ( ypGraduation.SelectedYear.HasValue )
                {
                    newGraduationYear = ypGraduation.SelectedYear.Value;
                }

                int? newCampusId = cpCampus.SelectedCampusId;

                bool? newEmailActive = null;
                if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                {
                    newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                }

                EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();

                string newEmailNote = tbEmailNote.Text;

                int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                string newSystemNote = tbSystemNote.Text;
                string newReviewReasonNote = tbReviewReasonNote.Text;

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

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

                var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();
                foreach ( var person in people )
                {
                    var changes = new List<string>();
                    allChanges.Add( person.Id, changes );

                    if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                        person.TitleValueId = newTitleId;
                    }

                    if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                        person.SuffixValueId = newSuffixId;
                    }

                    if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                        person.ConnectionStatusValueId = newConnectionStatusId;
                    }

                    if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                        person.RecordStatusValueId = newRecordStatusId;

                        if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;

                            if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                            {
                                History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                                person.InactiveReasonNote = newInactiveReasonNote;
                            }
                        }
                    }

                    if ( SelectedFields.Contains( ddlGender.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                        person.Gender = newGender;
                    }

                    if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                        person.MaritalStatusValueId = newMaritalStatusId;
                    }

                    if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear );
                        person.GraduationYear = newGraduationYear;
                    }

                    if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                        person.IsEmailActive = newEmailActive;
                    }

                    if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                        person.EmailPreference = newEmailPreference.Value;
                    }

                    if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                        person.EmailNote = newEmailNote;
                    }

                    if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                        person.SystemNote = newSystemNote;
                    }

                    if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                        person.ReviewReasonValueId = newReviewReason;
                    }

                    if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                        person.ReviewReasonNote = newReviewReasonNote;
                    }
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue )
                {
                    int campusId = cpCampus.SelectedCampusId.Value;

                    Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );

                    var familyMembers = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => new { m.PersonId, m.GroupId } )
                        .Distinct()
                        .ToList();

                    var families = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => m.Group )
                        .Distinct()
                        .ToList();

                    foreach ( int personId in ids )
                    {
                        var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList();
                        if ( familyIds.Count == 1 )
                        {
                            int familyId = familyIds.FirstOrDefault();
                            var family = families.Where( g => g.Id == familyId ).FirstOrDefault();
                            {
                                if ( family != null )
                                {
                                    family.CampusId = campusId;
                                }
                                familyMembers.RemoveAll( m => m.GroupId == familyId );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                // Update following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
                    if ( personAliasEntityType != null )
                    {
                        int personAliasEntityTypeId = personAliasEntityType.Id;

                        bool follow = true;
                        if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                        {
                            follow = ddlFollow.SelectedValue == "Add";
                        }

                        var personAliasService = new PersonAliasService( rockContext );
                        var followingService = new FollowingService( rockContext );
                        if ( follow )
                        {
                            var paQry = personAliasService.Queryable();

                            var alreadyFollowingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } )
                                .Select( p => p.PersonAlias.PersonId )
                                .Distinct()
                                .ToList();

                            foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personAliasEntityTypeId,
                                    EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            var paQry = personAliasService.Queryable()
                                .Where( p => ids.Contains( p.PersonId ) )
                                .Select( p => p.Id );

                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    paQry.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                #endregion

                #region Attributes

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    attributes.Add( attributeCache );
                                    attributeValues.Add( attributeCache.Id, newValue );
                                }
                            }
                        }
                    }
                }

                if ( attributes.Any() )
                {
                    foreach ( var person in people )
                    {
                        person.LoadAttributes();
                        foreach ( var attribute in attributes )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = attributeValues[attribute.Id];
                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

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

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

                                History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                // Create the history records
                foreach ( var changes in allChanges )
                {
                    if ( changes.Value.Any() )
                    {
                        HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            changes.Key, changes.Value );
                    }
                }
                rockContext.SaveChanges();

                #endregion

                #region Add Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    string text = tbNote.Text;
                    bool isAlert = cbIsAlert.Checked;
                    bool isPrivate = cbIsPrivate.Checked;

                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                    if ( noteType != null )
                    {
                        var notes = new List<Note>();
                        var noteService = new NoteService( rockContext );

                        foreach ( int id in ids )
                        {
                            var note = new Note();
                            note.IsSystem = false;
                            note.EntityId = id;
                            note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                            note.Text = tbNote.Text;
                            note.IsAlert = cbIsAlert.Checked;
                            note.NoteType = noteType;
                            notes.Add( note );
                            noteService.Add( note );
                        }

                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.SaveChanges();
                            foreach ( var note in notes )
                            {
                                note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                if ( isPrivate )
                                {
                                    note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                }
                            }
                        } );

                    }
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        var groupMemberService = new GroupMemberService( rockContext );

                        var existingMembers = groupMemberService.Queryable( "Group" )
                            .Where( m =>
                                m.GroupId == group.Id &&
                                ids.Contains( m.PersonId ) )
                            .ToList();

                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            groupMemberService.DeleteRange( existingMembers );
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            var roleId = ddlGroupRole.SelectedValueAsInt();
                            var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                            // Get the attribute values updated
                            var gm = new GroupMember();
                            gm.Group = group;
                            gm.GroupId = group.Id;
                            gm.LoadAttributes( rockContext );
                            var selectedGroupAttributes = new List<AttributeCache>();
                            var selectedGroupAttributeValues = new Dictionary<string, string>();
                            foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    selectedGroupAttributes.Add( attributeCache );
                                    selectedGroupAttributeValues.Add( attributeCache.Key, newValue );
                                }
                            }

                            if ( action == "Add" )
                            {
                                if ( roleId.HasValue )
                                {
                                    var newGroupMembers = new List<GroupMember>();

                                    var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList();
                                    foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) )
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId = group.Id;
                                        groupMember.GroupRoleId = roleId.Value;
                                        groupMember.GroupMemberStatus = status;
                                        groupMember.PersonId = id;
                                        groupMemberService.Add( groupMember );
                                        newGroupMembers.Add( groupMember );
                                    }

                                    rockContext.SaveChanges();

                                    if ( selectedGroupAttributes.Any() )
                                    {
                                        foreach ( var groupMember in newGroupMembers )
                                        {
                                            foreach ( var attribute in selectedGroupAttributes )
                                            {
                                                Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                            }
                                        }
                                    }
                                }
                            }
                            else // Update
                            {
                                if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue )
                                {
                                    foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) )
                                    {
                                        if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() )
                                        {
                                            member.GroupRoleId = roleId.Value;
                                        }
                                    }
                                }

                                if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                                {
                                    foreach ( var member in existingMembers )
                                    {
                                        member.GroupMemberStatus = status;
                                    }
                                }

                                rockContext.SaveChanges();

                                if ( selectedGroupAttributes.Any() )
                                {
                                    foreach ( var groupMember in existingMembers )
                                    {
                                        foreach ( var attribute in selectedGroupAttributes )
                                        {
                                            Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                pnlEntry.Visible = false;
                pnlConfirm.Visible = false;

                nbResult.Text = string.Format( "{0} {1} succesfully updated.",
                    ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ;
                pnlResult.Visible = true;
            }
        }