/// <summary> /// Shows the detail. /// </summary> /// <param name="groupTypeId">The groupType identifier.</param> public void ShowDetail( int groupTypeId ) { pnlDetails.Visible = false; bool editAllowed = true; GroupType groupType = null; if ( !groupTypeId.Equals( 0 ) ) { groupType = new GroupTypeService( new RockContext() ).Get( groupTypeId ); pdAuditDetails.SetEntity( groupType, ResolveRockUrl( "~" ) ); } if ( groupType == null ) { groupType = new GroupType { Id = 0 }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } if ( groupType != null ) { editAllowed = groupType.IsAuthorized( Authorization.EDIT, CurrentPerson ); pnlDetails.Visible = true; hfGroupTypeId.Value = groupType.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( GroupType.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( groupType ); } else { btnEdit.Visible = true; btnDelete.Visible = true; if ( groupType.Id > 0 ) { ShowReadonlyDetails( groupType ); } else { ShowEditDetails( groupType ); } } } }
/// <summary> /// Handles the Delete event of the gGroupType control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gGroupType_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupType groupType = groupTypeService.Get( e.RowKeyId ); if ( groupType != null ) { int groupTypeId = groupType.Id; if ( !groupType.IsAuthorized( "Administrate", CurrentPerson ) ) { mdGridWarning.Show( "Sorry, you're not authorized to delete this group type.", ModalAlertType.Alert ); return; } string errorMessage; if ( !groupTypeService.CanDelete( groupType, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Alert ); return; } groupType.ParentGroupTypes.Clear(); groupType.ChildGroupTypes.Clear(); groupTypeService.Delete( groupType ); rockContext.SaveChanges(); GroupTypeCache.Flush( groupTypeId ); } BindGrid(); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; string[] parts = ( value ?? string.Empty ).Split( '|' ); Guid? groupTypeGuid = parts[0].AsGuidOrNull(); Guid? groupGuid = parts[1].AsGuidOrNull(); var rockContext = new RockContext(); if ( groupGuid.HasValue ) { var group = new GroupService( rockContext ).Get( groupGuid.Value ); if ( group != null ) { formattedValue = "Group: " + group.Name; } } else if ( groupTypeGuid.HasValue ) { var groupType = new GroupTypeService( rockContext ).Get( groupTypeGuid.Value ); if ( groupType != null ) { formattedValue = "Group type: " + groupType.Name; } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
protected void doCheckinGroupStuff() { int checkinConfigFilter = int.TryParse(gtpCheckinConfig.SelectedValue, out checkinConfigFilter) ? checkinConfigFilter : -1; int checkinAreaFilter = int.TryParse(gtpCheckinArea.SelectedValue, out checkinAreaFilter) ? checkinAreaFilter : -1; int checkinGroupFilter = int.TryParse(rddlCheckinGroup.SelectedValue, out checkinGroupFilter) ? checkinGroupFilter : -1; int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE)).Id; List<GroupType> checkinConfigs = new GroupTypeService(_rockContext).Queryable().Where(a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId).OrderBy(a => a.ParentGroupTypes.FirstOrDefault().Id).ThenBy(a => a.Order).ThenBy(a => a.Name).ToList(); gtpCheckinConfig.GroupTypes = checkinConfigs; if (gtpCheckinConfig.Items.FindByValue(checkinConfigFilter.ToString()) != null) { gtpCheckinConfig.SelectedValue = checkinConfigFilter.ToString(); } gtpCheckinArea.GroupTypes = getCGT(checkinConfigs.Where(a => a.Id == gtpCheckinConfig.SelectedGroupTypeId).ToList(), ""); if (gtpCheckinArea.Items.FindByValue(checkinAreaFilter.ToString()) != null) { gtpCheckinArea.SelectedValue = checkinAreaFilter.ToString(); } List<Rock.Model.Group> checkinGroups = new GroupService(_rockContext).Queryable().Where(a => a.GroupTypeId == gtpCheckinArea.SelectedGroupTypeId).OrderBy(a => a.Order).ThenBy(a => a.Name).ToList(); checkinGroups.Insert(0, new Rock.Model.Group() { Name = "", Id = -1 }); rddlCheckinGroup.DataSource = checkinGroups; rddlCheckinGroup.DataTextField = "Name"; rddlCheckinGroup.DataValueField = "Id"; rddlCheckinGroup.DataBind(); if (rddlCheckinGroup.Items.FindByValue(checkinGroupFilter.ToString()) != null) { rddlCheckinGroup.SelectedValue = checkinGroupFilter.ToString(); } }
/// <summary> /// Creates the control(s) neccessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <returns> /// The control /// </returns> public override System.Web.UI.Control EditControl( Dictionary<string, ConfigurationValue> configurationValues ) { CheckBoxList editControl = new CheckBoxList(); GroupTypeService groupTypeService = new GroupTypeService(); var groupTypes = groupTypeService.Queryable().OrderBy( a => a.Name ).ToList(); foreach ( var groupType in groupTypes ) { editControl.Items.Add(new ListItem(groupType.Name, groupType.Id.ToString())); } return editControl; }
/// <summary> /// Creates the control(s) neccessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override System.Web.UI.Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id ) { var editControl = new GroupTypePicker { ID = id }; var qryGroupTypes = new GroupTypeService( new RockContext() ).Queryable(); if ( configurationValues.ContainsKey( GROUP_TYPE_PURPOSE_VALUE_GUID ) ) { var groupTypePurposeValueGuid = ( configurationValues[GROUP_TYPE_PURPOSE_VALUE_GUID] ).Value.AsGuidOrNull(); if ( groupTypePurposeValueGuid.HasValue ) { qryGroupTypes = qryGroupTypes.Where( a => a.GroupTypePurposeValue.Guid == groupTypePurposeValueGuid.Value ); } } editControl.GroupTypes = qryGroupTypes.OrderBy( a => a.Name ).ToList(); return editControl; }
public GroupOfTypeResult GetInGroupOfType(int personId, Guid groupTypeId) { GroupOfTypeResult result = new GroupOfTypeResult(); result.PersonId = personId; result.PersonInGroup = false; result.GroupList = new List<GroupSummary>(); // get person info Person person = new PersonService( (Rock.Data.RockContext)Service.Context ).Get( personId ); if (person != null) { result.NickName = person.NickName; result.LastName = person.LastName; } // get group type info GroupType groupType = new GroupTypeService( (Rock.Data.RockContext)Service.Context ).Get( groupTypeId ); if (groupType != null) { result.GroupTypeName = groupType.Name; result.GroupTypeIconCss = groupType.IconCssClass; result.GroupTypeId = groupType.Id; } // determine if person is in this type of group GroupMemberService groupMemberService = new GroupMemberService( (Rock.Data.RockContext)Service.Context ); IQueryable<GroupMember> groupMembershipsQuery = groupMemberService.Queryable("Person,GroupRole,Group") .Where(t => t.Group.GroupType.Guid == groupTypeId && t.PersonId == personId ) .OrderBy(g => g.GroupRole.Order); foreach (GroupMember member in groupMembershipsQuery) { result.PersonInGroup = true; GroupSummary group = new GroupSummary(); group.GroupName = member.Group.Name; group.GroupId = member.Group.Id; group.RoleName = member.GroupRole.Name; result.GroupList.Add(group); } return result; }
/// <summary> /// Creates the HTML controls required to configure this type of field /// </summary> /// <returns></returns> public override List<Control> ConfigurationControls() { var controls = base.ConfigurationControls(); // build a drop down list of defined types (the one that gets selected is // used to build a list of defined values) var ddl = new RockDropDownList(); controls.Add( ddl ); ddl.AutoPostBack = true; ddl.SelectedIndexChanged += OnQualifierUpdated; ddl.Label = "Group Type"; ddl.Help = "Type of group to select roles from, if left blank any group type's role can be selected."; ddl.Items.Add( new ListItem() ); var groupTypeService = new GroupTypeService( new RockContext() ); var groupTypes = groupTypeService.Queryable().OrderBy( a => a.Name ).ToList(); groupTypes.ForEach( g => ddl.Items.Add( new ListItem( g.Name, g.Id.ToString().ToUpper() ) ) ); return controls; }
/// <summary> /// Shows the settings. /// </summary> protected override void ShowSettings() { pnlEditModal.Visible = true; upnlContent.Update(); mdEdit.Show(); var rockContext = new RockContext(); var groupTypes = new GroupTypeService( rockContext ) .Queryable().AsNoTracking().ToList(); BindGroupType( gtpGroupType, groupTypes, "GroupType" ); BindGroupType( gtpGeofenceGroupType, groupTypes, "GeofencedGroupType" ); string scheduleFilters = GetAttributeValue( "ScheduleFilters" ); if ( !string.IsNullOrEmpty( scheduleFilters ) ) { foreach ( string val in scheduleFilters.SplitDelimitedValues() ) { var li = cblSchedule.Items.FindByValue( val ); if ( li != null ) { li.Selected = true; } } } SetGroupTypeOptions(); foreach ( string attr in GetAttributeValue( "AttributeFilters" ).SplitDelimitedValues() ) { var li = cblAttributes.Items.FindByValue( attr ); if ( li != null ) { li.Selected = true; } } cbShowMap.Checked = GetAttributeValue( "ShowMap" ).AsBoolean(); ddlMapStyle.BindToDefinedType( DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.MAP_STYLES.AsGuid() ) ); ddlMapStyle.SetValue( GetAttributeValue( "MapStyle" ) ); nbMapHeight.Text = GetAttributeValue( "MapHeight" ); cbShowFence.Checked = GetAttributeValue( "ShowFence" ).AsBoolean(); vlPolygonColors.Value = GetAttributeValue( "PolygonColors" ); ceMapInfo.Text = GetAttributeValue( "MapInfo" ); cbMapInfoDebug.Checked = GetAttributeValue( "MapInfoDebug" ).AsBoolean(); cbShowLavaOutput.Checked = GetAttributeValue( "ShowLavaOutput" ).AsBoolean(); ceLavaOutput.Text = GetAttributeValue( "LavaOutput" ); cbLavaOutputDebug.Checked = GetAttributeValue( "LavaOutputDebug" ).AsBoolean(); cbShowGrid.Checked = GetAttributeValue( "ShowGrid" ).AsBoolean(); cbShowSchedule.Checked = GetAttributeValue( "ShowSchedule" ).AsBoolean(); cbShowDescription.Checked = GetAttributeValue( "ShowDescription" ).AsBoolean(); cbProximity.Checked = GetAttributeValue( "ShowProximity" ).AsBoolean(); cbSortByDistance.Checked = GetAttributeValue( "SortByDistance" ).AsBoolean(); tbPageSizes.Text = GetAttributeValue( "PageSizes" ); cbShowCount.Checked = GetAttributeValue( "ShowCount" ).AsBoolean(); cbShowAge.Checked = GetAttributeValue( "ShowAge" ).AsBoolean(); foreach ( string attr in GetAttributeValue( "AttributeColumns" ).SplitDelimitedValues() ) { var li = cblGridAttributes.Items.FindByValue( attr ); if ( li != null ) { li.Selected = true; } } var ppFieldType = new PageReferenceFieldType(); ppFieldType.SetEditValue( ppGroupDetailPage, null, GetAttributeValue( "GroupDetailPage" ) ); ppFieldType.SetEditValue( ppRegisterPage, null, GetAttributeValue( "RegisterPage" ) ); upnlContent.Update(); }
/// <summary> /// Binds the attendees grid. /// </summary> private void BindAttendeesGrid() { var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.End == null || dateRange.End > RockDateTime.Now ) { dateRange.End = RockDateTime.Now; } var rockContext = new RockContext(); // make a qryPersonAlias so that the generated SQL will be a "WHERE .. IN ()" instead of an OUTER JOIN (which is incredibly slow for this) var qryPersonAlias = new PersonAliasService( rockContext ).Queryable(); var qryAttendance = new AttendanceService( rockContext ).Queryable(); qryAttendance = qryAttendance.Where( a => a.DidAttend.HasValue && a.DidAttend.Value ); var groupType = this.GetSelectedTemplateGroupType(); var qryAllVisits = qryAttendance; if ( groupType != null ) { var childGroupTypeIds = new GroupTypeService( rockContext ).GetChildGroupTypes( groupType.Id ).Select( a => a.Id ); qryAllVisits = qryAttendance.Where( a => childGroupTypeIds.Any( b => b == a.Group.GroupTypeId ) ); } else { return; } var groupIdList = new List<int>(); string groupIds = GetSelectedGroupIds().AsDelimited( "," ); if ( !string.IsNullOrWhiteSpace( groupIds ) ) { groupIdList = groupIds.Split( ',' ).AsIntegerList(); qryAttendance = qryAttendance.Where( a => a.GroupId.HasValue && groupIdList.Contains( a.GroupId.Value ) ); } //// If campuses were included, filter attendances by those that have selected campuses //// if 'null' is one of the campuses, treat that as a 'CampusId is Null' var includeNullCampus = clbCampuses.SelectedValues.Any( a => a.Equals( "null", StringComparison.OrdinalIgnoreCase ) ); var campusIdList = clbCampuses.SelectedValues.AsIntegerList(); // remove 0 from the list, just in case it is there campusIdList.Remove( 0 ); if ( campusIdList.Any() ) { if ( includeNullCampus ) { // show records that have a campusId in the campusIdsList + records that have a null campusId qryAttendance = qryAttendance.Where( a => ( a.CampusId.HasValue && campusIdList.Contains( a.CampusId.Value ) ) || !a.CampusId.HasValue ); } else { // only show records that have a campusId in the campusIdList qryAttendance = qryAttendance.Where( a => a.CampusId.HasValue && campusIdList.Contains( a.CampusId.Value ) ); } } else if ( includeNullCampus ) { // 'null' was the only campusId in the campusIds parameter, so only show records that have a null CampusId qryAttendance = qryAttendance.Where( a => !a.CampusId.HasValue ); } // have the "Missed" query be the same as the qry before the Main date range is applied since it'll have a different date range var qryMissed = qryAttendance; if ( dateRange.Start.HasValue ) { qryAttendance = qryAttendance.Where( a => a.StartDateTime >= dateRange.Start.Value ); } if ( dateRange.End.HasValue ) { qryAttendance = qryAttendance.Where( a => a.StartDateTime < dateRange.End.Value ); } // we want to get the first 2 visits at a minimum so we can show the date in the grid int nthVisitsTake = 2; int? byNthVisit = null; if ( radByVisit.Checked ) { // If we are filtering by nth visit, we might want to get up to first 5 byNthVisit = ddlNthVisit.SelectedValue.AsIntegerOrNull(); if ( byNthVisit.HasValue && byNthVisit > 2 ) { nthVisitsTake = byNthVisit.Value; } } ChartGroupBy groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week; IQueryable<PersonWithSummary> qryByPersonWithSummary = null; if ( byNthVisit.HasValue && byNthVisit.Value == 0 ) { // Show members of the selected groups that did not attend at all during selected date range // Get all the person ids that did attend var attendeePersonIds = qryAttendance.Select( a => a.PersonAlias.PersonId ); // Get all the active members of the selected groups who have no attendance within selected date range and campus qryByPersonWithSummary = new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => groupIdList.Contains( m.GroupId ) && !attendeePersonIds.Contains( m.PersonId ) && m.GroupMemberStatus == GroupMemberStatus.Active ) .Select( m => new PersonWithSummary { PersonId = m.PersonId, FirstVisits = new DateTime[] { }.AsQueryable(), LastVisit = new AttendancePersonAlias(), AttendanceSummary = new DateTime[] { }.AsQueryable() } ); } else { var qryAttendanceWithSummaryDateTime = qryAttendance.GetAttendanceWithSummaryDateTime( groupBy ); var qryGroup = new GroupService( rockContext ).Queryable(); var qryJoinPerson = qryAttendance.Join( qryPersonAlias, k1 => k1.PersonAliasId, k2 => k2.Id, ( a, pa ) => new { CampusId = a.CampusId, GroupId = a.GroupId, ScheduleId = a.ScheduleId, StartDateTime = a.StartDateTime, PersonAliasId = pa.Id, PersonAliasPersonId = pa.PersonId } ); var qryJoinFinal = qryJoinPerson.Join( qryGroup, k1 => k1.GroupId, k2 => k2.Id, ( a, g ) => new AttendancePersonAlias { CampusId = a.CampusId, GroupId = a.GroupId, GroupName = g.Name, ScheduleId = a.ScheduleId, StartDateTime = a.StartDateTime, PersonAliasId = a.PersonAliasId, PersonAliasPersonId = a.PersonAliasPersonId } ); var qryByPerson = qryJoinFinal.GroupBy( a => a.PersonAliasPersonId ).Select( a => new { PersonId = a.Key, Attendances = a } ); int? attendedMinCount = null; int? attendedMissedCount = null; DateRange attendedMissedDateRange = new DateRange(); if ( radByPattern.Checked ) { attendedMinCount = tbPatternXTimes.Text.AsIntegerOrNull(); if ( cbPatternAndMissed.Checked ) { attendedMissedCount = tbPatternMissedXTimes.Text.AsIntegerOrNull(); attendedMissedDateRange = new DateRange( drpPatternDateRange.LowerValue, drpPatternDateRange.UpperValue ); if ( !attendedMissedDateRange.Start.HasValue || !attendedMissedDateRange.End.HasValue ) { nbMissedDateRangeRequired.Visible = true; return; } } } nbMissedDateRangeRequired.Visible = false; // get either the first 2 visits or the first 5 visits (using a const take of 2 or 5 vs a variable to help the SQL optimizer) qryByPersonWithSummary = qryByPerson.Select( a => new PersonWithSummary { PersonId = a.PersonId, FirstVisits = qryAllVisits.Where( b => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == b.PersonAliasId ) ).Select( s => s.StartDateTime ).OrderBy( x => x ).Take( 2 ), LastVisit = a.Attendances.OrderByDescending( x => x.StartDateTime ).FirstOrDefault(), AttendanceSummary = qryAttendanceWithSummaryDateTime.Where( x => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == x.Attendance.PersonAliasId ) ).GroupBy( g => g.SummaryDateTime ).Select( s => s.Key ) } ); if ( nthVisitsTake > 2 ) { qryByPersonWithSummary = qryByPerson.Select( a => new PersonWithSummary { PersonId = a.PersonId, FirstVisits = qryAllVisits.Where( b => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == b.PersonAliasId ) ).Select( s => s.StartDateTime ).OrderBy( x => x ).Take( 5 ), LastVisit = a.Attendances.OrderByDescending( x => x.StartDateTime ).FirstOrDefault(), AttendanceSummary = qryAttendanceWithSummaryDateTime.Where( x => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == x.Attendance.PersonAliasId ) ).GroupBy( g => g.SummaryDateTime ).Select( s => s.Key ) } ); } if ( byNthVisit.HasValue ) { // only return attendees where their nth visit is within the selected daterange int skipCount = byNthVisit.Value - 1; qryByPersonWithSummary = qryByPersonWithSummary.Where( a => a.FirstVisits.OrderBy( x => x ).Skip( skipCount ).Take( 1 ).Any( d => d >= dateRange.Start && d < dateRange.End ) ); } if ( attendedMinCount.HasValue ) { qryByPersonWithSummary = qryByPersonWithSummary.Where( a => a.AttendanceSummary.Count() >= attendedMinCount ); } if ( attendedMissedCount.HasValue ) { if ( attendedMissedDateRange.Start.HasValue && attendedMissedDateRange.End.HasValue ) { var attendedMissedPossible = GetPossibleAttendancesForDateRange( attendedMissedDateRange, groupBy ); int attendedMissedPossibleCount = attendedMissedPossible.Count(); qryMissed = qryMissed.Where( a => a.StartDateTime >= attendedMissedDateRange.Start.Value && a.StartDateTime < attendedMissedDateRange.End.Value ); var qryMissedAttendanceByPersonAndSummary = qryMissed.GetAttendanceWithSummaryDateTime( groupBy ) .GroupBy( g1 => new { g1.SummaryDateTime, g1.Attendance.PersonAlias.PersonId } ) .GroupBy( a => a.Key.PersonId ) .Select( a => new { PersonId = a.Key, AttendanceCount = a.Count() } ); var qryMissedByPerson = qryMissedAttendanceByPersonAndSummary .Where( x => ( attendedMissedPossibleCount - x.AttendanceCount ) >= attendedMissedCount ); // filter to only people that missed at least X weeks/months/years between specified missed date range qryByPersonWithSummary = qryByPersonWithSummary.Where( a => qryMissedByPerson.Any( b => b.PersonId == a.PersonId ) ); } } } var personService = new PersonService( rockContext ); // Filter by dataview var dataViewId = dvpDataView.SelectedValueAsInt(); if ( dataViewId.HasValue ) { var dataView = new DataViewService( _rockContext ).Get( dataViewId.Value ); if ( dataView != null ) { var errorMessages = new List<string>(); ParameterExpression paramExpression = personService.ParameterExpression; Expression whereExpression = dataView.GetExpression( personService, paramExpression, out errorMessages ); SortProperty sort = null; var dataViewPersonIdQry = personService .Queryable().AsNoTracking() .Where( paramExpression, whereExpression, sort ) .Select( p => p.Id ); qryByPersonWithSummary = qryByPersonWithSummary.Where( a => dataViewPersonIdQry.Contains( a.PersonId ) ); } } // declare the qryResult that we'll use in case they didn't choose IncludeParents or IncludeChildren (and the Anonymous Type will also work if we do include parents or children) var qryPerson = personService.Queryable(); var qryResult = qryByPersonWithSummary.Join( qryPerson, a => a.PersonId, p => p.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)null, ChildId = (int?)null, Person = p, Parent = (Person)null, Child = (Person)null, a.FirstVisits, a.LastVisit, p.PhoneNumbers, a.AttendanceSummary } ); var includeParents = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ParentsOfAttendees; var includeChildren = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ChildrenOfAttendees; // if Including Parents, join with qryChildWithParent instead of qryPerson if ( includeParents ) { var qryChildWithParent = new PersonService( rockContext ).GetChildWithParent(); qryResult = qryByPersonWithSummary.Join( qryChildWithParent, a => a.PersonId, p => p.Child.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)p.Parent.Id, ChildId = (int?)null, Person = p.Child, Parent = p.Parent, Child = (Person)null, a.FirstVisits, a.LastVisit, p.Parent.PhoneNumbers, a.AttendanceSummary } ); } if ( includeChildren ) { var qryParentWithChildren = new PersonService( rockContext ).GetParentWithChild(); qryResult = qryByPersonWithSummary.Join( qryParentWithChildren, a => a.PersonId, p => p.Parent.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)null, ChildId = (int?)p.Child.Id, Person = p.Parent, Parent = (Person)null, Child = p.Child, a.FirstVisits, a.LastVisit, p.Child.PhoneNumbers, a.AttendanceSummary } ); } var parentField = gAttendeesAttendance.Columns.OfType<PersonField>().FirstOrDefault( a => a.HeaderText == "Parent" ); if ( parentField != null ) { parentField.Visible = includeParents; } var parentEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent Email" ); if ( parentEmailField != null ) { parentEmailField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var childField = gAttendeesAttendance.Columns.OfType<PersonField>().FirstOrDefault( a => a.HeaderText == "Child" ); if ( childField != null ) { childField.Visible = includeChildren; } var childEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Email" ); if ( childEmailField != null ) { childEmailField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } SortProperty sortProperty = gAttendeesAttendance.SortProperty; if ( sortProperty != null ) { if ( sortProperty.Property == "AttendanceSummary.Count" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.AttendanceSummary.Count() ); } else { qryResult = qryResult.OrderBy( a => a.AttendanceSummary.Count() ); } } else if ( sortProperty.Property == "FirstVisit.StartDateTime" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.FirstVisits.Min() ); } else { qryResult = qryResult.OrderBy( a => a.FirstVisits.Min() ); } } else { qryResult = qryResult.Sort( sortProperty ); } } else { qryResult = qryResult.OrderBy( a => a.Person.LastName ).ThenBy( a => a.Person.NickName ); } var attendancePercentField = gAttendeesAttendance.Columns.OfType<RockTemplateField>().First( a => a.HeaderText.EndsWith( "Attendance %" ) ); attendancePercentField.HeaderText = string.Format( "{0}ly Attendance %", groupBy.ConvertToString() ); // Calculate all the possible attendance summary dates UpdatePossibleAttendances( dateRange, groupBy ); // pre-load the schedule names since FriendlyScheduleText requires building the ICal object, etc _scheduleNameLookup = new ScheduleService( rockContext ).Queryable() .ToList() .ToDictionary( k => k.Id, v => v.FriendlyScheduleText ); if ( includeParents ) { gAttendeesAttendance.PersonIdField = "ParentId"; gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" }; } else if ( includeChildren ) { gAttendeesAttendance.PersonIdField = "ChildId"; gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" }; } else { gAttendeesAttendance.PersonIdField = "PersonId"; gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" }; } // Create the dynamic attendance grid columns as needed CreateDynamicAttendanceGridColumns(); try { nbAttendeesError.Visible = false; // increase the timeout from 30 to 90. The Query can be slow if SQL hasn't calculated the Query Plan for the query yet. // Sometimes, most of the time consumption is figuring out the Query Plan, but after it figures it out, it caches it so that the next time it'll be much faster rockContext.Database.CommandTimeout = 90; gAttendeesAttendance.SetLinqDataSource( qryResult.AsNoTracking() ); gAttendeesAttendance.DataBind(); } catch ( Exception exception ) { LogAndShowException( exception ); } }
/// <summary> /// Builds the group types UI /// </summary> private void BuildGroupTypesUI() { var groupType = this.GetSelectedTemplateGroupType(); if ( groupType != null ) { nbGroupTypeWarning.Visible = false; var groupTypes = new GroupTypeService( _rockContext ).GetChildGroupTypes( groupType.Id ).OrderBy( a => a.Order ).ThenBy( a => a.Name ); // only add each group type once in case the group type is a child of multiple parents _addedGroupTypeIds = new List<int>(); rptGroupTypes.DataSource = groupTypes.ToList(); rptGroupTypes.DataBind(); } else { nbGroupTypeWarning.Text = "Please select a check-in type."; nbGroupTypeWarning.Visible = true; } }
/// <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 ) { GroupType groupType; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext ); CategoryService categoryService = new CategoryService( rockContext ); GroupScheduleExclusionService scheduleExclusionService = new GroupScheduleExclusionService( rockContext ); int groupTypeId = int.Parse( hfGroupTypeId.Value ); if ( groupTypeId == 0 ) { groupType = new GroupType(); groupTypeService.Add( groupType ); } else { groupType = groupTypeService.Get( groupTypeId ); // selected roles var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid ); foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() ) { groupType.Roles.Remove( role ); groupTypeRoleService.Delete( role ); } } foreach ( var roleState in GroupTypeRolesState ) { GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault(); if ( role == null ) { role = new GroupTypeRole(); groupType.Roles.Add( role ); } else { roleState.Id = role.Id; roleState.Guid = role.Guid; } role.CopyPropertiesFrom( roleState ); } ScheduleType allowedScheduleTypes = ScheduleType.None; foreach( ListItem li in cblScheduleTypes.Items ) { if ( li.Selected ) { allowedScheduleTypes = allowedScheduleTypes | (ScheduleType)li.Value.AsInteger(); } } GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None; foreach ( ListItem li in cblLocationSelectionModes.Items ) { if ( li.Selected ) { locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger(); } } groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.GroupTerm = tbGroupTerm.Text; groupType.GroupMemberTerm = tbGroupMemberTerm.Text; groupType.ShowInGroupList = cbShowInGroupList.Checked; groupType.ShowInNavigation = cbShowInNavigation.Checked; groupType.IconCssClass = tbIconCssClass.Text; groupType.TakesAttendance = cbTakesAttendance.Checked; groupType.SendAttendanceReminder = cbSendAttendanceReminder.Checked; groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>(); groupType.AttendancePrintTo = ddlPrintTo.SelectedValueAsEnum<PrintTo>(); groupType.AllowedScheduleTypes = allowedScheduleTypes; groupType.LocationSelectionMode = locationSelectionMode; groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt(); groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked; groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId; groupType.EnableLocationSchedules = cbEnableLocationSchedules.Checked; groupType.ChildGroupTypes = new List<GroupType>(); groupType.ChildGroupTypes.Clear(); foreach ( var item in ChildGroupTypesDictionary ) { var childGroupType = groupTypeService.Get( item.Key ); if ( childGroupType != null ) { groupType.ChildGroupTypes.Add( childGroupType ); } } // Delete any removed exclusions foreach ( var exclusion in groupType.GroupScheduleExclusions.Where( s => !ScheduleExclusionDictionary.Keys.Contains( s.Guid ) ).ToList() ) { groupType.GroupScheduleExclusions.Remove( exclusion ); scheduleExclusionService.Delete( exclusion ); } // Update exclusions foreach( var keyVal in ScheduleExclusionDictionary ) { var scheduleExclusion = groupType.GroupScheduleExclusions .FirstOrDefault( s => s.Guid.Equals( keyVal.Key)); if ( scheduleExclusion == null ) { scheduleExclusion = new GroupScheduleExclusion(); groupType.GroupScheduleExclusions.Add( scheduleExclusion); } scheduleExclusion.StartDate = keyVal.Value.Start; scheduleExclusion.EndDate = keyVal.Value.End; } DefinedValueService definedValueService = new DefinedValueService( rockContext ); groupType.LocationTypes = new List<GroupTypeLocationType>(); groupType.LocationTypes.Clear(); foreach ( var item in LocationTypesDictionary ) { var locationType = definedValueService.Get( item.Key ); if ( locationType != null ) { groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } ); } } if ( !groupType.IsValid ) { // Controls will render the error messages return; } // need WrapTransaction due to Attribute saves rockContext.WrapTransaction( () => { rockContext.SaveChanges(); /* Save Attributes */ string qualifierValue = groupType.Id.ToString(); SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, rockContext ); SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, rockContext ); SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, rockContext ); // Reload to save default role groupType = groupTypeService.Get( groupType.Id ); groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) ); if ( groupType.DefaultGroupRole == null ) { groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault(); } rockContext.SaveChanges(); // Reload the roles and apply their attribute values foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ).ToList() ) { role.LoadAttributes( rockContext ); var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault(); if ( roleState != null && roleState.AttributeValues != null ) { foreach ( var attributeValue in roleState.AttributeValues ) { role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) ); } role.SaveAttributeValues( rockContext ); } } } ); GroupTypeCache.Flush( groupType.Id ); NavigateToParentPage(); }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs /// </summary> /// <param name="pageReference">The page reference.</param> /// <returns></returns> public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference ) { var breadCrumbs = new List<BreadCrumb>(); int? groupTypeId = PageParameter( pageReference, "groupTypeId" ).AsIntegerOrNull(); if ( groupTypeId != null ) { GroupType groupType = new GroupTypeService( new RockContext() ).Get( groupTypeId.Value ); if ( groupType != null ) { breadCrumbs.Add( new BreadCrumb( groupType.Name, pageReference ) ); } else { breadCrumbs.Add( new BreadCrumb( "New Group Type", pageReference ) ); } } else { // don't show a breadcrumb if we don't have a pageparam to work with } return breadCrumbs; }
/// <summary> /// Binds the inherited attributes. /// </summary> /// <param name="inheritedGroupTypeId">The inherited group type identifier.</param> /// <param name="groupTypeService">The group type service.</param> /// <param name="attributeService">The attribute service.</param> private void BindInheritedAttributes( int? inheritedGroupTypeId, GroupTypeService groupTypeService, AttributeService attributeService ) { GroupTypeAttributesInheritedState = new List<InheritedAttribute>(); GroupAttributesInheritedState = new List<InheritedAttribute>(); GroupMemberAttributesInheritedState = new List<InheritedAttribute>(); while ( inheritedGroupTypeId.HasValue ) { var inheritedGroupType = groupTypeService.Get( inheritedGroupTypeId.Value ); if ( inheritedGroupType != null ) { string qualifierValue = inheritedGroupType.Id.ToString(); foreach ( var attribute in attributeService.GetByEntityTypeId( new GroupType().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "Id", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ) { GroupTypeAttributesInheritedState.Add( new InheritedAttribute( attribute.Name, attribute.Key, attribute.Description, Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ), inheritedGroupType.Name ) ); } foreach ( var attribute in attributeService.GetByEntityTypeId( new Group().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ) { GroupAttributesInheritedState.Add( new InheritedAttribute( attribute.Name, attribute.Key, attribute.Description, Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ), inheritedGroupType.Name ) ); } foreach ( var attribute in attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ) { GroupMemberAttributesInheritedState.Add( new InheritedAttribute( attribute.Name, attribute.Key, attribute.Description, Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ), inheritedGroupType.Name ) ); } inheritedGroupTypeId = inheritedGroupType.InheritedGroupTypeId; } else { inheritedGroupTypeId = null; } } BindGroupTypeAttributesInheritedGrid(); BindGroupAttributesInheritedGrid(); BindGroupMemberAttributesInheritedGrid(); }
/// <summary> /// Handles the SaveClick event of the mdAddCheckinGroupType 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 mdAddCheckinGroupType_SaveClick( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var groupTypeService = new GroupTypeService( rockContext ); GroupType groupType; if ( hfGroupTypeId.Value.AsInteger() == 0 ) { groupType = new GroupType(); groupTypeService.Add( groupType ); groupType.GroupTypePurposeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ).Id; groupType.ShowInNavigation = false; groupType.ShowInGroupList = false; } else { groupType = groupTypeService.Get( hfGroupTypeId.Value.AsInteger() ); } groupType.Name = tbGroupTypeName.Text; groupType.Description = tbGroupTypeDescription.Text; rockContext.SaveChanges(); } mdAddEditCheckinGroupType.Hide(); BindGrid(); }
/// <summary> /// Sets the selection. /// </summary> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection( System.Web.UI.Control[] controls, string selection ) { var groupType = new GroupTypeService( new RockContext() ).Get( selection.AsGuid()); ( controls[0] as GroupTypePicker ).SetValue( groupType != null ? groupType.Id : (int?)null ); }
/// <summary> /// Handles the SelectedIndexChanged event of the gtpInheritedGroupType 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 gtpInheritedGroupType_SelectedIndexChanged( object sender, EventArgs e ) { var rockContext = new RockContext(); var groupTypeService = new GroupTypeService( rockContext ); var attributeService = new AttributeService( rockContext ); BindInheritedAttributes( gtpInheritedGroupType.SelectedValueAsInt(), groupTypeService, attributeService ); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { using ( var rockContext = new RockContext() ) { GroupTypeService groupTypeService = new GroupTypeService( rockContext ); SortProperty sortProperty = gGroupType.SortProperty; var qry = groupTypeService.Queryable(); // limit to show only GroupTypes that have a group type purpose of Checkin Template int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ) ).Id; qry = qry.Where( a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId ); if ( sortProperty != null ) { gGroupType.DataSource = qry.Sort( sortProperty ).ToList(); } else { gGroupType.DataSource = qry.OrderBy( p => p.Name ).ToList(); } gGroupType.DataBind(); } }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="groupType">Type of the group.</param> private void ShowEditDetails( GroupType groupType ) { hlType.Visible = false; if ( groupType.Id == 0 ) { lReadOnlyTitle.Text = ActionTitle.Add( GroupType.FriendlyTypeName ).FormatAsHtmlTitle(); if ( groupType.GroupTypePurposeValue != null ) { hlType.Text = groupType.GroupTypePurposeValue.Value; hlType.Visible = true; } } else { lReadOnlyTitle.Text = groupType.Name.FormatAsHtmlTitle(); } SetEditMode( true ); var rockContext = new RockContext(); var groupTypeService = new GroupTypeService( rockContext ); var attributeService = new AttributeService( rockContext ); LoadDropDowns( groupType.Id ); // General tbName.ReadOnly = groupType.IsSystem; tbName.Text = groupType.Name; tbDescription.ReadOnly = groupType.IsSystem; tbDescription.Text = groupType.Description; tbGroupTerm.ReadOnly = groupType.IsSystem; tbGroupTerm.Text = groupType.GroupTerm; tbGroupMemberTerm.ReadOnly = groupType.IsSystem; tbGroupMemberTerm.Text = groupType.GroupMemberTerm; ddlGroupTypePurpose.Enabled = !groupType.IsSystem; ddlGroupTypePurpose.SetValue( groupType.GroupTypePurposeValueId ); ChildGroupTypesDictionary = new Dictionary<int, string>(); groupType.ChildGroupTypes.ToList().ForEach( a => ChildGroupTypesDictionary.Add( a.Id, a.Name ) ); BindChildGroupTypesGrid(); // Display cbShowInGroupList.Checked = groupType.ShowInGroupList; cbShowInNavigation.Checked = groupType.ShowInNavigation; tbIconCssClass.Text = groupType.IconCssClass; // Locations cbAllowMultipleLocations.Enabled = !groupType.IsSystem; cbAllowMultipleLocations.Checked = groupType.AllowMultipleLocations; cblScheduleTypes.Enabled = !groupType.IsSystem; foreach ( ListItem li in cblScheduleTypes.Items ) { ScheduleType scheduleType = (ScheduleType)li.Value.AsInteger(); li.Selected = ( groupType.AllowedScheduleTypes & scheduleType ) == scheduleType; } ScheduleExclusionDictionary = new Dictionary<Guid, DateRange>(); groupType.GroupScheduleExclusions.ToList().ForEach( s => ScheduleExclusionDictionary.Add( s.Guid, new DateRange( s.StartDate, s.EndDate ) ) ); BindScheduleExclusionsGrid(); cblLocationSelectionModes.Enabled = !groupType.IsSystem; foreach ( ListItem li in cblLocationSelectionModes.Items ) { GroupLocationPickerMode mode = (GroupLocationPickerMode)li.Value.AsInteger(); li.Selected = ( groupType.LocationSelectionMode & mode ) == mode; } LocationTypesDictionary = new Dictionary<int, string>(); groupType.LocationTypes.ToList().ForEach( a => LocationTypesDictionary.Add( a.LocationTypeValueId, a.LocationTypeValue.Value ) ); BindLocationTypesGrid(); // Support Location Schedules cbEnableLocationSchedules.Enabled = !groupType.IsSystem; cbEnableLocationSchedules.Checked = groupType.EnableLocationSchedules ?? false; // Check In cbTakesAttendance.Checked = groupType.TakesAttendance; cbSendAttendanceReminder.Checked = groupType.SendAttendanceReminder; ddlAttendanceRule.SetValue( (int)groupType.AttendanceRule ); ddlPrintTo.SetValue( (int)groupType.AttendancePrintTo ); // Attributes gtpInheritedGroupType.Enabled = !groupType.IsSystem; gtpInheritedGroupType.SelectedGroupTypeId = groupType.InheritedGroupTypeId; var groupTypeRoles = new List<GroupTypeRole>(); foreach ( var role in groupType.Roles ) { role.LoadAttributes(); groupTypeRoles.Add( role ); } GroupTypeRolesState = new ViewStateList<GroupTypeRole>(); GroupTypeRolesState.AddAll( groupTypeRoles ); BindGroupTypeRolesGrid(); string qualifierValue = groupType.Id.ToString(); GroupTypeAttributesState = new ViewStateList<Attribute>(); GroupTypeAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupType().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "Id", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ); BindGroupTypeAttributesGrid(); GroupAttributesState = new ViewStateList<Attribute>(); GroupAttributesState.AddAll( attributeService.GetByEntityTypeId( new Group().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ); BindGroupAttributesGrid(); GroupMemberAttributesState = new ViewStateList<Attribute>(); GroupMemberAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable() .Where( a => a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifierValue ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) .ToList() ); BindGroupMemberAttributesGrid(); BindInheritedAttributes( groupType.InheritedGroupTypeId, groupTypeService, attributeService ); }
/// <summary> /// Handles the RowSelected event of the gGroupType control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gGroupType_RowSelected( object sender, RowEventArgs e ) { using ( var rockContext = new RockContext() ) { var groupType = new GroupTypeService( rockContext ).Get( e.RowKeyId ); if ( groupType != null ) { hfGroupTypeId.Value = groupType.Id.ToString(); tbGroupTypeName.Text = groupType.Name; tbGroupTypeDescription.Text = groupType.Description; mdAddEditCheckinGroupType.Show(); } } }
/// <summary> /// Shows the edit. /// </summary> /// <param name="groupTypeId">The group type identifier.</param> public void ShowDetail( int groupTypeId ) { pnlDetails.Visible = false; GroupType groupType = null; if ( !groupTypeId.Equals( 0 ) ) { groupType = new GroupTypeService( new RockContext() ).Get( groupTypeId ); } if ( groupType == null ) { groupType = new GroupType { Id = 0, ShowInGroupList = true, GroupTerm = "Group", GroupMemberTerm = "Member" }; groupType.ChildGroupTypes = new List<GroupType>(); groupType.LocationTypes = new List<GroupTypeLocationType>(); Guid defaultRoleGuid = Guid.NewGuid(); var memberRole = new GroupTypeRole { Guid = defaultRoleGuid, Name = "Member" }; groupType.Roles.Add( memberRole ); groupType.DefaultGroupRole = memberRole; groupType.AllowedScheduleTypes = ScheduleType.None; groupType.LocationSelectionMode = GroupLocationPickerMode.None; } bool editAllowed = groupType.IsAuthorized( Authorization.EDIT, CurrentPerson ); DefaultRoleGuid = groupType.DefaultGroupRole != null ? groupType.DefaultGroupRole.Guid : Guid.Empty; pnlDetails.Visible = true; hfGroupTypeId.Value = groupType.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( GroupType.FriendlyTypeName ); } if ( groupType.IsSystem ) { nbEditModeMessage.Text = EditModeMessage.System( GroupType.FriendlyTypeName ); } if ( readOnly ) { ShowReadonlyDetails( groupType ); } else { ShowEditDetails( groupType ); } }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns( ConnectionOpportunity connectionOpportunity ) { cblCampus.Items.Clear(); cblCampus.DataSource = CampusCache.All(); cblCampus.DataBind(); cblCampus.SetValues( connectionOpportunity.ConnectionOpportunityCampuses.Select( c => c.CampusId ).ToList() ); // bind group types ddlGroupType.Items.Clear(); using ( var rockContext = new RockContext() ) { var groupTypeService = new Rock.Model.GroupTypeService( rockContext ); // get all group types that have at least one role var groupTypes = groupTypeService.Queryable().Where( a => a.Roles.Any() ).OrderBy( a => a.Name ).ToList(); foreach ( var g in groupTypes ) { ddlGroupType.Items.Add( new ListItem( g.Name, g.Id.ToString().ToUpper() ) ); } } ddlGroupType.SetValue( connectionOpportunity.GroupTypeId.ToString() ); LoadGroupRoles( ddlGroupType.SelectedValue.AsInteger() ); ddlGroupRole.SetValue( connectionOpportunity.GroupMemberRoleId.ToString() ); // bind group member status ddlGroupMemberStatus.BindToEnum<GroupMemberStatus>(); if ( !String.IsNullOrWhiteSpace( connectionOpportunity.GroupMemberStatus.ToString() ) ) { ddlGroupMemberStatus.SetValue( connectionOpportunity.GroupMemberStatus.ConvertToInt().ToString() ); } else { ddlGroupMemberStatus.SetValue( GroupMemberStatus.Pending.ConvertToInt().ToString() ); } }
/// <summary> /// Handles the Add event of the gChildGroupTypes 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 gChildGroupTypes_Add( object sender, EventArgs e ) { GroupTypeService groupTypeService = new GroupTypeService( new RockContext() ); int currentGroupTypeId = int.Parse( hfGroupTypeId.Value ); // populate dropdown with all grouptypes that aren't already childgroups var qry = from gt in groupTypeService.Queryable() where !( from cgt in ChildGroupTypesDictionary.Keys select cgt ).Contains( gt.Id ) select gt; List<GroupType> list = qry.ToList(); if ( list.Count == 0 ) { modalAlert.Show( "There are not any other group types that can be added", ModalAlertType.Warning ); } else { ddlChildGroupType.DataSource = list; ddlChildGroupType.DataBind(); ShowDialog( "ChildGroupTypes" ); } }
/// <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 ) { ConnectionOpportunity connectionOpportunity = null; using ( RockContext rockContext = new RockContext() ) { int? groupTypeId = ddlGroupType.SelectedValueAsInt(); if ( groupTypeId.HasValue && GroupsState.Any( g => g.Group.GroupTypeId != groupTypeId.Value ) ) { var groupType = new GroupTypeService( rockContext ).Get( groupTypeId.Value ); if ( groupType != null ) { nbInvalidGroupTypes.Text = string.Format( "<p>One or more of the selected groups is not a <strong>{0}</strong> type. Please select groups that have a group type of <strong>{0}</strong>.", groupType.Name ); nbInvalidGroupTypes.Visible = true; return; } } ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext ); EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext ); ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext ); ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext ); ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext ); ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext ); int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt(); if ( connectionOpportunityId != 0 ) { connectionOpportunity = connectionOpportunityService .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" ) .Where( ei => ei.Id == connectionOpportunityId ) .FirstOrDefault(); } if ( connectionOpportunity == null ) { connectionOpportunity = new ConnectionOpportunity(); connectionOpportunity.Name = string.Empty; connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger(); connectionOpportunityService.Add( connectionOpportunity ); } connectionOpportunity.Name = tbName.Text; connectionOpportunity.Description = tbDescription.Text; connectionOpportunity.IsActive = cbIsActive.Checked; connectionOpportunity.PublicName = tbPublicName.Text; connectionOpportunity.IconCssClass = tbIconCssClass.Text; connectionOpportunity.GroupTypeId = ddlGroupType.SelectedValue.AsInteger(); connectionOpportunity.GroupMemberRoleId = ddlGroupRole.SelectedValue.AsInteger(); connectionOpportunity.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); int? orphanedPhotoId = null; if ( imgupPhoto.BinaryFileId != null ) { if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId ) { orphanedPhotoId = connectionOpportunity.PhotoId; } connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value; } // remove any workflows that removed in the UI var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid ); foreach ( var connectionOpportunityWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() ) { connectionOpportunity.ConnectionWorkflows.Remove( connectionOpportunityWorkflow ); connectionWorkflowService.Delete( connectionOpportunityWorkflow ); } // Add or Update workflows from the UI foreach ( ConnectionWorkflow connectionOpportunityWorkflowState in WorkflowsState.Where( w => w.ConnectionTypeId == null ) ) { ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == connectionOpportunityWorkflowState.Guid ).FirstOrDefault(); if ( connectionOpportunityWorkflow == null ) { connectionOpportunityWorkflow = new ConnectionWorkflow(); connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow ); } connectionOpportunityWorkflow.CopyPropertiesFrom( connectionOpportunityWorkflowState ); connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id; } // remove any group campuses that removed in the UI var uiGroupCampuses = GroupCampusesState.Select( l => l.Guid ); foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiGroupCampuses.Contains( l.Guid ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups ); connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups ); } // Add or Update group campuses from the UI foreach ( var connectionOpportunityConnectorGroupsState in GroupCampusesState ) { ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroups = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == connectionOpportunityConnectorGroupsState.Guid ).FirstOrDefault(); if ( connectionOpportunityConnectorGroups == null ) { connectionOpportunityConnectorGroups = new ConnectionOpportunityConnectorGroup(); connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroups ); } connectionOpportunityConnectorGroups.CopyPropertiesFrom( connectionOpportunityConnectorGroupsState ); } // remove any campuses that removed in the UI var uiCampuses = cblCampus.SelectedValuesAsInt; foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus ); connectionOpportunityCampusService.Delete( connectionOpportunityCampus ); } // Add or Update campuses from the UI foreach ( var campusId in uiCampuses ) { ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault(); if ( connectionOpportunityCampus == null ) { connectionOpportunityCampus = new ConnectionOpportunityCampus(); connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus ); } connectionOpportunityCampus.CampusId = campusId; } // Remove any groups that were removed in the UI var uiGroups = GroupsState.Select( r => r.Guid ); foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup ); connectionOpportunityGroupService.Delete( connectionOpportunityGroup ); } // Add or Update groups from the UI foreach ( var connectionOpportunityGroupState in GroupsState ) { ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == connectionOpportunityGroupState.Guid ).FirstOrDefault(); if ( connectionOpportunityGroup == null ) { connectionOpportunityGroup = new ConnectionOpportunityGroup(); connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup ); } connectionOpportunityGroup.CopyPropertiesFrom( connectionOpportunityGroupState ); } connectionOpportunity.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity ); if ( !Page.IsValid ) { return; } if ( !connectionOpportunity.IsValid ) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction( () => { rockContext.SaveChanges(); connectionOpportunity.SaveAttributeValues( rockContext ); if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } ); var qryParams = new Dictionary<string, string>(); qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" ); NavigateToParentPage( qryParams ); } }
/// <summary> /// Loads the drop downs. /// </summary> public void LoadDropDowns() { clbCampuses.Items.Clear(); var noCampusListItem = new ListItem(); noCampusListItem.Text = "<span title='Include records that are not associated with a campus'>No Campus</span>"; noCampusListItem.Value = "null"; clbCampuses.Items.Add( noCampusListItem ); foreach (var campus in CampusCache.All().OrderBy(a => a.Name)) { var listItem = new ListItem(); listItem.Text = campus.Name; listItem.Value = campus.Id.ToString(); clbCampuses.Items.Add( listItem ); } var groupTypeTemplateGuid = this.GetAttributeValue( "GroupTypeTemplate" ).AsGuidOrNull(); if ( !groupTypeTemplateGuid.HasValue ) { // show the CheckinType(GroupTypeTemplate) control if there isn't a block setting for it ddlAttendanceType.Visible = true; var groupTypeService = new GroupTypeService( _rockContext ); Guid groupTypePurposeGuid = Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid(); ddlAttendanceType.GroupTypes = groupTypeService.Queryable() .Where( a => a.GroupTypePurposeValue.Guid == groupTypePurposeGuid ) .OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList(); } else { // hide the CheckinType(GroupTypeTemplate) control if there is a block setting for it ddlAttendanceType.Visible = false; } }
/// <summary> /// Handles the SaveClick event of the dlgGroupDetails 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 dlgGroupDetails_SaveClick( object sender, EventArgs e ) { int? groupId = gpOpportunityGroup.SelectedValueAsInt(); if ( groupId.HasValue ) { var rockContext = new RockContext(); var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group != null ) { int? groupTypeId = ddlGroupType.SelectedValueAsInt(); if( groupTypeId.HasValue && group.GroupTypeId != groupTypeId.Value ) { var groupType = new GroupTypeService( rockContext ).Get( groupTypeId.Value ); if ( groupType != null ) { nbInvalidGroupType.Text = string.Format( "<p>The selected group is not a <strong>{0}</strong> type. Please select a group that has a group type of <strong>{0}</strong>.", groupType.Name ); nbInvalidGroupType.Visible = true; return; } } ConnectionOpportunityGroup connectionOpportunityGroup = new ConnectionOpportunityGroup(); connectionOpportunityGroup.Group = group; connectionOpportunityGroup.GroupId = groupId.Value; // Controls will show warnings if ( !connectionOpportunityGroup.IsValid ) { return; } if ( GroupsState.Any( a => a.Guid.Equals( connectionOpportunityGroup.Guid ) ) ) { GroupsState.RemoveEntity( connectionOpportunityGroup.Guid ); } GroupsState.Add( connectionOpportunityGroup ); BindGroupGrid(); HideDialog(); } } }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService( rockContext ); var groupTypeService = new GroupTypeService( rockContext ); var groupService = new GroupService( rockContext ); IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable(); List<int> currentAndDescendantGroupTypeIds = new List<int>(); var currentGroupTypeIds = this.CurrentGroupTypeIds.ToList(); currentAndDescendantGroupTypeIds.AddRange( currentGroupTypeIds ); foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => currentGroupTypeIds.Contains( a.Id ) ) ) { foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) ) { currentAndDescendantGroupTypeIds.Add( childGroupType.Id ); currentAndDescendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() ); } } groupLocationQry = groupLocationQry.Where( a => currentAndDescendantGroupTypeIds.Contains( a.Group.GroupTypeId ) ); groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name ); List<int> currentDeviceLocationIdList = this.GetGroupTypesLocations( rockContext ).Select( a => a.Id ).Distinct().ToList(); var qryList = groupLocationQry .Where( a => currentDeviceLocationIdList.Contains( a.LocationId ) ) .Select( a => new { GroupLocationId = a.Id, a.Location, GroupId = a.GroupId, GroupName = a.Group.Name, ScheduleIdList = a.Schedules.Select( s => s.Id ), GroupTypeId = a.Group.GroupTypeId } ).ToList(); var locationService = new LocationService( rockContext ); // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add( "GroupLocationId" ); dataTable.Columns.Add( "GroupId" ); dataTable.Columns.Add( "GroupName" ); dataTable.Columns.Add( "GroupPath" ); dataTable.Columns.Add( "LocationName" ); dataTable.Columns.Add( "LocationPath" ); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { dataTable.Columns.Add( field.DataField, typeof( bool ) ); } var locationPaths = new Dictionary<int, string>(); foreach ( var row in qryList ) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = groupService.GroupAncestorPathName( row.GroupId ); dataRow["GroupPath"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault(); dataRow["LocationName"] = row.Location.Name; if ( row.Location.ParentLocationId.HasValue ) { int locationId = row.Location.ParentLocationId.Value; if ( !locationPaths.ContainsKey( locationId ) ) { var locationNames = new List<string>(); var parentLocation = locationService.Get( locationId ); while ( parentLocation != null ) { locationNames.Add( parentLocation.Name ); parentLocation = parentLocation.ParentLocation; } if ( locationNames.Any() ) { locationNames.Reverse(); locationPaths.Add( locationId, locationNames.AsDelimited( " > " ) ); } else { locationPaths.Add( locationId, string.Empty ); } } dataRow["LocationPath"] = locationPaths[locationId]; } foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) ); dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId ); } dataTable.Rows.Add( dataRow ); } gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read<GroupLocation>().Id; gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Sets the selection. /// </summary> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection( System.Web.UI.Control[] controls, string selection ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 2 ) { var groupType = new GroupTypeService( new RockContext() ).Get( selectionValues[0].AsGuid()); ( controls[0] as GroupTypePicker ).SetValue( groupType != null ? groupType.Id : (int?)null ); groupTypePicker_SelectedIndexChanged( this, new EventArgs() ); string[] selectedRoleGuids = selectionValues[1].Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ); RockCheckBoxList cblRole = ( controls[1] as RockCheckBoxList ); foreach ( var item in cblRole.Items.OfType<ListItem>() ) { item.Selected = selectedRoleGuids.Contains( item.Value ); } } }
/// <summary> /// Builds the group types UI. /// </summary> private void BuildGroupTypesUI() { var rockContext = new RockContext(); var groupTypeService = new GroupTypeService( rockContext ); var groupTypeTemplateGuid = this.GetAttributeValue( "GroupTypeTemplate" ).AsGuidOrNull(); nbGroupTypeWarning.Visible = !groupTypeTemplateGuid.HasValue; if ( groupTypeTemplateGuid.HasValue ) { var groupType = groupTypeService.Get( groupTypeTemplateGuid.Value ); var groupTypes = groupTypeService.GetChildGroupTypes( groupType.Id ).OrderBy( a => a.Order ).ThenBy( a => a.Name ); rptGroupTypes.DataSource = groupTypes.ToList(); rptGroupTypes.DataBind(); } }
private void Map() { string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: 8px; }} </style>"; lMapStyling.Text = string.Format( mapStylingFormat, GetAttributeValue( "MapHeight" ) ); string settingGroupTypeId = GetAttributeValue( "GroupType" ); string queryStringGroupTypeId = PageParameter( "GroupTypeId" ); if ( ( string.IsNullOrWhiteSpace(settingGroupTypeId) && string.IsNullOrWhiteSpace(queryStringGroupTypeId) ) ) { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display as a block setting or pass a GroupTypeId as a query parameter.</div>"; } else { var rockContext = new RockContext(); pnlMap.Visible = true; int groupsMapped = 0; int groupsWithNoGeo = 0; StringBuilder sbGroupJson = new StringBuilder(); StringBuilder sbGroupsWithNoGeo = new StringBuilder(); Guid? groupType = null; int groupTypeId = -1; if ( !string.IsNullOrWhiteSpace( settingGroupTypeId ) ) { groupType = new Guid( settingGroupTypeId ); } else { if ( !string.IsNullOrWhiteSpace( queryStringGroupTypeId ) && Int32.TryParse( queryStringGroupTypeId, out groupTypeId ) ) { groupType = new GroupTypeService( rockContext ).Get( groupTypeId ).Guid; } } if ( groupType != null ) { Template template = null; if ( GetAttributeValue( "ShowMapInfoWindow" ).AsBoolean() ) { template = Template.Parse( GetAttributeValue( "InfoWindowContents" ).Trim() ); } else { template = Template.Parse( string.Empty ); } var groupPageRef = new PageReference( GetAttributeValue( "GroupDetailPage" ) ); // create group detail link for use in map's info window var personPageParams = new Dictionary<string, string>(); personPageParams.Add( "PersonId", string.Empty ); var personProfilePage = LinkedPageUrl( "PersonProfilePage", personPageParams ); var groupEntityType = EntityTypeCache.Read( typeof( Group ) ); var dynamicGroups = new List<dynamic>(); // Create query to get attribute values for selected attribute keys. var attributeKeys = GetAttributeValue( "Attributes" ).SplitDelimitedValues().ToList(); var attributeValues = new AttributeValueService( rockContext ).Queryable( "Attribute" ) .Where( v => v.Attribute.EntityTypeId == groupEntityType.Id && attributeKeys.Contains( v.Attribute.Key ) ); GroupService groupService = new GroupService( rockContext ); var groups = groupService.Queryable() .Where( g => g.GroupType.Guid == groupType ) .Select( g => new { Group = g, GroupId = g.Id, GroupName = g.Name, GroupGuid = g.Guid, GroupMemberTerm = g.GroupType.GroupMemberTerm, GroupCampus = g.Campus.Name, IsActive = g.IsActive, GroupLocation = g.GroupLocations .Where( l => l.Location.GeoPoint != null ) .Select( l => new { l.Location.Street1, l.Location.Street2, l.Location.City, l.Location.State, PostalCode = l.Location.PostalCode, Latitude = l.Location.GeoPoint.Latitude, Longitude = l.Location.GeoPoint.Longitude, Name = l.GroupLocationTypeValue.Value } ).FirstOrDefault(), GroupMembers = g.Members, AttributeValues = attributeValues .Where( v => v.EntityId == g.Id ) } ); if ( GetAttributeValue( "IncludeInactiveGroups" ).AsBoolean() == false ) { groups = groups.Where( g => g.IsActive == true ); } // Create dynamic object to include attribute values foreach ( var group in groups ) { dynamic dynGroup = new ExpandoObject(); dynGroup.GroupId = group.GroupId; dynGroup.GroupName = group.GroupName; // create group detail link for use in map's info window if ( groupPageRef.PageId > 0 ) { var groupPageParams = new Dictionary<string, string>(); groupPageParams.Add( "GroupId", group.GroupId.ToString() ); groupPageRef.Parameters = groupPageParams; dynGroup.GroupDetailPage = groupPageRef.BuildUrl(); } else { dynGroup.GroupDetailPage = string.Empty; } dynGroup.PersonProfilePage = personProfilePage; dynGroup.GroupMemberTerm = group.GroupMemberTerm; dynGroup.GroupCampus = group.GroupCampus; dynGroup.GroupLocation = group.GroupLocation; var groupAttributes = new List<dynamic>(); foreach ( AttributeValue value in group.AttributeValues ) { var attrCache = AttributeCache.Read( value.AttributeId ); var dictAttribute = new Dictionary<string, object>(); dictAttribute.Add( "Key", attrCache.Key ); dictAttribute.Add( "Name", attrCache.Name ); if ( attrCache != null ) { dictAttribute.Add( "Value", attrCache.FieldType.Field.FormatValueAsHtml( null, value.Value, attrCache.QualifierValues, false ) ); } else { dictAttribute.Add( "Value", value.Value ); } groupAttributes.Add( dictAttribute ); } dynGroup.Attributes = groupAttributes; var groupMembers = new List<dynamic>(); foreach ( GroupMember member in group.GroupMembers ) { var dictMember = new Dictionary<string, object>(); dictMember.Add( "Id", member.Person.Id ); dictMember.Add( "GuidP", member.Person.Guid ); dictMember.Add( "NickName", member.Person.NickName ); dictMember.Add( "LastName", member.Person.LastName ); dictMember.Add( "RoleName", member.GroupRole.Name ); dictMember.Add( "Email", member.Person.Email ); dictMember.Add( "PhotoGuid", member.Person.Photo != null ? member.Person.Photo.Guid : Guid.Empty ); var phoneTypes = new List<dynamic>(); foreach ( PhoneNumber p in member.Person.PhoneNumbers ) { var dictPhoneNumber = new Dictionary<string, object>(); dictPhoneNumber.Add( "Name", p.NumberTypeValue.Value ); dictPhoneNumber.Add( "Number", p.ToString() ); phoneTypes.Add( dictPhoneNumber ); } dictMember.Add( "PhoneTypes", phoneTypes ); groupMembers.Add( dictMember ); } dynGroup.GroupMembers = groupMembers; dynamicGroups.Add( dynGroup ); } // enable showing debug info if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) ) { lDebug.Visible = true; lDebug.Text = dynamicGroups.Take( 5 ).lavaDebugInfo(); } else { lDebug.Visible = false; lDebug.Text = string.Empty; } foreach ( var group in dynamicGroups ) { if ( group.GroupLocation != null && group.GroupLocation.Latitude != null ) { groupsMapped++; var groupDict = group as IDictionary<string, object>; string infoWindow = template.Render( Hash.FromDictionary( groupDict ) ).Replace( "\n", string.Empty ); sbGroupJson.Append( string.Format( @"{{ ""name"":""{0}"" , ""latitude"":""{1}"", ""longitude"":""{2}"", ""infowindow"":""{3}"" }},", HttpUtility.HtmlEncode( group.GroupName ), group.GroupLocation.Latitude, group.GroupLocation.Longitude, HttpUtility.HtmlEncode( infoWindow ) ) ); } else { groupsWithNoGeo++; if ( !string.IsNullOrWhiteSpace( group.GroupDetailPage ) ) { sbGroupsWithNoGeo.Append( string.Format( @"<li><a href='{0}'>{1}</a></li>", group.GroupDetailPage, group.GroupName ) ); } else { sbGroupsWithNoGeo.Append( string.Format( @"<li>{0}</li>", group.GroupName ) ); } } } string groupJson = sbGroupJson.ToString(); // remove last comma if ( groupJson.Length > 0 ) { groupJson = groupJson.Substring( 0, groupJson.Length - 1 ); } // add styling to map string styleCode = "null"; string markerColor = "FE7569"; DefinedValueCache dvcMapStyle = DefinedValueCache.Read( GetAttributeValue( "MapStyle" ).AsGuid() ); if ( dvcMapStyle != null ) { styleCode = dvcMapStyle.GetAttributeValue( "DynamicMapStyle" ); var colors = dvcMapStyle.GetAttributeValue( "Colors" ).Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ).ToList(); if ( colors.Any() ) { markerColor = colors.First().Replace( "#", "" ); } } // write script to page string mapScriptFormat = @" <script> Sys.Application.add_load(function () {{ var groupData = JSON.parse('{{ ""groups"" : [ {0} ]}}'); var showInfoWindow = {1}; var mapStyle = {2}; var pinColor = '{3}'; var pinImage = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + pinColor, new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34)); var pinShadow = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_shadow', new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35)); initializeMap(); function initializeMap() {{ console.log(mapStyle); var map; var bounds = new google.maps.LatLngBounds(); var mapOptions = {{ mapTypeId: 'roadmap', styles: mapStyle }}; // Display a map on the page map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); map.setTilt(45); // Display multiple markers on a map if (showInfoWindow) {{ var infoWindow = new google.maps.InfoWindow(), marker, i; }} // Loop through our array of markers & place each one on the map $.each(groupData.groups, function (i, group) {{ var position = new google.maps.LatLng(group.latitude, group.longitude); bounds.extend(position); marker = new google.maps.Marker({{ position: position, map: map, title: htmlDecode(group.name), icon: pinImage, shadow: pinShadow }}); // Allow each marker to have an info window if (showInfoWindow) {{ google.maps.event.addListener(marker, 'click', (function (marker, i) {{ return function () {{ infoWindow.setContent(htmlDecode(groupData.groups[i].infowindow)); infoWindow.open(map, marker); }} }})(marker, i)); }} map.fitBounds(bounds); }}); // Override our map zoom level once our fitBounds function runs (Make sure it only runs once) var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {{ google.maps.event.removeListener(boundsListener); }}); }} function htmlDecode(input) {{ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue; }} }}); </script>"; string mapScript = string.Format( mapScriptFormat, groupJson, GetAttributeValue( "ShowMapInfoWindow" ).AsBoolean().ToString().ToLower(), styleCode, markerColor ); ScriptManager.RegisterStartupScript( pnlMap, pnlMap.GetType(), "group-mapper-script", mapScript, false ); if ( groupsMapped == 0 ) { pnlMap.Visible = false; lMessages.Text = @" <p> <div class='alert alert-warning fade in'>No groups were able to be mapped. You may want to check your configuration.</div> </p>"; } else { // output any warnings if ( groupsWithNoGeo > 0 ) { string messagesFormat = @" <p> <div class='alert alert-warning fade in'>Some groups could not be mapped. <button type='button' class='close' data-dismiss='alert' aria-hidden='true'><i class='fa fa-times'></i></button> <small><a data-toggle='collapse' data-parent='#accordion' href='#map-error-details'>Show Details</a></small> <div id='map-error-details' class='collapse'> <p class='margin-t-sm'> <strong>Groups That Could Not Be Mapped</strong> <ul> {0} </ul> </p> </div> </div> </p>"; lMessages.Text = string.Format( messagesFormat, sbGroupsWithNoGeo.ToString() ); } } } else { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display and a location type to use.</div>"; } } }