private void SaveGroupMember(RockContext rockContext, GroupMember groupMember, Panel pnlWell, List <AttributeCache> AttributeList, TextBox notes)
        {
            var changes = new List <string>();

            foreach (var attribute in AttributeList)
            {
                if (Person != null && groupMember.Group.IsAuthorized(Authorization.EDIT, CurrentPerson))
                {
                    groupMember.Note = notes.Text;
                    rockContext.SaveChanges();

                    Control attributeControl = pnlWell.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                    if (attributeControl != null)
                    {
                        string newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                        groupMember.SetAttributeValue(attribute.Key, newValue);

                        groupMember.SaveAttributeValues();
                    }
                }
            }
            ShowEdit(groupMember.Id);
        }
        /// <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);
        }
Esempio n. 3
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);
        }
        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();
        }
 private void UpdateSettings(GroupMember member, PlaceHolder attributePlaceholder)
 {
     Rock.Attribute.Helper.GetEditValues(attributePlaceholder, member);
     member.SaveAttributeValues();
 }
        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();
        }
Esempio n. 7
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 );
        }