/// <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; if ( !string.IsNullOrWhiteSpace( value ) ) { var names = new List<string>(); var guids = new List<Guid>(); foreach ( string guidValue in value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { Guid? guid = guidValue.AsGuidOrNull(); if ( guid.HasValue ) { guids.Add( guid.Value ); } } if ( guids.Any() ) { var schedules = new ScheduleService( new RockContext() ).Queryable().Where( a => guids.Contains( a.Guid ) ); if ( schedules.Any() ) { formattedValue = string.Join( ", ", ( from schedule in schedules select schedule.Name ).ToArray() ); } } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); var scheduleGuids = GetAttributeValue( "LiveSchedule" ); // Check to make sure that scheduleGuids is not null if ( scheduleGuids != null ) { var scheduleArray = scheduleGuids.Split( ',' ).AsGuidList(); var scheduleService = new ScheduleService( new RockContext() ); // Support for multiples schedules loops through each foreach ( var scheduleGuid in scheduleArray ) { var schedule = new ScheduleService( new RockContext() ).Get( scheduleGuid ); if ( schedule != null ) { var scheduleExpired = schedule.IsValid; bool scheduleActive = schedule.IsScheduleOrCheckInActive; // Check if Check in or Schedule is active and set the state accordingly if ( scheduleActive ) { // Active Schedule, set liveFeedStatus to on liveFeedStatus.Value = "on"; liveHeading.Text = BlockName; // Get the ip address String currentIp = GetLanIPAddress(); String internalIp = "204.116.47.244"; if ( currentIp == internalIp ) { localIP.Value = "true"; } else { localIP.Value = "false"; } break; } else { liveFeedStatus.Value = "off"; } } else { liveFeedStatus.Value = "off"; } } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail( string itemKey, int itemKeyValue, int? parentCategoryId ) { pnlDetails.Visible = false; if ( itemKey != "ScheduleId" ) { return; } var scheduleService = new ScheduleService( new RockContext() ); Schedule schedule = null; if ( !itemKeyValue.Equals( 0 ) ) { schedule = scheduleService.Get( itemKeyValue ); } else { schedule = new Schedule { Id = 0, CategoryId = parentCategoryId }; } if ( schedule == null ) { return; } pnlDetails.Visible = true; hfScheduleId.Value = schedule.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Schedule.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( schedule ); } else { btnEdit.Visible = true; string errorMessage = string.Empty; btnDelete.Visible = scheduleService.CanDelete( schedule, out errorMessage ); if ( schedule.Id > 0 ) { ShowReadonlyDetails( schedule ); } else { ShowEditDetails( schedule ); } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="scheduleId">The schedule identifier.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail( int scheduleId, int? parentCategoryId ) { pnlDetails.Visible = false; var scheduleService = new ScheduleService( new RockContext() ); Schedule schedule = null; if ( !scheduleId.Equals( 0 ) ) { schedule = scheduleService.Get( scheduleId ); pdAuditDetails.SetEntity( schedule, ResolveRockUrl( "~" ) ); } if ( schedule == null ) { schedule = new Schedule { Id = 0, CategoryId = parentCategoryId }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } pnlDetails.Visible = true; hfScheduleId.Value = schedule.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Schedule.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( schedule ); } else { btnEdit.Visible = true; string errorMessage = string.Empty; btnDelete.Visible = scheduleService.CanDelete( schedule, out errorMessage ); if ( schedule.Id > 0 ) { ShowReadonlyDetails( schedule ); } else { ShowEditDetails( schedule ); } } }
/// <summary> /// Adds the schedule columns. /// </summary> private void AddScheduleColumns() { ScheduleService scheduleService = new ScheduleService(); // limit Schedules to ones that have a CheckInStartOffsetMinutes var scheduleQry = scheduleService.Queryable().Where( a => a.CheckInStartOffsetMinutes != null ); // limit Schedules to the Category from the Filter int scheduleCategoryId = rFilter.GetUserPreference( "Category" ).AsInteger() ?? Rock.Constants.All.Id; if ( scheduleCategoryId != Rock.Constants.All.Id ) { scheduleQry = scheduleQry.Where( a => a.CategoryId == scheduleCategoryId ); } else { // NULL (or 0) means Shared, so specifically filter so to show only Schedules with CategoryId NULL scheduleQry = scheduleQry.Where( a => a.CategoryId == null ); } // clear out any existing schedule columns and add the ones that match the current filter setting var scheduleList = scheduleQry.ToList().OrderBy( a => a.ToString() ).ToList(); var checkBoxEditableFields = gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>().ToList(); foreach ( var field in checkBoxEditableFields ) { gGroupLocationSchedule.Columns.Remove( field ); } foreach ( var item in scheduleList ) { string dataFieldName = string.Format( "scheduleField_{0}", item.Id ); CheckBoxEditableField field = new CheckBoxEditableField { HeaderText = item.Name, DataField = dataFieldName }; gGroupLocationSchedule.Columns.Add( field ); } if ( !scheduleList.Any() ) { nbNotification.Text = nbNotification.Text = String.Format( "<p><strong>Warning</strong></p>No schedules found. Consider <a class='alert-link' href='{0}'>adding a schedule</a> or a different schedule category.", ResolveUrl( "~/Schedules" ) ); nbNotification.Visible = true; } else { nbNotification.Visible = false; } }
/// <summary> /// Handles the Delete event of the gSchedules 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 gSchedules_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); ScheduleService scheduleService = new ScheduleService( rockContext ); Schedule schedule = scheduleService.Get( e.RowKeyId ); if ( schedule != null ) { string errorMessage; if ( !scheduleService.CanDelete( schedule, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } scheduleService.Delete( schedule ); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGrid() { if ( _group != null ) { lHeading.Text = _group.Name; var qry = new ScheduleService( _rockContext ).GetGroupOccurrences( _group ).AsQueryable(); SortProperty sortProperty = gOccurrences.SortProperty; List<ScheduleOccurrence> occurrences = null; if ( sortProperty != null ) { occurrences = qry.Sort( sortProperty ).ToList(); } else { occurrences = qry.OrderByDescending( a => a.StartDateTime ).ToList(); } gOccurrences.DataSource = occurrences; gOccurrences.DataBind(); } }
/// <summary> /// Handles the RowDataBound event of the gGroupLocationSchedule control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param> protected void gGroupLocationSchedule_RowDataBound( object sender, GridViewRowEventArgs e ) { // add tooltip to header columns if ( e.Row.RowType == DataControlRowType.Header ) { var scheduleService = new ScheduleService( new RockContext() ); foreach ( var cell in e.Row.Cells.OfType<DataControlFieldCell>() ) { if ( cell.ContainingField is CheckBoxEditableField ) { CheckBoxEditableField checkBoxEditableField = cell.ContainingField as CheckBoxEditableField; int scheduleId = int.Parse( checkBoxEditableField.DataField.Replace( "scheduleField_", string.Empty ) ); var schedule = scheduleService.Get( scheduleId ); if ( schedule != null ) { cell.Attributes["title"] = schedule.ToString(); } } } } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { ScheduleService scheduleService = new ScheduleService( new RockContext() ); SortProperty sortProperty = gSchedules.SortProperty; var qry = scheduleService.Queryable().Select( a => new { a.Id, a.Name, CategoryName = a.Category.Name } ); if ( sortProperty != null ) { gSchedules.DataSource = qry.Sort( sortProperty ).ToList(); } else { gSchedules.DataSource = qry.OrderBy( s => s.Name ).ToList(); } gSchedules.EntityTypeId = EntityTypeCache.Read<Schedule>().Id; gSchedules.DataBind(); }
/// <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 ) { Metric metric; var rockContext = new RockContext(); MetricService metricService = new MetricService( rockContext ); MetricCategoryService metricCategoryService = new MetricCategoryService( rockContext ); MetricValueService metricValueService = new MetricValueService( rockContext ); MetricPartitionService metricPartitionService = new MetricPartitionService( rockContext ); int metricId = hfMetricId.Value.AsInteger(); if ( metricId == 0 ) { metric = new Metric(); } else { metric = metricService.Get( metricId ); // remove any metricPartitions that were removed in the UI var selectedMetricPartitionGuids = MetricPartitionsState.Select( r => r.Guid ); foreach ( var item in metric.MetricPartitions.Where( r => !selectedMetricPartitionGuids.Contains( r.Guid ) ).ToList() ) { metric.MetricPartitions.Remove( item ); metricPartitionService.Delete( item ); } } metric.MetricPartitions = metric.MetricPartitions ?? new List<MetricPartition>(); if ( MetricPartitionsState.Count() > 1 && MetricPartitionsState.Any(a => !a.EntityTypeId.HasValue )) { mdMetricPartitionsEntityTypeWarning.Text = "If multiple partitions are defined for a metric, all the partitions must have an EntityType assigned"; mdMetricPartitionsEntityTypeWarning.Visible = true; pwMetricPartitions.Expanded = true; return; } mdMetricPartitionsEntityTypeWarning.Visible = false; foreach ( var metricPartitionState in MetricPartitionsState ) { MetricPartition metricPartition = metric.MetricPartitions.Where( r => r.Guid == metricPartitionState.Guid ).FirstOrDefault(); if ( metricPartition == null ) { metricPartition = new MetricPartition(); metric.MetricPartitions.Add( metricPartition ); } else { metricPartitionState.Id = metricPartition.Id; metricPartitionState.Guid = metricPartition.Guid; } metricPartition.CopyPropertiesFrom( metricPartitionState ); } // ensure there is at least one partition if ( !metric.MetricPartitions.Any() ) { var metricPartition = new MetricPartition(); metricPartition.EntityTypeId = null; metricPartition.IsRequired = true; metricPartition.Order = 0; metric.MetricPartitions.Add( metricPartition ); } metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.IconCssClass = tbIconCssClass.Text; metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId(); metric.YAxisLabel = tbYAxisLabel.Text; metric.IsCumulative = cbIsCumulative.Checked; int sourceTypeDataView = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid() ).Id; int sourceTypeSQL = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid() ).Id; var personService = new PersonService( rockContext ); var metricChampionPerson = personService.Get( ppMetricChampionPerson.SelectedValue ?? 0 ); metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null; var adminPerson = personService.Get( ppAdminPerson.SelectedValue ?? 0 ); metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null; if ( metric.SourceValueTypeId == sourceTypeSQL ) { metric.SourceSql = ceSourceSql.Text; } else { metric.SourceSql = string.Empty; } if ( metric.SourceValueTypeId == sourceTypeDataView ) { metric.DataViewId = ddlDataView.SelectedValueAsId(); } else { metric.DataViewId = null; } var scheduleSelectionType = rblScheduleSelect.SelectedValueAsEnum<ScheduleSelectionType>(); if ( scheduleSelectionType == ScheduleSelectionType.NamedSchedule ) { metric.ScheduleId = ddlSchedule.SelectedValueAsId(); } else { metric.ScheduleId = hfUniqueScheduleId.ValueAsInt(); } if ( !Page.IsValid ) { return; } if ( !metric.IsValid ) { // Controls will render the error messages return; } if ( !cpMetricCategories.SelectedValuesAsInt().Any() ) { cpMetricCategories.ShowErrorMessage( "Must select at least one category" ); return; } // do a WrapTransaction since we are doing multiple SaveChanges() rockContext.WrapTransaction( () => { var scheduleService = new ScheduleService( rockContext ); var schedule = scheduleService.Get( metric.ScheduleId ?? 0 ); int metricScheduleCategoryId = new CategoryService( rockContext ).Get( Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid() ).Id; if ( schedule == null ) { schedule = new Schedule(); // make it an "Unnamed" metrics schedule schedule.Name = string.Empty; schedule.CategoryId = metricScheduleCategoryId; } // if the schedule was a unique schedule (configured in the Metric UI, set the schedule's ical content to the schedule builder UI's value if ( scheduleSelectionType == ScheduleSelectionType.Unique ) { schedule.iCalendarContent = sbSchedule.iCalendarContent; } if ( !schedule.HasSchedule() && scheduleSelectionType == ScheduleSelectionType.Unique ) { // don't save as a unique schedule if the schedule doesn't do anything schedule = null; } else { if ( schedule.Id == 0 ) { scheduleService.Add( schedule ); // save to make sure we have a scheduleId rockContext.SaveChanges(); } } if ( schedule != null ) { metric.ScheduleId = schedule.Id; } else { metric.ScheduleId = null; } if ( metric.Id == 0 ) { metricService.Add( metric ); // save to make sure we have a metricId rockContext.SaveChanges(); } // update MetricCategories for Metric metric.MetricCategories = metric.MetricCategories ?? new List<MetricCategory>(); var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt(); // delete any categories that were removed foreach ( var metricCategory in metric.MetricCategories.ToList() ) { if ( !selectedCategoryIds.Contains( metricCategory.CategoryId ) ) { metricCategoryService.Delete( metricCategory ); } } // add any categories that were added foreach ( int categoryId in selectedCategoryIds ) { if ( !metric.MetricCategories.Any( a => a.CategoryId == categoryId ) ) { metricCategoryService.Add( new MetricCategory { CategoryId = categoryId, MetricId = metric.Id } ); } } rockContext.SaveChanges(); // delete any orphaned Unnamed metric schedules var metricIdSchedulesQry = metricService.Queryable().Select( a => a.ScheduleId ); int? metricScheduleId = schedule != null ? schedule.Id : (int?)null; var orphanedSchedules = scheduleService.Queryable() .Where( a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != ( metricScheduleId ?? 0 ) ) .Where( s => !metricIdSchedulesQry.Any( m => m == s.Id ) ); foreach ( var item in orphanedSchedules ) { scheduleService.Delete( item ); } if ( orphanedSchedules.Any() ) { rockContext.SaveChanges(); } } ); var qryParams = new Dictionary<string, string>(); qryParams["MetricId"] = metric.Id.ToString(); if ( hfMetricCategoryId.ValueAsInt() == 0 ) { int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull(); int? metricCategoryId = new MetricCategoryService( new RockContext() ).Queryable().Where( a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId ).Select( a => a.Id ).FirstOrDefault(); hfMetricCategoryId.Value = metricCategoryId.ToString(); } qryParams["MetricCategoryId"] = hfMetricCategoryId.Value; qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e ) { int? categoryId = null; var rockContext = new RockContext(); var service = new ScheduleService( rockContext ); var item = service.Get( int.Parse( hfScheduleId.Value ) ); if ( item != null ) { string errorMessage; if ( !service.CanDelete( item, out errorMessage ) ) { ShowReadonlyDetails( item ); mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); } else { categoryId = item.CategoryId; service.Delete( item ); rockContext.SaveChanges(); // reload page, selecting the deleted data view's parent var qryParams = new Dictionary<string, string>(); if ( categoryId != null ) { qryParams["CategoryId"] = categoryId.ToString(); } NavigateToPage( RockPage.Guid, qryParams ); } } }
/// <summary> /// Binds the group members grid. /// </summary> protected void ShowDetails() { bool existingOccurrence = _occurrence != null; if ( !existingOccurrence && !_allowAdd ) { nbNotice.Heading = "No Occurrences"; nbNotice.Text = "<p>There are currently not any active occurrences for selected group to take attendance for.</p>"; nbNotice.NotificationBoxType = NotificationBoxType.Warning; nbNotice.Visible = true; pnlDetails.Visible = false; } else { if ( existingOccurrence ) { lOccurrenceDate.Visible = _occurrence.ScheduleId.HasValue; lOccurrenceDate.Text = _occurrence.Date.ToShortDateString(); dpOccurrenceDate.Visible = !_occurrence.ScheduleId.HasValue; dpOccurrenceDate.SelectedDate = _occurrence.Date; if ( _occurrence.LocationId.HasValue ) { lLocation.Visible = true; lLocation.Text = new LocationService( _rockContext ).GetPath( _occurrence.LocationId.Value ); } else { lLocation.Visible = false; } ddlLocation.Visible = false; lSchedule.Visible = !string.IsNullOrWhiteSpace( _occurrence.ScheduleName ); lSchedule.Text = _occurrence.ScheduleName; ddlSchedule.Visible = false; } else { lOccurrenceDate.Visible = false; dpOccurrenceDate.Visible = true; dpOccurrenceDate.SelectedDate = RockDateTime.Today; int? locationId = PageParameter( "LocationId" ).AsIntegerOrNull(); if ( locationId.HasValue ) { lLocation.Visible = true; lLocation.Text = new LocationService( _rockContext ).GetPath( locationId.Value ); ddlLocation.Visible = false; Schedule schedule = null; int? scheduleId = PageParameter( "ScheduleId" ).AsIntegerOrNull(); if ( scheduleId.HasValue ) { schedule = new ScheduleService( _rockContext ).Get( scheduleId.Value ); } if ( schedule != null ) { lSchedule.Visible = true; lSchedule.Text = schedule.Name; ddlSchedule.Visible = false; } else { BindSchedules( locationId.Value ); lSchedule.Visible = false; ddlSchedule.Visible = ddlSchedule.Items.Count > 1; } } else { lLocation.Visible = false; ddlLocation.Visible = ddlLocation.Items.Count > 1; lSchedule.Visible = false; ddlSchedule.Visible = ddlSchedule.Items.Count > 1; } } lMembers.Text = _group.GroupType.GroupMemberTerm.Pluralize(); lPendingMembers.Text = "Pending " + lMembers.Text; List<int> attendedIds = new List<int>(); // Load the attendance for the selected occurrence if ( existingOccurrence ) { cbDidNotMeet.Checked = _occurrence.DidNotOccur; // Get the list of people who attended attendedIds = new ScheduleService( _rockContext ).GetAttendance( _group, _occurrence ) .Where( a => a.DidAttend.HasValue && a.DidAttend.Value ) .Select( a => a.PersonAlias.PersonId ) .Distinct() .ToList(); } ppAddPerson.Visible = GetAttributeValue( "AllowAddingPerson" ).AsBoolean(); // Get the group members var groupMemberService = new GroupMemberService( _rockContext ); // Add any existing active members not on that list var unattendedIds = groupMemberService .Queryable().AsNoTracking() .Where( m => m.GroupId == _group.Id && m.GroupMemberStatus == GroupMemberStatus.Active && !attendedIds.Contains( m.PersonId ) ) .Select( m => m.PersonId ) .ToList(); string template = GetAttributeValue( "LavaTemplate" ); var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null ); // Bind the attendance roster _attendees = new PersonService( _rockContext ) .Queryable().AsNoTracking() .Where( p => attendedIds.Contains( p.Id ) || unattendedIds.Contains( p.Id ) ) .ToList() .Select( p => new GroupAttendanceAttendee() { PersonId = p.Id, NickName = p.NickName, LastName = p.LastName, Attended = attendedIds.Contains( p.Id ), CampusIds = p.GetCampusIds(), MergedTemplate = template.ResolveMergeFields( mergeFields.Union( new Dictionary<string, object>() { { "Person", p } } ).ToDictionary( x => x.Key, x => x.Value ) ) } ) .ToList(); BindAttendees(); // Bind the pending members var pendingMembers = groupMemberService .Queryable().AsNoTracking() .Where( m => m.GroupId == _group.Id && m.GroupMemberStatus == GroupMemberStatus.Pending ) .OrderBy( m => m.Person.LastName ) .ThenBy( m => m.Person.NickName ) .Select( m => new { Id = m.PersonId, FullName = m.Person.NickName + " " + m.Person.LastName } ) .ToList(); pnlPendingMembers.Visible = pendingMembers.Any(); lvPendingMembers.DataSource = pendingMembers; lvPendingMembers.DataBind(); } }
/// <summary> /// Rs the filter_ display filter value. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> /// <exception cref="System.NotImplementedException"></exception> protected void rFilter_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { var rockContext = new RockContext(); switch ( e.Key ) { case "Date Range": e.Value = DateRangePicker.FormatDelimitedValues( e.Value ); break; case "Person": int? personId = e.Value.AsIntegerOrNull(); e.Value = null; if ( personId.HasValue ) { var person = new PersonService( rockContext ).Get( personId.Value ); if ( person != null ) { e.Value = person.ToString(); } } break; case "Group": int? groupId = e.Value.AsIntegerOrNull(); e.Value = null; if ( groupId.HasValue ) { var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group != null ) { e.Value = group.ToString(); } } break; case "Schedule": int? scheduleId = e.Value.AsIntegerOrNull(); e.Value = null; if ( scheduleId.HasValue ) { var schedule = new ScheduleService( rockContext ).Get( scheduleId.Value ); if ( schedule != null ) { e.Value = schedule.Name; } } break; case "Attended": if ( e.Value == "1" ) { e.Value = "Did Attend"; } else if ( e.Value == "0" ) { e.Value = "Did Not Attend"; } else { e.Value = null; } break; default: e.Value = null; break; } }
/// <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 ) { using ( new UnitOfWorkScope() ) { GroupLocationService groupLocationService = new GroupLocationService(); ScheduleService scheduleService = new ScheduleService(); RockTransactionScope.WrapTransaction( () => { var gridViewRows = gGroupLocationSchedule.Rows; foreach ( GridViewRow row in gridViewRows.OfType<GridViewRow>() ) { int groupLocationId = int.Parse( gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string ); GroupLocation groupLocation = groupLocationService.Get( groupLocationId ); if ( groupLocation != null ) { foreach ( var fieldCell in row.Cells.OfType<DataControlFieldCell>() ) { CheckBoxEditableField checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField; if ( checkBoxTemplateField != null ) { CheckBox checkBox = fieldCell.Controls[0] as CheckBox; string dataField = ( fieldCell.ContainingField as CheckBoxEditableField ).DataField; int scheduleId = int.Parse( dataField.Replace( "scheduleField_", string.Empty ) ); // update GroupLocationSchedule depending on if the Schedule is Checked or not if ( checkBox.Checked ) { // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it if ( !groupLocation.Schedules.Any( a => a.Id == scheduleId ) ) { var schedule = scheduleService.Get( scheduleId ); groupLocation.Schedules.Add( schedule ); } } else { // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it if ( groupLocation.Schedules.Any( a => a.Id == scheduleId ) ) { groupLocation.Schedules.Remove( groupLocation.Schedules.FirstOrDefault( a => a.Id == scheduleId ) ); } } } } groupLocationService.Save( groupLocation, this.CurrentPersonId ); } } } ); } NavigateToParentPage(); }
/// <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 ) { Metric metric; var rockContext = new RockContext(); MetricService metricService = new MetricService( rockContext ); MetricCategoryService metricCategoryService = new MetricCategoryService( rockContext ); MetricValueService metricValueService = new MetricValueService( rockContext ); bool deleteValuesOnSave = sender == btnDeleteValuesAndSave; int metricId = hfMetricId.Value.AsInteger(); if ( metricId == 0 ) { metric = new Metric(); } else { metric = metricService.Get( metricId ); } metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.IconCssClass = tbIconCssClass.Text; metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId(); metric.XAxisLabel = tbXAxisLabel.Text; metric.YAxisLabel = tbYAxisLabel.Text; metric.IsCumulative = cbIsCumulative.Checked; var origEntityType = metric.EntityTypeId.HasValue ? EntityTypeCache.Read( metric.EntityTypeId.Value ) : null; var newEntityType = etpEntityType.SelectedEntityTypeId.HasValue ? EntityTypeCache.Read( etpEntityType.SelectedEntityTypeId.Value ) : null; if ( origEntityType != null && !deleteValuesOnSave ) { if ( newEntityType == null || newEntityType.Id != origEntityType.Id ) { // if the EntityTypeId of this metric has changed to NULL or to another EntityType, warn about the EntityId values being wrong bool hasEntityValues = metricValueService.Queryable().Any( a => a.MetricId == metric.Id && a.EntityId.HasValue ); if ( hasEntityValues ) { nbEntityTypeChanged.Text = string.Format( "Warning: You can't change the series partition to {0} when there are values associated with {1}. Do you want to delete existing values?", newEntityType != null ? newEntityType.FriendlyName : "<none>", origEntityType.FriendlyName ); mdEntityTypeChanged.Show(); nbEntityTypeChanged.Visible = true; return; } } } metric.EntityTypeId = etpEntityType.SelectedEntityTypeId; int sourceTypeDataView = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid() ).Id; int sourceTypeSQL = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid() ).Id; var personService = new PersonService( rockContext ); var metricChampionPerson = personService.Get( ppMetricChampionPerson.SelectedValue ?? 0 ); metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null; var adminPerson = personService.Get( ppAdminPerson.SelectedValue ?? 0 ); metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null; if ( metric.SourceValueTypeId == sourceTypeSQL ) { metric.SourceSql = ceSourceSql.Text; } else { metric.SourceSql = string.Empty; } if ( metric.SourceValueTypeId == sourceTypeDataView ) { metric.DataViewId = ddlDataView.SelectedValueAsId(); } else { metric.DataViewId = null; } var scheduleSelectionType = rblScheduleSelect.SelectedValueAsEnum<ScheduleSelectionType>(); if ( scheduleSelectionType == ScheduleSelectionType.NamedSchedule ) { metric.ScheduleId = ddlSchedule.SelectedValueAsId(); } else { metric.ScheduleId = hfUniqueScheduleId.ValueAsInt(); } if ( !Page.IsValid ) { return; } if ( !metric.IsValid ) { // Controls will render the error messages return; } if ( !cpMetricCategories.SelectedValuesAsInt().Any() ) { cpMetricCategories.ShowErrorMessage( "Must select at least one category" ); return; } // do a WrapTransaction since we are doing multiple SaveChanges() rockContext.WrapTransaction( () => { var scheduleService = new ScheduleService( rockContext ); var schedule = scheduleService.Get( metric.ScheduleId ?? 0 ); int metricScheduleCategoryId = new CategoryService( rockContext ).Get( Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid() ).Id; if ( schedule == null ) { schedule = new Schedule(); // make it an "Unnamed" metrics schedule schedule.Name = string.Empty; schedule.CategoryId = metricScheduleCategoryId; } // if the schedule was a unique schedule (configured in the Metric UI, set the schedule's ical content to the schedule builder UI's value if ( scheduleSelectionType == ScheduleSelectionType.Unique ) { schedule.iCalendarContent = sbSchedule.iCalendarContent; } if ( !schedule.HasSchedule() && scheduleSelectionType == ScheduleSelectionType.Unique ) { // don't save as a unique schedule if the schedule doesn't do anything schedule = null; } else { if ( schedule.Id == 0 ) { scheduleService.Add( schedule ); // save to make sure we have a scheduleId rockContext.SaveChanges(); } } if ( schedule != null ) { metric.ScheduleId = schedule.Id; } else { metric.ScheduleId = null; } if ( metric.Id == 0 ) { metricService.Add( metric ); // save to make sure we have a metricId rockContext.SaveChanges(); } // update MetricCategories for Metric metric.MetricCategories = metric.MetricCategories ?? new List<MetricCategory>(); var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt(); // delete any categories that were removed foreach ( var metricCategory in metric.MetricCategories.ToList() ) { if ( !selectedCategoryIds.Contains( metricCategory.CategoryId ) ) { metricCategoryService.Delete( metricCategory ); } } // add any categories that were added foreach ( int categoryId in selectedCategoryIds ) { if ( !metric.MetricCategories.Any( a => a.CategoryId == categoryId ) ) { metricCategoryService.Add( new MetricCategory { CategoryId = categoryId, MetricId = metric.Id } ); } } rockContext.SaveChanges(); // delete MetricValues associated with the old entityType if they confirmed the EntityType change if ( deleteValuesOnSave ) { metricValueService.DeleteRange( metricValueService.Queryable().Where( a => a.MetricId == metric.Id && a.EntityId.HasValue ) ); // since there could be 1000s of values that got deleted, do a SaveChanges that skips PrePostProcessing rockContext.SaveChanges( true ); } // delete any orphaned Unnamed metric schedules var metricIdSchedulesQry = metricService.Queryable().Select( a => a.ScheduleId ); int? metricScheduleId = schedule != null ? schedule.Id : (int?)null; var orphanedSchedules = scheduleService.Queryable() .Where( a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != ( metricScheduleId ?? 0 ) ) .Where( s => !metricIdSchedulesQry.Any( m => m == s.Id ) ); foreach ( var item in orphanedSchedules ) { scheduleService.Delete( item ); } if ( orphanedSchedules.Any() ) { rockContext.SaveChanges(); } } ); var qryParams = new Dictionary<string, string>(); qryParams["MetricId"] = metric.Id.ToString(); if ( hfMetricCategoryId.ValueAsInt() == 0 ) { int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull(); int? metricCategoryId = new MetricCategoryService( new RockContext() ).Queryable().Where( a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId ).Select( a => a.Id ).FirstOrDefault(); hfMetricCategoryId.Value = metricCategoryId.ToString(); } qryParams["MetricCategoryId"] = hfMetricCategoryId.Value; qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Grabs the necessary parameters from the XML and then calls the CreateAttendance() method /// to generate all the attendance data for the family. /// </summary> /// <param name="family">The family.</param> /// <param name="elemFamily">The elem family.</param> /// <param name="rockContext">The rock context.</param> /// <param name="attendanceData">The attendance data.</param> private void AddFamilyAttendance( Group family, XElement elemFamily, RockContext rockContext, Dictionary<Guid, List<Attendance>> attendanceData ) { // return from here if there's not startingAttendance date if ( elemFamily.Attribute( "startingAttendance" ) == null ) { return; } // get some variables we'll need to create the attendance records DateTime startingDate = DateTime.Parse( elemFamily.Attribute( "startingAttendance" ).Value.Trim(), new CultureInfo( "en-US" ) ); DateTime endDate = RockDateTime.Now; // If the XML specifies an endingAttendance date use it, otherwise use endingAttendanceWeeksAgo // to calculate the end date otherwise we'll just use the current date as the end date. if ( elemFamily.Attribute( "endingAttendance" ) != null ) { DateTime.TryParse( elemFamily.Attribute( "endingAttendance" ).Value.Trim(), out endDate ); } else if ( elemFamily.Attribute( "endingAttendanceWeeksAgo" ) != null ) { int endingWeeksAgo = 0; int.TryParse( elemFamily.Attribute( "endingAttendanceWeeksAgo" ).Value.Trim(), out endingWeeksAgo ); endDate = RockDateTime.Now.AddDays( -7 * endingWeeksAgo ); } int pctAttendance = 100; if ( elemFamily.Attribute( "percentAttendance" ) != null ) { int.TryParse( elemFamily.Attribute( "percentAttendance" ).Value.Trim(), out pctAttendance ); } int pctAttendedRegularService = 100; if ( elemFamily.Attribute( "percentAttendedRegularService" ) != null ) { int.TryParse( elemFamily.Attribute( "percentAttendedRegularService" ).Value.Trim(), out pctAttendedRegularService ); } int scheduleId = 13; if ( elemFamily.Attribute( "attendingScheduleId" ) != null ) { int.TryParse( elemFamily.Attribute( "attendingScheduleId" ).Value.Trim(), out scheduleId ); if ( !_scheduleTimes.ContainsKey( scheduleId ) ) { Schedule schedule = new ScheduleService( rockContext ).Get( scheduleId ); if ( schedule == null ) { // We're not going to continue if they are missing this schedule return; } _scheduleTimes.Add( scheduleId, schedule.GetCalenderEvent().DTStart.Value ); } } int altScheduleId = 4; if ( elemFamily.Attribute( "attendingAltScheduleId" ) != null ) { int.TryParse( elemFamily.Attribute( "attendingAltScheduleId" ).Value.Trim(), out altScheduleId ); if ( !_scheduleTimes.ContainsKey( altScheduleId ) ) { Schedule schedule = new ScheduleService( rockContext ).Get( altScheduleId ); if ( schedule == null ) { // We're not going to continue if they are missing this schedule return; } _scheduleTimes.Add( altScheduleId, schedule.GetCalenderEvent().DTStart.Value ); } } CreateAttendance( family.Members, startingDate, endDate, pctAttendance, pctAttendedRegularService, scheduleId, altScheduleId, attendanceData ); }
/// <summary> /// Handles adding groups from the given XML element snippet. /// </summary> /// <param name="elemGroups">The elem groups.</param> /// <param name="rockContext">The rock context.</param> /// <exception cref="System.NotSupportedException"></exception> private void AddGroups( XElement elemGroups, RockContext rockContext ) { // Add groups if ( elemGroups == null ) { return; } GroupService groupService = new GroupService( rockContext ); DefinedTypeCache smallGroupTopicType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC.AsGuid() ); // Next create the group along with its members. foreach ( var elemGroup in elemGroups.Elements( "group" ) ) { Guid guid = elemGroup.Attribute( "guid" ).Value.Trim().AsGuid(); string type = elemGroup.Attribute( "type" ).Value; Group group = new Group() { Guid = guid, Name = elemGroup.Attribute( "name" ).Value.Trim(), IsActive = true, IsPublic = true }; // skip any where there is no group type given -- they are invalid entries. if ( string.IsNullOrEmpty( elemGroup.Attribute( "type" ).Value.Trim() ) ) { return; } int? roleId; GroupTypeCache groupType; switch ( elemGroup.Attribute( "type" ).Value.Trim() ) { case "serving": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SERVING_TEAM.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; case "smallgroup": groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SMALL_GROUP.AsGuid() ); group.GroupTypeId = groupType.Id; roleId = groupType.DefaultGroupRoleId; break; default: throw new NotSupportedException( string.Format( "unknown group type {0}", elemGroup.Attribute( "type" ).Value.Trim() ) ); } if ( elemGroup.Attribute( "description" ) != null ) { group.Description = elemGroup.Attribute( "description" ).Value; } if ( elemGroup.Attribute( "parentGroupGuid" ) != null ) { var parentGroup = groupService.Get( elemGroup.Attribute( "parentGroupGuid" ).Value.AsGuid() ); if ( parentGroup != null ) { group.ParentGroupId = parentGroup.Id; } } // Set the group's meeting location if ( elemGroup.Attribute( "meetsAtHomeOfFamily" ) != null ) { int meetingLocationValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION.AsGuid() ).Id; var groupLocation = new GroupLocation() { IsMappedLocation = false, IsMailingLocation = false, GroupLocationTypeValueId = meetingLocationValueId, LocationId = _familyLocationDictionary[elemGroup.Attribute( "meetsAtHomeOfFamily" ).Value.AsGuid()], }; // Set the group location's GroupMemberPersonId if given (required?) if ( elemGroup.Attribute( "meetsAtHomeOfPerson" ) != null ) { groupLocation.GroupMemberPersonAliasId = _peopleAliasDictionary[elemGroup.Attribute( "meetsAtHomeOfPerson" ).Value.AsGuid()]; } group.GroupLocations.Add( groupLocation ); } group.LoadAttributes( rockContext ); // Set the study topic if ( elemGroup.Attribute( "studyTopic" ) != null ) { var topic = elemGroup.Attribute( "studyTopic" ).Value; DefinedValue smallGroupTopicDefinedValue = _smallGroupTopicDefinedType.DefinedValues.FirstOrDefault( a => a.Value == topic ); // add it as new if we didn't find it. if ( smallGroupTopicDefinedValue == null ) { smallGroupTopicDefinedValue = AddDefinedTypeValue( topic, _smallGroupTopicDefinedType, rockContext ); } group.SetAttributeValue( "Topic", smallGroupTopicDefinedValue.Guid.ToString() ); } // Set the schedule and meeting time if ( elemGroup.Attribute( "groupSchedule" ) != null ) { string[] schedule = elemGroup.Attribute( "groupSchedule" ).Value.SplitDelimitedValues( whitespace: false ); if ( schedule[0] == "weekly" ) { var dow = schedule[1]; var time = schedule[2]; AddWeeklySchedule( group, dow, time ); } } // Add each person as a member foreach ( var elemPerson in elemGroup.Elements( "person" ) ) { Guid personGuid = elemPerson.Attribute( "guid" ).Value.Trim().AsGuid(); GroupMember groupMember = new GroupMember(); groupMember.GroupMemberStatus = GroupMemberStatus.Active; if ( elemPerson.Attribute( "isLeader" ) != null ) { bool isLeader = elemPerson.Attribute( "isLeader" ).Value.Trim().AsBoolean(); if ( isLeader ) { var gtLeaderRole = groupType.Roles.Where( r => r.IsLeader ).FirstOrDefault(); if ( gtLeaderRole != null ) { groupMember.GroupRoleId = gtLeaderRole.Id; } } } else { groupMember.GroupRoleId = roleId ?? -1; } groupMember.PersonId = _peopleDictionary[personGuid]; group.Members.Add( groupMember ); } groupService.Add( group ); // Now we have to save changes in order for the attributes to be saved correctly. rockContext.SaveChanges(); group.SaveAttributeValues( rockContext ); if ( !_groupDictionary.ContainsKey( group.Guid ) ) { _groupDictionary.Add( group.Guid, group.Id ); } // Now add any group location schedules LocationService locationService = new LocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); Guid locationTypeMeetingLocationGuid = new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION ); var locationTypeMeetingLocationId = Rock.Web.Cache.DefinedValueCache.Read( locationTypeMeetingLocationGuid ).Id; foreach ( var elemLocation in elemGroup.Elements( "location" ) ) { Guid locationGuid = elemLocation.Attribute( "guid" ).Value.Trim().AsGuid(); Location location = locationService.Get( locationGuid ); GroupLocation groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.GroupLocationTypeValueId = locationTypeMeetingLocationId; group.GroupLocations.Add( groupLocation ); foreach ( var elemSchedule in elemLocation.Elements( "schedule" ) ) { try { Guid scheduleGuid = elemSchedule.Attribute( "guid" ).Value.Trim().AsGuid(); Schedule schedule = scheduleService.Get( scheduleGuid ); groupLocation.Schedules.Add( schedule ); } catch { } } TimeSpan ts = _stopwatch.Elapsed; AppendFormat( "{0:00}:{1:00}.{2:00} group location schedules added<br/>", ts.Minutes, ts.Seconds, ts.Milliseconds / 10 ); } } }
/// <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 ) { Schedule schedule; var rockContext = new RockContext(); ScheduleService scheduleService = new ScheduleService( rockContext ); int scheduleId = int.Parse( hfScheduleId.Value ); if ( scheduleId == 0 ) { schedule = new Schedule(); scheduleService.Add( schedule ); } else { schedule = scheduleService.Get( scheduleId ); } schedule.Name = tbScheduleName.Text; schedule.Description = tbScheduleDescription.Text; schedule.iCalendarContent = sbSchedule.iCalendarContent; schedule.CategoryId = cpCategory.SelectedValueAsInt(); int offsetMins = int.MinValue; if ( int.TryParse( nbStartOffset.Text, out offsetMins ) ) { schedule.CheckInStartOffsetMinutes = offsetMins; } else { schedule.CheckInStartOffsetMinutes = null; } offsetMins = int.MinValue; if ( int.TryParse( nbEndOffset.Text, out offsetMins ) ) { schedule.CheckInEndOffsetMinutes = offsetMins; } else { schedule.CheckInEndOffsetMinutes = null; } if ( !schedule.IsValid ) { // Controls will render the error messages return; } rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams["ScheduleId"] = schedule.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e ) { var service = new ScheduleService( new RockContext() ); var item = service.Get( int.Parse( hfScheduleId.Value ) ); ShowEditDetails( item ); }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGrid() { if ( _group != null ) { lHeading.Text = _group.Name; DateTime? fromDateTime = drpDates.LowerValue; DateTime? toDateTime = drpDates.UpperValue; List<int> locationIds = new List<int>(); List<int> scheduleIds = new List<int>(); // Location Filter if ( ddlLocation.Visible ) { string locValue = ddlLocation.SelectedValue; if ( locValue.StartsWith( "P" ) ) { int? parentLocationId = locValue.Substring( 1 ).AsIntegerOrNull(); if ( parentLocationId.HasValue ) { locationIds = new LocationService( _rockContext ) .GetAllDescendents( parentLocationId.Value ) .Select( l => l.Id ) .ToList(); } } else { int? locationId = locValue.AsIntegerOrNull(); if ( locationId.HasValue ) { locationIds.Add( locationId.Value ); } } } // Schedule Filter if ( ddlSchedule.Visible && ddlSchedule.SelectedValue != "0" ) { scheduleIds.Add( ddlSchedule.SelectedValueAsInt() ?? 0 ); } var qry = new ScheduleService( _rockContext ) .GetGroupOccurrences( _group, fromDateTime, toDateTime, locationIds, scheduleIds, true, bddlCampus.SelectedValueAsInt() ) .AsQueryable(); SortProperty sortProperty = gOccurrences.SortProperty; List<ScheduleOccurrence> occurrences = null; if ( sortProperty != null ) { occurrences = qry.Sort( sortProperty ).ToList(); } else { occurrences = qry.OrderByDescending( a => a.Date ).ThenByDescending( a => a.StartTime ).ToList(); } gOccurrences.DataSource = occurrences; gOccurrences.DataBind(); } }
/// <summary> /// Rs the filter_ display filter value. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void rFilter_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { if ( e.Key == MakeKeyUniqueToGroup( "Date Range" ) ) { // show the date range pickers current value, instead of the user preference since we set it to a default value if blank e.Value = DateRangePicker.FormatDelimitedValues( drpDates.DelimitedValues ); } else if ( e.Key == MakeKeyUniqueToGroup( "Schedule" ) ) { int scheduleId = e.Value.AsInteger(); if ( scheduleId != 0 ) { var schedule = new ScheduleService( _rockContext ).Get( scheduleId ); e.Value = schedule != null ? schedule.Name : string.Empty; } else { e.Value = string.Empty; } } else if ( e.Key == MakeKeyUniqueToGroup( "Location" ) ) { string locId = e.Value; if ( locId.StartsWith( "P" ) ) { locId = locId.Substring( 1 ); } int locationId = locId.AsInteger(); e.Value = new LocationService( _rockContext ).GetPath( locationId ); } else { e.Value = string.Empty; } }
/// <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 ) { using ( var rockContext = new RockContext() ) { GroupLocationService groupLocationService = new GroupLocationService( rockContext ); ScheduleService scheduleService = new ScheduleService( rockContext ); bool schedulesChanged = false; var gridViewRows = gGroupLocationSchedule.Rows; foreach ( GridViewRow row in gridViewRows.OfType<GridViewRow>() ) { int groupLocationId = int.Parse( gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string ); GroupLocation groupLocation = groupLocationService.Get( groupLocationId ); if ( groupLocation != null ) { foreach ( var fieldCell in row.Cells.OfType<DataControlFieldCell>() ) { var checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField; if ( checkBoxTemplateField != null ) { CheckBox checkBox = fieldCell.Controls[0] as CheckBox; string dataField = ( fieldCell.ContainingField as CheckBoxEditableField ).DataField; int scheduleId = int.Parse( dataField.Replace( "scheduleField_", string.Empty ) ); // update GroupLocationSchedule depending on if the Schedule is Checked or not if ( checkBox.Checked ) { // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it if ( !groupLocation.Schedules.Any( a => a.Id == scheduleId ) ) { var schedule = scheduleService.Get( scheduleId ); groupLocation.Schedules.Add( schedule ); schedulesChanged = true; } } else { // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it if ( groupLocation.Schedules.Any( a => a.Id == scheduleId ) ) { groupLocation.Schedules.Remove( groupLocation.Schedules.FirstOrDefault( a => a.Id == scheduleId ) ); schedulesChanged = true; } } } } } } if ( schedulesChanged ) { rockContext.SaveChanges(); if ( this.CurrentKioskId.HasValue ) { KioskDevice.Flush( this.CurrentKioskId.Value ); } } } NavigateToHomePage(); }
/// <summary> /// Sets the schedule context. /// </summary> /// <param name="scheduleId">The schedule identifier.</param> /// <param name="refreshPage">if set to <c>true</c> [refresh page].</param> /// <returns></returns> protected Schedule SetScheduleContext( int scheduleId, bool refreshPage = false ) { bool pageScope = GetAttributeValue( "ContextScope" ) == "Page"; var schedule = new ScheduleService( new RockContext() ).Get( scheduleId ); if ( schedule == null ) { // clear the current schedule context schedule = new Schedule() { Name = GetAttributeValue( "NoScheduleText" ), Guid = Guid.Empty }; } // set context and refresh below with the correct query string if needed RockPage.SetContextCookie( schedule, pageScope, false ); if ( refreshPage ) { // Only redirect if refreshPage is true if ( !string.IsNullOrWhiteSpace( PageParameter( "scheduleId" ) ) || GetAttributeValue( "DisplayQueryStrings" ).AsBoolean() ) { var queryString = HttpUtility.ParseQueryString( Request.QueryString.ToStringSafe() ); queryString.Set( "scheduleId", scheduleId.ToString() ); Response.Redirect( string.Format( "{0}?{1}", Request.Url.AbsolutePath, queryString ), false ); } else { Response.Redirect( Request.RawUrl, false ); } Context.ApplicationInstance.CompleteRequest(); } return schedule; }
private void ShowDetail(Guid personGuid) { using ( var rockContext = new RockContext() ) { var personService = new PersonService( new RockContext() ); var person = personService.Get( personGuid ); if ( person != null ) { lName.Text = person.FullName; string photoTag = Rock.Model.Person.GetPhotoImageTag( person, 120, 120 ); if ( person.PhotoId.HasValue ) { lPhoto.Text = string.Format( "<a href='{0}'>{1}</a>", person.PhotoUrl, photoTag ); } else { lPhoto.Text = photoTag; } lEmail.Visible = !string.IsNullOrWhiteSpace( person.Email ); lEmail.Text = person.GetEmailTag( ResolveRockUrl( "/" ), "btn btn-default", "<i class='fa fa-envelope'></i>" ); var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); var isFamilyChild = new Dictionary<int, bool>(); var allFamilyMembers = person.GetFamilyMembers( true ).ToList(); allFamilyMembers.Where( m => m.PersonId == person.Id ).ToList().ForEach( m => isFamilyChild.Add( m.GroupId, m.GroupRole.Guid.Equals( childGuid ) ) ); string urlRoot = Request.Url.ToString().ReplaceCaseInsensitive( personGuid.ToString(), "" ); var familyMembers = allFamilyMembers.Where( m => m.PersonId != person.Id ) .OrderBy( m => m.GroupId ) .ThenBy( m => m.Person.BirthDate ) .Select( m => new { Url = urlRoot + m.Person.Guid.ToString(), FullName = m.Person.FullName, Gender = m.Person.Gender, FamilyRole = m.GroupRole, Note = isFamilyChild[m.GroupId] ? ( m.GroupRole.Guid.Equals( childGuid ) ? " (Sibling)" : "(Parent)" ) : ( m.GroupRole.Guid.Equals( childGuid ) ? " (Child)" : "" ) } ) .ToList(); rcwFamily.Visible = familyMembers.Any(); rptrFamily.DataSource = familyMembers; rptrFamily.DataBind(); rptrPhones.DataSource = person.PhoneNumbers.Where( p => !p.IsUnlisted ).ToList(); rptrPhones.DataBind(); var schedules = new ScheduleService( rockContext ).Queryable() .Where( s => s.CheckInStartOffsetMinutes.HasValue ) .ToList(); var scheduleIds = schedules.Select( s => s.Id ).ToList(); var activeScheduleIds = new List<int>(); foreach ( var schedule in schedules ) { if ( schedule.IsScheduleOrCheckInActive ) { activeScheduleIds.Add( schedule.Id ); } } int? personAliasId = person.PrimaryAliasId; if ( !personAliasId.HasValue ) { personAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( person.Id ); } var attendances = new AttendanceService( rockContext ) .Queryable( "Schedule,Group,Location" ) .Where( a => a.PersonAliasId.HasValue && a.PersonAliasId == personAliasId && a.ScheduleId.HasValue && a.GroupId.HasValue && a.LocationId.HasValue && a.DidAttend.HasValue && a.DidAttend.Value && scheduleIds.Contains( a.ScheduleId.Value ) ) .OrderByDescending( a => a.StartDateTime ) .Take( 20 ) .Select( a => new AttendanceInfo { Date = a.StartDateTime, GroupId = a.Group.Id, Group = a.Group.Name, LocationId = a.LocationId.Value, Location = a.Location.Name, Schedule = a.Schedule.Name, IsActive = a.StartDateTime > DateTime.Today && activeScheduleIds.Contains( a.ScheduleId.Value ) } ).ToList(); // Set active locations to be a link to the room in manager page var qryParam = new Dictionary<string, string>(); qryParam.Add( "Group", "" ); qryParam.Add( "Location", "" ); foreach ( var attendance in attendances.Where( a => a.IsActive ) ) { qryParam["Group"] = attendance.GroupId.ToString(); qryParam["Location"] = attendance.LocationId.ToString(); attendance.Location = string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "ManagerPage", qryParam ), attendance.Location ); } rcwCheckinHistory.Visible = attendances.Any(); gHistory.DataSource = attendances; gHistory.DataBind(); } } }
/// <summary> /// Gets the occurrence items. /// </summary> private ScheduleOccurrence GetOccurrence() { DateTime? occurrenceDate = PageParameter( "Date" ).AsDateTime(); if ( !occurrenceDate.HasValue ) { occurrenceDate = PageParameter( "Occurrence" ).AsDateTime(); } List<int> locationIds = new List<int>(); int? locationId = PageParameter( "LocationId" ).AsIntegerOrNull(); locationIds.Add( locationId ?? 0 ); List<int> scheduleIds = new List<int>(); int? scheduleId = PageParameter( "ScheduleId" ).AsIntegerOrNull(); scheduleIds.Add( scheduleId ?? 0 ); if ( Page.IsPostBack && _allowAdd ) { if ( dpOccurrenceDate.Visible && dpOccurrenceDate.SelectedDate.HasValue ) { occurrenceDate = dpOccurrenceDate.SelectedDate; } if ( !locationIds.Any( l => l != 0 ) && ddlLocation.SelectedValueAsInt().HasValue ) { locationId = ddlLocation.SelectedValueAsInt().Value; locationIds = new List<int> { locationId.Value }; } if ( !scheduleIds.Any( s => s != 0 ) && ddlSchedule.SelectedValueAsInt().HasValue ) { scheduleId = ddlSchedule.SelectedValueAsInt().Value; scheduleIds = new List<int> { scheduleId.Value }; } } if ( occurrenceDate.HasValue ) { // Try to find the selected occurrence based on group's schedule if ( _group != null ) { // Get all the occurrences for this group, and load the attendance so we can show Attendance Count var occurrence = new ScheduleService( _rockContext ) .GetGroupOccurrences( _group, occurrenceDate.Value.Date, occurrenceDate.Value.AddDays( 1 ), locationIds, scheduleIds, true ) .OrderBy( o => o.Date ) .FirstOrDefault(); if ( occurrence != null ) { if ( occurrenceDate.Value.Date != occurrence.Date.Date ) { occurrence.ScheduleId = null; occurrence.ScheduleName = string.Empty; occurrence.Date = occurrenceDate.Value; } return occurrence; } } // If an occurrence date was included, but no occurrence was found with that date, and new // occurrences can be added, create a new one if ( _allowAdd ) { Schedule schedule = null; if ( scheduleId.HasValue ) { schedule = new ScheduleService( _rockContext ).Get( scheduleId.Value ); } return new ScheduleOccurrence( occurrenceDate.Value.Date, ( schedule != null ? schedule.StartTimeOfDay : occurrenceDate.Value.TimeOfDay ), scheduleId, string.Empty, locationId ); } } return null; }
/// <summary> /// Handles the Click event of the btnCancel 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 btnCancel_Click( object sender, EventArgs e ) { if ( hfScheduleId.Value.Equals( "0" ) ) { int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull(); if ( parentCategoryId.HasValue ) { // Cancelling on Add, and we know the parentCategoryId, so we are probably in treeview mode, so navigate to the current page var qryParams = new Dictionary<string, string>(); qryParams["CategoryId"] = parentCategoryId.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } else { // Cancelling on Add. Return to Grid NavigateToParentPage(); } } else { // Cancelling on Edit. Return to Details var service = new ScheduleService( new RockContext() ); var item = service.Get( int.Parse( hfScheduleId.Value ) ); ShowReadonlyDetails( item ); } }
/// <summary> /// Adds the schedule columns. /// </summary> private void AddScheduleColumns() { ScheduleService scheduleService = new ScheduleService( new RockContext() ); // limit Schedules to ones that have a CheckInStartOffsetMinutes var scheduleQry = scheduleService.Queryable().Where( a => a.CheckInStartOffsetMinutes != null ); // limit Schedules to the Category from the Filter int scheduleCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.SCHEDULE_SERVICE_TIMES.AsGuid() ).Id; scheduleQry = scheduleQry.Where( a => a.CategoryId == scheduleCategoryId ); // clear out any existing schedule columns just in case schedules been added/removed var scheduleList = scheduleQry.ToList().OrderBy( a => a.ToString() ).ToList(); var checkBoxEditableFields = gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>().ToList(); foreach ( var field in checkBoxEditableFields ) { gGroupLocationSchedule.Columns.Remove( field ); } foreach ( var item in scheduleList ) { string dataFieldName = string.Format( "scheduleField_{0}", item.Id ); CheckBoxEditableField field = new CheckBoxEditableField { HeaderText = item.FriendlyScheduleText.Replace( " at ", "<br/>" ), DataField = dataFieldName }; gGroupLocationSchedule.Columns.Add( field ); } }
/// <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 ) { EventItemOccurrence eventItemOccurrence = null; using ( var rockContext = new RockContext() ) { bool newItem = false; var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext ); var eventItemOccurrenceGroupMapService = new EventItemOccurrenceGroupMapService( rockContext ); var registrationInstanceService = new RegistrationInstanceService( rockContext ); var scheduleService = new ScheduleService( rockContext ); int eventItemOccurrenceId = hfEventItemOccurrenceId.ValueAsInt(); if ( eventItemOccurrenceId != 0 ) { eventItemOccurrence = eventItemOccurrenceService .Queryable( "Linkages" ) .Where( i => i.Id == eventItemOccurrenceId ) .FirstOrDefault(); } if ( eventItemOccurrence == null ) { newItem = true; eventItemOccurrence = new EventItemOccurrence{ EventItemId = PageParameter("EventItemId").AsInteger() }; eventItemOccurrenceService.Add( eventItemOccurrence ); } int? newCampusId = ddlCampus.SelectedValueAsInt(); if ( eventItemOccurrence.CampusId != newCampusId ) { eventItemOccurrence.CampusId = newCampusId; if ( newCampusId.HasValue ) { var campus = new CampusService( rockContext ).Get( newCampusId.Value ); eventItemOccurrence.Campus = campus; } else { eventItemOccurrence.Campus = null; } } eventItemOccurrence.Location = tbLocation.Text; string iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent( iCalendarContent ); if ( calEvent != null && calEvent.DTStart != null ) { if ( eventItemOccurrence.Schedule == null ) { eventItemOccurrence.Schedule = new Schedule(); } eventItemOccurrence.Schedule.iCalendarContent = iCalendarContent; } else { if ( eventItemOccurrence.ScheduleId.HasValue ) { var oldSchedule = scheduleService.Get( eventItemOccurrence.ScheduleId.Value ); if ( oldSchedule != null ) { scheduleService.Delete( oldSchedule ); } } } if ( !eventItemOccurrence.ContactPersonAliasId.Equals( ppContact.PersonAliasId )) { PersonAlias personAlias = null; eventItemOccurrence.ContactPersonAliasId = ppContact.PersonAliasId; if ( eventItemOccurrence.ContactPersonAliasId.HasValue ) { personAlias = new PersonAliasService( rockContext ).Get( eventItemOccurrence.ContactPersonAliasId.Value ); } if ( personAlias != null ) { eventItemOccurrence.ContactPersonAlias = personAlias; } } eventItemOccurrence.ContactPhone = PhoneNumber.FormattedNumber( PhoneNumber.DefaultCountryCode(), pnPhone.Number ); eventItemOccurrence.ContactEmail = tbEmail.Text; eventItemOccurrence.Note = htmlOccurrenceNote.Text; // Remove any linkage no longer in UI Guid uiLinkageGuid = LinkageState != null ? LinkageState.Guid : Guid.Empty; foreach( var linkage in eventItemOccurrence.Linkages.Where( l => !l.Guid.Equals(uiLinkageGuid)).ToList()) { eventItemOccurrence.Linkages.Remove( linkage ); eventItemOccurrenceGroupMapService.Delete( linkage ); } // Add/Update linkage in UI if ( !uiLinkageGuid.Equals( Guid.Empty )) { var linkage = eventItemOccurrence.Linkages.Where( l => l.Guid.Equals( uiLinkageGuid)).FirstOrDefault(); if ( linkage == null ) { linkage = new EventItemOccurrenceGroupMap(); eventItemOccurrence.Linkages.Add( linkage ); } linkage.CopyPropertiesFrom( LinkageState ); // update registration instance if ( LinkageState.RegistrationInstance != null ) { if ( LinkageState.RegistrationInstance.Id != 0 ) { linkage.RegistrationInstance = registrationInstanceService.Get( LinkageState.RegistrationInstance.Id ); } if ( linkage.RegistrationInstance == null ) { var registrationInstance = new RegistrationInstance(); registrationInstanceService.Add( registrationInstance ); linkage.RegistrationInstance = registrationInstance; } linkage.RegistrationInstance.CopyPropertiesFrom( LinkageState.RegistrationInstance ); } } if ( !Page.IsValid ) { return; } if ( !eventItemOccurrence.IsValid ) { // Controls will render the error messages return; } rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) ); qryParams.Add( "EventItemId", PageParameter( "EventItemId" ) ); if ( newItem ) { NavigateToParentPage( qryParams ); } else { qryParams.Add( "EventItemOccurrenceId", eventItemOccurrence.Id.ToString() ); NavigateToPage( RockPage.Guid, qryParams ); } } }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute( IJobExecutionContext context ) { JobDataMap dataMap = context.JobDetail.JobDataMap; var groupType = GroupTypeCache.Read( dataMap.GetString( "GroupType" ).AsGuid() ); int attendanceRemindersSent = 0; if ( groupType.TakesAttendance && groupType.SendAttendanceReminder ) { // Get the occurrence dates that apply var dates = new List<DateTime>(); dates.Add( RockDateTime.Today ); try { string[] reminderDays = dataMap.GetString( "SendReminders" ).Split( ',' ); foreach ( string reminderDay in reminderDays ) { if ( reminderDay.Trim() != string.Empty ) { var reminderDate = RockDateTime.Today.AddDays( 0 - Convert.ToInt32( reminderDay ) ); if ( !dates.Contains( reminderDate ) ) { dates.Add( reminderDate ); } } } } catch { } var rockContext = new RockContext(); var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var scheduleService = new ScheduleService( rockContext ); var attendanceService = new AttendanceService( rockContext ); var startDate = dates.Min(); var endDate = dates.Max().AddDays( 1 ); // Find all 'occurrences' for the groups that occur on the affected dates var occurrences = new Dictionary<int, List<DateTime>>(); foreach ( var group in groupService .Queryable( "Schedule" ).AsNoTracking() .Where( g => g.GroupTypeId == groupType.Id && g.IsActive && g.Schedule != null && g.Members.Any( m => m.GroupMemberStatus == GroupMemberStatus.Active && m.GroupRole.IsLeader && m.Person.Email != null && m.Person.Email != "" ) ) ) { // Add the group occurrences.Add( group.Id, new List<DateTime>() ); // Check for a iCal schedule if ( !string.IsNullOrWhiteSpace( group.Schedule.iCalendarContent ) ) { // If schedule has an iCal schedule, get occurrences between first and last dates foreach ( var occurrence in group.Schedule.GetOccurrences( startDate, endDate ) ) { var startTime = occurrence.Period.StartTime.Value; if ( dates.Contains( startTime.Date ) ) { occurrences[group.Id].Add( startTime ); } } } else { // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week if ( group.Schedule.WeeklyDayOfWeek.HasValue ) { foreach ( var date in dates ) { if ( date.DayOfWeek == group.Schedule.WeeklyDayOfWeek.Value ) { var startTime = date; if ( group.Schedule.WeeklyTimeOfDay.HasValue ) { startTime = startTime.Add( group.Schedule.WeeklyTimeOfDay.Value ); } occurrences[group.Id].Add( startTime ); } } } } } // Remove any occurrences during group type exclusion date ranges foreach ( var exclusion in groupType.GroupScheduleExclusions ) { if ( exclusion.Start.HasValue && exclusion.End.HasValue ) { foreach ( var keyVal in occurrences ) { foreach ( var occurrenceDate in keyVal.Value.ToList() ) { if ( occurrenceDate >= exclusion.Start.Value && occurrenceDate < exclusion.End.Value.AddDays( 1 ) ) { keyVal.Value.Remove( occurrenceDate ); } } } } } // Remove any 'occurrenes' that already have attendance data entered foreach ( var occurrence in attendanceService .Queryable().AsNoTracking() .Where( a => a.StartDateTime >= startDate && a.StartDateTime < endDate && occurrences.Keys.Contains( a.GroupId.Value ) && a.ScheduleId.HasValue ) .Select( a => new { GroupId = a.GroupId.Value, a.StartDateTime } ) .Distinct() .ToList() ) { occurrences[occurrence.GroupId].RemoveAll( d => d.Date == occurrence.StartDateTime.Date ); } // Get the groups that have occurrences var groupIds = occurrences.Where( o => o.Value.Any() ).Select( o => o.Key ).ToList(); // Get the leaders of those groups var leaders = groupMemberService .Queryable( "Group,Person" ).AsNoTracking() .Where( m => groupIds.Contains( m.GroupId ) && m.GroupMemberStatus == GroupMemberStatus.Active && m.GroupRole.IsLeader && m.Person.Email != null && m.Person.Email != "" ) .ToList(); // Loop through the leaders foreach ( var leader in leaders ) { foreach ( var group in occurrences.Where( o => o.Key == leader.GroupId ) ) { var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields( null, leader.Person ); mergeObjects.Add( "Person", leader.Person ); mergeObjects.Add( "Group", leader.Group ); mergeObjects.Add( "Occurrence", group.Value.Max() ); var recipients = new List<RecipientData>(); recipients.Add( new RecipientData( leader.Person.Email, mergeObjects ) ); Email.Send( dataMap.GetString( "SystemEmail" ).AsGuid(), recipients ); attendanceRemindersSent++; } } } context.Result = string.Format( "{0} attendance reminders sent", attendanceRemindersSent ); }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns() { RockContext rockContext = new RockContext(); ddlDataView.Items.Clear(); var dataviewList = new DataViewService( rockContext ).Queryable().Select( s => new { s.Id, s.Name } ).OrderBy( a => a.Name ).ToList(); foreach ( var item in dataviewList ) { ddlDataView.Items.Add( new ListItem( item.Name, item.Id.ToString() ) ); } ddlSourceType.Items.Clear(); foreach ( var item in new DefinedValueService( rockContext ).GetByDefinedTypeGuid( Rock.SystemGuid.DefinedType.METRIC_SOURCE_TYPE.AsGuid() ) ) { ddlSourceType.Items.Add( new ListItem( item.Value, item.Id.ToString() ) ); } rblScheduleSelect.Items.Clear(); rblScheduleSelect.Items.Add( new ListItem( ScheduleSelectionType.Unique.ConvertToString(), ScheduleSelectionType.Unique.ConvertToInt().ToString() ) ); rblScheduleSelect.Items.Add( new ListItem( ScheduleSelectionType.NamedSchedule.ConvertToString(), ScheduleSelectionType.NamedSchedule.ConvertToInt().ToString() ) ); var scheduleCategoryId = new CategoryService( rockContext ).Get( Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid() ).Id; var scheduleCategories = new ScheduleService( rockContext ).Queryable() .Where( a => a.CategoryId == scheduleCategoryId && a.Name != string.Empty ) .OrderBy( a => a.Name ).ToList(); ddlSchedule.Items.Clear(); foreach ( var item in scheduleCategories ) { ddlSchedule.Items.Add( new ListItem( item.Name, item.Id.ToString() ) ); } // limit to EntityTypes that support picking a Value with a picker etpMetricPartitionEntityType.EntityTypes = new EntityTypeService( new RockContext() ).GetEntities().OrderBy( t => t.FriendlyName ).Where( a => a.SingleValueFieldTypeId.HasValue ).ToList(); // just in case they select an EntityType that can be qualified by DefinedType... ddlMetricPartitionDefinedTypePicker.Items.Clear(); ddlMetricPartitionDefinedTypePicker.Items.Add( new ListItem() ); var definedTypesList = new DefinedTypeService( rockContext ).Queryable().OrderBy( a => a.Name ) .Select( a => new { a.Id, a.Name } ).ToList(); foreach ( var definedType in definedTypesList ) { ddlMetricPartitionDefinedTypePicker.Items.Add( new ListItem( definedType.Name, definedType.Id.ToString() ) ); } }