private void BindGridMetric() { var queryable = new Rock.Model.MetricService().Queryable(); if (ddlCategoryFilter.SelectedValue != Rock.Constants.All.Text) { queryable = queryable. Where(a => a.Category == ddlCategoryFilter.SelectedValue); } SortProperty sortProperty = rGridMetric.SortProperty; if (sortProperty != null) { queryable = queryable. Sort(sortProperty); } else { queryable = queryable. OrderBy(a => a.Category). ThenBy(a => a.Title); } rGridMetric.DataSource = queryable.ToList(); rGridMetric.DataBind(); }
/// <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 valueParts = value.Split( '|' ); if ( valueParts.Length > 0 ) { var service = new MetricService( new RockContext() ); var metric = service.Get( new Guid( valueParts[0] ) ); if ( metric != null ) { formattedValue = metric.Title; var entityType = EntityTypeCache.Read( metric.EntityTypeId ?? 0 ); if ( entityType != null && entityType.SingleValueFieldType != null ) { if ( valueParts.Length > 1 ) { formattedValue = string.Format( "{0} - EntityId:{1}", metric.Title, valueParts[1].AsIntegerOrNull() ); } } } } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
public IQueryable<MetricValue> GetByMetricId( int metricId, MetricValueType? metricValueType = null ) { var metric = new MetricService( new RockContext() ).Get( metricId ); var result = Get().Where( a => a.MetricId == metricId ); if ( metricValueType.HasValue ) { result = result.Where( a => a.MetricValueType == metricValueType ); } return result.OrderBy( a => a.MetricValueDateTime ); }
protected void rGridMetric_Delete(object sender, RowEventArgs e) { var metricService = new Rock.Model.MetricService(); Rock.Model.Metric metric = metricService.Get((int)rGridMetric.DataKeys[e.RowIndex]["id"]); if (metric != null) { metricService.Delete(metric, CurrentPersonId); metricService.Save(metric, CurrentPersonId); } BindGridMetric(); }
/// <summary> /// Gets the primary partition entity identifier from context. /// </summary> /// <returns></returns> private List <MetricPartitionEntityId> GetPrimaryMetricPartitionEntityIdFromContext() { List <MetricPartitionEntityId> results = new List <MetricPartitionEntityId>(); if (!this.MetricId.HasValue) { return(results); } using (var rockContext = new Rock.Data.RockContext()) { var metric = new Rock.Model.MetricService(rockContext).Get(this.MetricId ?? 0); if (metric == null) { return(results); } foreach (var mp in metric.MetricPartitions.OrderBy(a => a.Order)) { var result = new MetricPartitionEntityId(); result.MetricPartition = mp; var entityTypeCache = EntityTypeCache.Get(result.MetricPartition.EntityTypeId ?? 0); if (entityTypeCache != null && this.ContextEntity(entityTypeCache.Name) != null) { result.EntityId = this.ContextEntity(entityTypeCache.Name).Id; } // if Getting the EntityFromContext, and we didn't get it from ContextEntity, get it from the Page Param if (!result.EntityId.HasValue) { // figure out what the param name should be ("CampusId, GroupId, etc") depending on metric's entityType var entityParamName = "EntityId"; if (entityTypeCache != null) { entityParamName = entityTypeCache.Name + "Id"; } result.EntityId = this.PageParameter(entityParamName).AsIntegerOrNull(); } results.Add(result); } } return(results); }
/// <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 guidPairs = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs( value ); var metricGuids = guidPairs.Select( a => a.MetricGuid ); var metrics = new MetricService( new RockContext() ).Queryable().Where( a => metricGuids.Contains( a.Guid ) ); if ( metrics.Any() ) { formattedValue = string.Join( ", ", ( from metric in metrics select metric.Title ).ToArray() ); } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Gets the primary partition entity identifier from context. /// </summary> /// <returns></returns> private MetricPartitionEntityId GetPrimaryMetricPartitionEntityIdFromContext() { EntityTypeCache entityTypeCache = null; MetricPartitionEntityId result = new MetricPartitionEntityId(); if (this.MetricId.HasValue) { using (var rockContext = new Rock.Data.RockContext()) { var metric = new Rock.Model.MetricService(rockContext).Get(this.MetricId ?? 0); if (metric != null) { // for backwards compatibily, get the first metric partition result.MetricPartition = metric.MetricPartitions.OrderBy(a => a.Order).First(); entityTypeCache = EntityTypeCache.Read(result.MetricPartition.EntityTypeId ?? 0); } } } if (entityTypeCache != null && this.ContextEntity(entityTypeCache.Name) != null) { result.EntityId = this.ContextEntity(entityTypeCache.Name).Id; } // if Getting the EntityFromContext, and we didn't get it from ContextEntity, get it from the Page Param if (!result.EntityId.HasValue) { // figure out what the param name should be ("CampusId, GroupId, etc") depending on metric's entityType var entityParamName = "EntityId"; if (entityTypeCache != null) { entityParamName = entityTypeCache.Name + "Id"; } result.EntityId = this.PageParameter(entityParamName).AsIntegerOrNull(); } return(result); }
protected void btnSaveMetric_Click(object sender, EventArgs e) { using (new Rock.Data.UnitOfWorkScope()) { var metricService = new Rock.Model.MetricService(); Rock.Model.Metric metric; int metricId = (hfIdMetric.Value) != null?Int32.Parse(hfIdMetric.Value) : 0; if (metricId == 0) { metric = new Rock.Model.Metric(); metric.IsSystem = false; metricService.Add(metric, CurrentPersonId); } else { metric = metricService.Get(metricId); } metric.Category = tbCategory.Text; metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.MinValue = tbMinValue.Text != "" ? Int32.Parse(tbMinValue.Text, NumberStyles.AllowThousands) : (int?)null; metric.MaxValue = tbMinValue.Text != "" ? Int32.Parse(tbMaxValue.Text, NumberStyles.AllowThousands) : (int?)null; metric.Type = cbType.Checked; metric.CollectionFrequencyValueId = Int32.Parse(ddlCollectionFrequency.SelectedValue); metric.Source = tbSource.Text; metric.SourceSQL = tbSourceSQL.Text; metricService.Save(metric, CurrentPersonId); } BindCategoryFilter(); BindGridMetric(); pnlMetricDetails.Visible = false; pnlMetricList.Visible = true; }
protected void ShowEditMetric(int metricId) { hfIdMetric.Value = metricId.ToString(); var metric = new Rock.Model.MetricService().Get(metricId); if (metric != null) { lAction.Text = "Edit"; tbCategory.Text = metric.Category; tbTitle.Text = metric.Title; tbSubtitle.Text = metric.Subtitle; tbDescription.Text = metric.Description; tbMinValue.Text = metric.MinValue.ToString(); tbMaxValue.Text = metric.MaxValue.ToString(); cbType.Checked = metric.Type; ddlCollectionFrequency.SelectedValue = metric.CollectionFrequencyValueId.ToString(); tbSource.Text = metric.Source; tbSourceSQL.Text = metric.SourceSQL; } else { lAction.Text = "Add"; tbCategory.Text = ddlCategoryFilter.SelectedValue != Rock.Constants.All.Text ? ddlCategoryFilter.SelectedValue : string.Empty; tbTitle.Text = string.Empty; tbSubtitle.Text = string.Empty; tbDescription.Text = string.Empty; tbMinValue.Text = string.Empty; tbMaxValue.Text = string.Empty; cbType.Checked = false; tbSource.Text = string.Empty; tbSourceSQL.Text = string.Empty; } pnlMetricList.Visible = false; pnlMetricDetails.Visible = true; }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { int? metricId = hfMetricId.Value.AsIntegerOrNull(); if ( !metricId.HasValue ) { return; } var rockContext = new RockContext(); SortProperty sortProperty = gMetricValues.SortProperty; MetricValueService metricValueService = new MetricValueService( rockContext ); var qry = metricValueService.Queryable(); qry = qry.Where( a => a.MetricId == metricId ); var entityColumn = gMetricValues.Columns.OfType<BoundField>().FirstOrDefault( a => a.DataField == "EntityId" ); var metric = new MetricService( rockContext ).Get( metricId ?? 0 ); entityColumn.Visible = metric != null && metric.EntityTypeId.HasValue; if ( metric != null ) { _entityNameLookup = new Dictionary<int, string>(); var entityTypeCache = EntityTypeCache.Read( metric.EntityTypeId ?? 0 ); if ( entityTypeCache != null ) { entityColumn.HeaderText = entityTypeCache.FriendlyName; IQueryable<IEntity> entityQry = null; if ( entityTypeCache.GetEntityType() == typeof( Rock.Model.Group ) ) { // special case for Group since there could be a very large number (especially if you include families), so limit to GroupType.ShowInGroupList entityQry = new GroupService( rockContext ).Queryable().Where( a => a.GroupType.ShowInGroupList ); } else { Type[] modelType = { entityTypeCache.GetEntityType() }; Type genericServiceType = typeof( Rock.Data.Service<> ); Type modelServiceType = genericServiceType.MakeGenericType( modelType ); var serviceInstance = Activator.CreateInstance( modelServiceType, new object[] { rockContext } ) as IService; MethodInfo qryMethod = serviceInstance.GetType().GetMethod( "Queryable", new Type[] { } ); entityQry = qryMethod.Invoke( serviceInstance, new object[] { } ) as IQueryable<IEntity>; } if ( entityQry != null ) { var entityList = entityQry.ToList(); foreach ( var e in entityList ) { _entityNameLookup.AddOrReplace( e.Id, e.ToString() ); } } } } var drp = new DateRangePicker(); drp.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); if ( drp.LowerValue.HasValue ) { qry = qry.Where( a => a.MetricValueDateTime >= drp.LowerValue.Value ); } if ( drp.UpperValue.HasValue ) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 ); qry = qry.Where( a => a.MetricValueDateTime < upperDate ); } var metricValueType = gfMetricValues.GetUserPreference( "Goal/Measure" ).ConvertToEnumOrNull<MetricValueType>(); if ( metricValueType.HasValue ) { qry = qry.Where( a => a.MetricValueType == metricValueType.Value ); } var entityParts = gfMetricValues.GetUserPreference( this.EntityPreferenceKey ).Split( '|' ); if ( entityParts.Length == 2 ) { if ( entityParts[0].AsInteger() == metric.EntityTypeId ) { var entityId = entityParts[1].AsIntegerOrNull(); if ( entityId.HasValue ) { qry = qry.Where( a => a.EntityId == entityId ); } } } if ( sortProperty != null ) { gMetricValues.DataSource = qry.Sort( sortProperty ).ToList(); } else { gMetricValues.DataSource = qry.OrderBy( s => s.Order ).ThenBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ThenBy( s => s.XValue ).ToList(); } gMetricValues.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 ); 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> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( !Page.IsPostBack ) { // Options for Chart var chartOptions = ChartOptions.Default; chartOptions.vAxis.title = this.Title; if ( !string.IsNullOrWhiteSpace( this.Subtitle ) ) { chartOptions.vAxis.title += Environment.NewLine + this.Subtitle; } hfOptions.Value = ( chartOptions as object ).ToJson(); List<ColumnDefinition> columnDefinitions = new List<ColumnDefinition>(); columnDefinitions.Add( new ColumnDefinition( "Date", ColumnDataType.date ) ); columnDefinitions.Add( new ColumnDefinition( "Attendance", ColumnDataType.number ) ); columnDefinitions.Add( new ChartTooltip() ); hfColumns.Value = columnDefinitions.ToJson(); // Data for Chart Guid attendanceMetricGuid = new Guid( "D4752628-DFC9-4681-ADB3-01936B8F38CA" ); int metricId = new MetricService( new RockContext()).Get(attendanceMetricGuid).Id; DateTime? startDate = new DateTime( 2013, 1, 1 ); DateTime? endDate = new DateTime( 2014, 1, 1 ); int? entityId = null; hfRestUrlParams.Value = string.Format( "{0}?startDate={1}&endDate={2}", metricId, startDate ?? DateTime.MinValue, endDate ?? DateTime.MaxValue); if (entityId.HasValue) { hfRestUrlParams.Value += string.Format( "&entityId={0}", entityId ); } } }
/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { drpDates.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); ddlGoalMeasure.Items.Clear(); ddlGoalMeasure.Items.Add( new ListItem( string.Empty, string.Empty ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Goal.ConvertToString(), MetricValueType.Goal.ConvertToInt().ToString() ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Measure.ConvertToString(), MetricValueType.Measure.ConvertToInt().ToString() ) ); ddlGoalMeasure.SelectedValue = gfMetricValues.GetUserPreference( "Goal/Measure" ); var metric = new MetricService( new RockContext() ).Get( hfMetricId.Value.AsInteger() ); epEntity.Visible = metric != null; if ( metric != null ) { epEntity.EntityTypeId = metric.EntityTypeId; epEntity.EntityTypePickerVisible = false; var parts = gfMetricValues.GetUserPreference( this.EntityPreferenceKey ).Split( '|' ); if ( parts.Length >= 2 ) { epEntity.EntityId = parts[1].AsIntegerOrNull(); } } }
/// <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> /// Binds the grid. /// </summary> private void BindGrid() { int? metricId = hfMetricId.Value.AsIntegerOrNull(); if ( !metricId.HasValue ) { return; } var rockContext = new RockContext(); SortProperty sortProperty = gMetricValues.SortProperty; MetricValueService metricValueService = new MetricValueService( rockContext ); var qry = metricValueService.Queryable().Include( a => a.MetricValuePartitions ); qry = qry.Where( a => a.MetricId == metricId ); var metricValuePartitionsColumn = gMetricValues.Columns.OfType<RockLiteralField>().FirstOrDefault( a => a.ID == "lMetricValuePartitions" ); var metric = new MetricService( rockContext ).Get( metricId ?? 0 ); metricValuePartitionsColumn.Visible = metric != null && metric.MetricPartitions.Any( a => a.EntityTypeId.HasValue ); var drp = new DateRangePicker(); drp.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); if ( drp.LowerValue.HasValue ) { qry = qry.Where( a => a.MetricValueDateTime >= drp.LowerValue.Value ); } if ( drp.UpperValue.HasValue ) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 ); qry = qry.Where( a => a.MetricValueDateTime < upperDate ); } var metricValueType = gfMetricValues.GetUserPreference( "Goal/Measure" ).ConvertToEnumOrNull<MetricValueType>(); if ( metricValueType.HasValue ) { qry = qry.Where( a => a.MetricValueType == metricValueType.Value ); } var entityTypeEntityUserPreference = gfMetricValues.GetUserPreference( this.EntityTypeEntityPreferenceKey ) ?? string.Empty; var entityTypeEntityList = entityTypeEntityUserPreference.Split( ',' ).Select( a => a.Split( '|' ) ).Where( a => a.Length == 2 ).Select( a => new { EntityTypeId = a[0].AsIntegerOrNull(), EntityId = a[1].AsIntegerOrNull() } ); foreach ( var entityTypeEntity in entityTypeEntityList ) { if ( entityTypeEntity.EntityTypeId.HasValue && entityTypeEntity.EntityId.HasValue ) { qry = qry.Where( a => a.MetricValuePartitions.Any( x => x.MetricPartition.EntityTypeId == entityTypeEntity.EntityTypeId && x.EntityId == entityTypeEntity.EntityId ) ); } } if ( sortProperty != null ) { qry = qry.Sort( sortProperty ); } else { qry = qry.OrderBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ThenBy( s => s.XValue ).ThenByDescending( s => s.ModifiedDateTime ); } gMetricValues.SetLinqDataSource( qry ); gMetricValues.DataBind(); }
/// <summary> /// Creates the dynamic controls. /// </summary> private void CreateDynamicControls( int? metricId ) { phMetricValuePartitions.Controls.Clear(); Metric metric = new MetricService( new RockContext() ).Get( metricId ?? 0 ); if ( metric != null ) { foreach ( var metricPartition in metric.MetricPartitions ) { if ( metricPartition.EntityTypeId.HasValue ) { var entityTypeCache = EntityTypeCache.Read( metricPartition.EntityTypeId.Value ); if ( entityTypeCache != null && entityTypeCache.SingleValueFieldType != null ) { var fieldType = entityTypeCache.SingleValueFieldType; Dictionary<string, Rock.Field.ConfigurationValue> configurationValues; if ( fieldType.Field is IEntityQualifierFieldType ) { configurationValues = ( fieldType.Field as IEntityQualifierFieldType ).GetConfigurationValuesFromEntityQualifier( metricPartition.EntityTypeQualifierColumn, metricPartition.EntityTypeQualifierValue ); } else { configurationValues = new Dictionary<string, ConfigurationValue>(); } var entityTypeEditControl = fieldType.Field.EditControl( configurationValues, string.Format( "metricPartition{0}_entityTypeEditControl", metricPartition.Id ) ); var panelCol4 = new Panel { CssClass = "col-md-4" }; if ( entityTypeEditControl != null ) { phMetricValuePartitions.Controls.Add( entityTypeEditControl ); if ( entityTypeEditControl is IRockControl ) { var entityTypeRockControl = ( entityTypeEditControl as IRockControl ); entityTypeRockControl.Label = metricPartition.Label; } } else { var errorControl = new LiteralControl(); errorControl.Text = string.Format( "<span class='label label-danger'>Unable to create Partition control for {0}. Verify that the metric partition settings are set correctly</span>", metricPartition.Label ); phMetricValuePartitions.Controls.Add( errorControl ); } } } } } }
/// <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 ) { var rockContext = new RockContext(); MetricService metricService = new MetricService( rockContext ); Metric metric = metricService.Get( hfMetricId.Value.AsInteger() ); // intentionally get metricCategory with new RockContext() so we don't confuse SaveChanges() int? parentCategoryId = null; var metricCategory = new MetricCategoryService( new RockContext() ).Get( hfMetricCategoryId.ValueAsInt() ); if ( metricCategory != null ) { parentCategoryId = metricCategory.CategoryId; } if ( metric != null ) { string errorMessage; if ( !metricService.CanDelete( metric, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } metricService.Delete( metric ); rockContext.SaveChanges(); } var qryParams = new Dictionary<string, string>(); if ( parentCategoryId != null ) { qryParams["CategoryId"] = parentCategoryId.ToString(); } NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the lbCancel 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 lbCancel_Click( object sender, EventArgs e ) { var metric = new MetricService().Get( hfMetricId.ValueAsInt() ); ShowReadOnly( metric ); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="metricValueId">The metric value identifier.</param> /// <param name="metricId">The metric identifier.</param> public void ShowDetail( int metricValueId, int? metricId ) { pnlDetails.Visible = true; // Load depending on Add(0) or Edit MetricValue metricValue = null; if ( !metricValueId.Equals( 0 ) ) { metricValue = new MetricValueService( new RockContext() ).Get( metricValueId ); lActionTitle.Text = ActionTitle.Edit( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle(); pdAuditDetails.SetEntity( metricValue, ResolveRockUrl( "~" ) ); } if ( metricValue == null && metricId.HasValue ) { metricValue = new MetricValue { Id = 0, MetricId = metricId.Value }; metricValue.Metric = metricValue.Metric ?? new MetricService( new RockContext() ).Get( metricValue.MetricId ); lActionTitle.Text = ActionTitle.Add( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle(); // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } hfMetricValueId.Value = metricValue.Id.ToString(); LoadDropDowns(); ddlMetricValueType.SelectedValue = metricValue.MetricValueType.ConvertToInt().ToString(); tbXValue.Text = metricValue.XValue; tbYValue.Text = metricValue.YValue.ToString(); hfMetricId.Value = metricValue.MetricId.ToString(); tbNote.Text = metricValue.Note; dpMetricValueDateTime.SelectedDate = metricValue.MetricValueDateTime; // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; bool canEdit = UserCanEdit; if ( !canEdit && metricId.HasValue && metricId.Value > 0 ) { var metric = new MetricService( new RockContext() ).Get( metricId.Value ); if ( metric != null && metric.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { canEdit = true; } } if ( !canEdit ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( MetricValue.FriendlyTypeName ); } if ( readOnly ) { lActionTitle.Text = ActionTitle.View( MetricValue.FriendlyTypeName ); btnCancel.Text = "Close"; } CreateDynamicControls( metricValue, true, readOnly ); ddlMetricValueType.Enabled = !readOnly; tbXValue.ReadOnly = readOnly; tbYValue.ReadOnly = readOnly; tbNote.ReadOnly = readOnly; dpMetricValueDateTime.Enabled = !readOnly; btnSave.Visible = !readOnly; }
/// <summary> /// Handles the ApplyFilterClick event of the gfMetricValues 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 gfMetricValues_ApplyFilterClick( object sender, EventArgs e ) { gfMetricValues.SaveUserPreference( "Date Range", drpDates.DelimitedValues ); gfMetricValues.SaveUserPreference( "Goal/Measure", ddlGoalMeasure.SelectedValue ); var metric = new MetricService( new RockContext() ).Get( hfMetricId.Value.AsInteger() ); var entityTypeEntityFilters = new Dictionary<int, int?>(); foreach ( var metricPartition in metric.MetricPartitions ) { var metricPartitionEntityType = EntityTypeCache.Read( metricPartition.EntityTypeId ?? 0 ); var controlId = string.Format( "metricPartition{0}_entityTypeEditControl", metricPartition.Id ); Control entityTypeEditControl = phMetricValuePartitions.FindControl( controlId ); int? entityId; if ( metricPartitionEntityType != null && metricPartitionEntityType.SingleValueFieldType != null && metricPartitionEntityType.SingleValueFieldType.Field is IEntityFieldType ) { entityId = ( metricPartitionEntityType.SingleValueFieldType.Field as IEntityFieldType ).GetEditValueAsEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>() ); entityTypeEntityFilters.AddOrIgnore( metricPartitionEntityType.Id, entityId ); } } var entityTypeEntityUserPreferenceValue = entityTypeEntityFilters .Select( a => new { EntityTypeId = a.Key, EntityId = a.Value } ) .Select( a => string.Format( "{0}|{1}", a.EntityTypeId, a.EntityId ) ) .ToList().AsDelimited( "," ); gfMetricValues.SaveUserPreference( this.EntityTypeEntityPreferenceKey, entityTypeEntityUserPreferenceValue ); BindGrid(); }
/// <summary> /// Sets the hidden field values. /// </summary> private void SetHiddenFieldValues() { var rockContext = new RockContext(); // in case called normally int? metricId = PageParameter( "MetricId" ).AsIntegerOrNull(); // in case called from CategoryTreeView int? metricCategoryId = PageParameter( "MetricCategoryId" ).AsIntegerOrNull(); MetricCategory metricCategory = null; if ( metricCategoryId.HasValue ) { if ( metricCategoryId.Value > 0 ) { // editing a metric, but get the metricId from the metricCategory metricCategory = new MetricCategoryService( rockContext ).Get( metricCategoryId.Value ); if ( metricCategory != null ) { metricId = metricCategory.MetricId; } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricId.Value = metricId.ToString(); hfMetricCategoryId.Value = metricCategoryId.ToString(); gMetricValues.Actions.ShowAdd = false; gMetricValues.IsDeleteEnabled = false; if ( metricId.HasValue && metricId.Value > 0 ) { var metric = new MetricService( new RockContext() ).Get( metricId.Value ); if ( UserCanEdit || ( metric != null && metric.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) ) { // Block Security and special attributes (RockPage takes care of View) gMetricValues.Actions.ShowAdd = true; gMetricValues.IsDeleteEnabled = true; } } }
/// <summary> /// Creates the entity value lookups. /// </summary> /// <param name="metricID">The metric identifier.</param> private void CreateEntityValueLookups( int? metricID ) { Metric metric = new MetricService( new RockContext() ).Get( metricID ?? 0 ); if ( metric != null ) { var rockContext = new RockContext(); _entityTypeEntityNameLookup = new Dictionary<int, Dictionary<int, string>>(); _entityTypeEntityLookupQry = new Dictionary<int, IQueryable<IEntity>>(); foreach ( var metricPartition in metric.MetricPartitions.Where( a => a.EntityTypeId.HasValue ) ) { var entityTypeCache = EntityTypeCache.Read( metricPartition.EntityTypeId ?? 0 ); _entityTypeEntityNameLookup.AddOrIgnore( entityTypeCache.Id, new Dictionary<int, string>() ); _entityTypeEntityLookupQry.AddOrIgnore( entityTypeCache.Id, null ); if ( entityTypeCache != null ) { if ( entityTypeCache.GetEntityType() == typeof( Rock.Model.Group ) ) { _entityTypeEntityLookupQry[entityTypeCache.Id] = new GroupService( rockContext ).Queryable(); } else { Type[] modelType = { entityTypeCache.GetEntityType() }; Type genericServiceType = typeof( Rock.Data.Service<> ); Type modelServiceType = genericServiceType.MakeGenericType( modelType ); var serviceInstance = Activator.CreateInstance( modelServiceType, new object[] { rockContext } ) as IService; MethodInfo qryMethod = serviceInstance.GetType().GetMethod( "Queryable", new Type[] { } ); _entityTypeEntityLookupQry[entityTypeCache.Id] = qryMethod.Invoke( serviceInstance, new object[] { } ) as IQueryable<IEntity>; } } } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="metricId">The metric identifier.</param> /// <param name="parentCategoryId">The parent category id.</param> public void ShowDetail( int metricId, int? parentCategoryId ) { pnlDetails.Visible = false; var rockContext = new RockContext(); var metricService = new MetricService( rockContext ); Metric metric = null; if ( !metricId.Equals( 0 ) ) { metric = metricService.Get( metricId ); pdAuditDetails.SetEntity( metric, ResolveRockUrl( "~" ) ); } if ( metric == null ) { // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; metric = new Metric { Id = 0, IsSystem = false }; metric.SourceValueTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_MANUAL.AsGuid() ).Id; metric.MetricCategories = new List<MetricCategory>(); if ( parentCategoryId.HasValue ) { var metricCategory = new MetricCategory { CategoryId = parentCategoryId.Value }; metricCategory.Category = metricCategory.Category ?? new CategoryService( rockContext ).Get( metricCategory.CategoryId ); metric.MetricCategories.Add( metricCategory ); } metric.MetricPartitions = new List<MetricPartition>(); } if ( !metric.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) { return; } pnlDetails.Visible = true; hfMetricId.Value = metric.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( metric.IsSystem ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Metric.FriendlyTypeName ); } if ( !UserCanEdit && !metric.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit( Metric.FriendlyTypeName ); } bool canAdministrate = UserCanAdministrate || metric.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); if ( canAdministrate ) { btnSecurity.Visible = true; btnSecurity.Title = metric.Title; btnSecurity.EntityId = metric.Id; } else { btnSecurity.Visible = false; } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( metric ); } else { btnEdit.Visible = true; string errorMessage = string.Empty; btnDelete.Visible = metricService.CanDelete( metric, out errorMessage ); if ( metric.Id > 0 ) { ShowReadonlyDetails( metric ); } else { ShowEditDetails( metric ); } } }
/// <summary> /// Gets the metric values. /// </summary> /// <param name="isPrimary">if set to <c>true</c> [is primary].</param> /// <returns></returns> protected List<MetricValue> GetMetricValues( bool isPrimary ) { var rockContext = new RockContext(); var metricService = new MetricService( rockContext ); List<Guid> sourceGuids = null; var preKey = isPrimary ? string.Empty : "Comparison"; IQueryable<MetricValue> metricValues = null; var attributeValue = GetAttributeValue( preKey + "MetricSource" ); if ( string.IsNullOrWhiteSpace( attributeValue ) ) { attributeValue = string.Empty; } var pairs = MetricCategoriesFieldAttribute.GetValueAsGuidPairs( attributeValue ); sourceGuids = pairs.Select( p => p.MetricGuid ).ToList(); if ( sourceGuids.Any() ) { metricValues = metricService.GetByGuids( sourceGuids ).SelectMany( m => m.MetricValues ); } else { nbMetricWarning.Visible = true; pnlMetricDisplay.Visible = false; return null; } if ( GetAttributeValue( preKey + "RespectCampusContext" ).AsBoolean() ) { var campusContext = RockPage.GetCurrentContext( EntityTypeCache.Read( typeof( Campus ) ) ); if ( campusContext != null ) { metricValues = FilterMetricValuesByPartition( metricValues, "Campus", campusContext.Id ); } } if ( GetAttributeValue( preKey + "RespectGroupContext" ).AsBoolean() ) { var groupTypeContext = RockPage.GetCurrentContext( EntityTypeCache.Read( typeof( GroupType ) ) ); var groupContext = RockPage.GetCurrentContext( EntityTypeCache.Read( typeof( Group ) ) ); if ( groupContext != null ) { metricValues = FilterMetricValuesByPartition( metricValues, "Group", groupContext.Id ); } else if ( groupTypeContext != null ) { var groupTypeIds = new GroupTypeService( rockContext ).GetAllAssociatedDescendents( groupTypeContext.Id ).Select( gt => gt.Id ); var groupIds = new GroupService( rockContext ).Queryable().Where( g => groupTypeIds.Contains( g.GroupTypeId ) ).Select( g => g.Id ); metricValues = metricValues.Where( a => a.MetricValuePartitions.Any( mvp => mvp.MetricPartition.Label == "Group" && groupIds.Any( i => i == mvp.EntityId ) ) ); } } if ( GetAttributeValue( preKey + "RespectDateContext" ).AsBoolean() ) { var dateRangeString = RockPage.GetUserPreference( ContextPreferenceName ); if ( !string.IsNullOrWhiteSpace( dateRangeString ) ) { var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( dateRangeString ); metricValues = metricValues.Where( v => v.MetricValueDateTime >= dateRange.Start && v.MetricValueDateTime <= dateRange.End ); } } if ( GetAttributeValue( preKey + "RespectScheduleContext" ).AsBoolean() ) { var scheduleContext = RockPage.GetCurrentContext( EntityTypeCache.Read( typeof( Schedule ) ) ); if ( scheduleContext != null ) { metricValues = FilterMetricValuesByPartition( metricValues, "Schedule", scheduleContext.Id ); } } return metricValues.ToList(); }
/// <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 ( hfMetricId.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 MetricService metricService = new MetricService( new RockContext() ); Metric metric = metricService.Get( hfMetricId.Value.AsInteger() ); ShowReadonlyDetails( metric ); } }
/// <summary> /// Binds the metric filter. /// </summary> private void BindMetricFilter() { ddlMetricFilter.Items.Clear(); var metricList = new MetricService().Queryable().OrderBy( m => m.Title ).ToList(); foreach ( Metric metric in metricList ) { ddlMetricFilter.Items.Add( new ListItem( metric.Title, metric.Id.ToString() ) ); } }
/// <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 ) { MetricService metricService = new MetricService( new RockContext() ); Metric metric = metricService.Get( hfMetricId.Value.AsInteger() ); ShowEditDetails( metric ); }
/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { var metric = new Rock.Model.MetricService(new Rock.Data.RockContext()).Get(this.MetricId ?? 0); // setup Rest URL parameters if (metric != null) { RegisterJavaScriptForMetric(metric); } else { _hfRestUrlParams.Value = string.Empty; } var scriptFormat = new StringBuilder(); if (!string.IsNullOrWhiteSpace(DataSourceUrl)) { string restUrl = this.ResolveUrl(this.DataSourceUrl); _hfRestUrl.Value = restUrl; scriptFormat.Append(@" var restUrl_{0} = $('#{0} .js-rest-url').val() + $('#{0} .js-rest-url-params').val(); $.ajax({{ url: restUrl_{0}, dataType: 'json', contentType: 'application/json' }}) .done( function (chartData) {{ "); } else { scriptFormat.Append(@" $(function() {{ var chartData = {5}; "); } scriptFormat.Append(@" var chartOptions = {1}; var plotSelector = '#{0} .js-chart-placeholder'; var yaxisLabelText = $('#{0} .js-yaxis-value').val(); var getSeriesUrl = $('#{0} .js-seriesname-url').val(); var combineValues = {4}; "); if (this.GetType() == typeof(PieChart)) { scriptFormat.Append(@" Rock.controls.charts.plotPieChartData(chartData, chartOptions, plotSelector, getSeriesUrl); "); } else if (this.GetType() == typeof(BarChart)) { scriptFormat.Append(@" Rock.controls.charts.plotBarChartData(chartData, chartOptions, plotSelector, getSeriesUrl); "); } else { scriptFormat.Append(@" Rock.controls.charts.plotChartData(chartData, chartOptions, plotSelector, yaxisLabelText, getSeriesUrl, combineValues); "); } scriptFormat.Append(@" // plothover script (tooltip script) {2} // plotclick script {3} "); if (!string.IsNullOrWhiteSpace(DataSourceUrl)) { scriptFormat.Append(@" }}) .fail(function (jqXHR, textStatus, errorThrown) {{ //debugger "); } scriptFormat.Append(@" }}); "); string chartOptionsJson = JsonConvert.SerializeObject(this.Options, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }); _hbChartOptions.Text = "<div style='white-space: pre; max-height: 120px; overflow-y:scroll' Font-Names='Consolas' Font-Size='8'><br />" + chartOptionsJson + "</div>"; var seriesPartitionNameUrl = this.SeriesPartitionNameUrl; if (this.MetricId.HasValue) { seriesPartitionNameUrl = seriesPartitionNameUrl ?? "~/api/MetricValues/GetSeriesPartitionName/"; seriesPartitionNameUrl = this.ResolveUrl(seriesPartitionNameUrl.EnsureTrailingForwardslash() + this.MetricId + "/"); } if (!string.IsNullOrWhiteSpace(seriesPartitionNameUrl)) { _hfSeriesPartitionNameUrl.Value = seriesPartitionNameUrl; } else { _hfSeriesPartitionNameUrl.Value = null; } string tooltipScript = ShowTooltip ? string.Format("Rock.controls.charts.bindTooltip('{0}', {1})", this.ClientID, this.TooltipFormatter ?? "null") : null; string chartClickScript = GetChartClickScript(); string chartData = string.IsNullOrEmpty(ChartData) ? "[]" : ChartData; string script = string.Format( scriptFormat.ToString(), this.ClientID, // {0} chartOptionsJson, // {1} tooltipScript, // {2} chartClickScript, // {3} this.CombineValues.ToTrueFalse().ToLower(), // {4} chartData); // {5} ScriptManager.RegisterStartupScript(this, this.GetType(), "flot-chart-script_" + this.ClientID, script, true); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> private void ShowDetail( string itemKey, int itemKeyValue ) { if ( !itemKey.Equals( "metricId" ) ) { return; } Metric metric = null; if ( !itemKeyValue.Equals( 0 ) ) { metric = new MetricService().Get( itemKeyValue ); } else { metric = new Metric { Id = 0 }; } bool readOnly = false; if ( !IsUserAuthorized( "Edit" ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Metric.FriendlyTypeName ); } if ( !readOnly ) { lbEdit.Visible = true; if ( metric.Id > 0 ) { ShowReadOnly( metric ); } else { ShowEdit( metric ); } } else { lbEdit.Visible = false; ShowReadOnly( metric ); } lbSave.Visible = !readOnly; }
/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { drpDates.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); ddlGoalMeasure.Items.Clear(); ddlGoalMeasure.Items.Add( new ListItem( string.Empty, string.Empty ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Goal.ConvertToString(), MetricValueType.Goal.ConvertToInt().ToString() ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Measure.ConvertToString(), MetricValueType.Measure.ConvertToInt().ToString() ) ); ddlGoalMeasure.SelectedValue = gfMetricValues.GetUserPreference( "Goal/Measure" ); var metric = new MetricService( new RockContext() ).Get( hfMetricId.Value.AsInteger() ); var entityTypeEntityUserPreference = gfMetricValues.GetUserPreference( this.EntityTypeEntityPreferenceKey ) ?? string.Empty; var entityTypeEntityList = entityTypeEntityUserPreference.Split( ',' ).Select( a => a.Split( '|' ) ).Where( a => a.Length == 2 ).Select( a => new { EntityTypeId = a[0].AsIntegerOrNull(), EntityId = a[1].AsIntegerOrNull() } ).ToList(); if ( metric != null ) { foreach ( var metricPartition in metric.MetricPartitions ) { var metricPartitionEntityType = EntityTypeCache.Read( metricPartition.EntityTypeId ?? 0 ); var controlId = string.Format( "metricPartition{0}_entityTypeEditControl", metricPartition.Id ); Control entityTypeEditControl = phMetricValuePartitions.FindControl( controlId ); int? entityId = entityTypeEntityList.Where( a => a.EntityTypeId == metricPartition.EntityTypeId ).Select( a => a.EntityId ).FirstOrDefault(); if ( metricPartitionEntityType != null && metricPartitionEntityType.SingleValueFieldType != null && metricPartitionEntityType.SingleValueFieldType.Field is IEntityFieldType ) { ( metricPartitionEntityType.SingleValueFieldType.Field as IEntityFieldType ).SetEditValueFromEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>(), entityId ); } } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="metricValueId">The metric value identifier.</param> /// <param name="metricId">The metric identifier.</param> public void ShowDetail( int metricValueId, int? metricId ) { pnlDetails.Visible = true; // Load depending on Add(0) or Edit MetricValue metricValue = null; if ( !metricValueId.Equals( 0 ) ) { metricValue = new MetricValueService( new RockContext() ).Get( metricValueId ); lActionTitle.Text = ActionTitle.Edit( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle(); } if ( metricValue == null && metricId.HasValue ) { metricValue = new MetricValue { Id = 0, MetricId = metricId.Value }; metricValue.Metric = metricValue.Metric ?? new MetricService( new RockContext() ).Get( metricValue.MetricId ); lActionTitle.Text = ActionTitle.Add( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle(); } hfMetricValueId.Value = metricValue.Id.ToString(); LoadDropDowns(); ddlMetricValueType.SelectedValue = metricValue.MetricValueType.ConvertToInt().ToString(); tbXValue.Text = metricValue.XValue; tbYValue.Text = metricValue.YValue.ToString(); hfMetricId.Value = metricValue.MetricId.ToString(); tbNote.Text = metricValue.Note; dpMetricValueDateTime.SelectedDateTime = metricValue.MetricValueDateTime; var metricEntityType = EntityTypeCache.Read( metricValue.Metric.EntityTypeId ?? 0 ); // Setup EntityType UI controls Control entityTypeEditControl = null; if ( metricEntityType != null && metricEntityType.SingleValueFieldType != null ) { hfSingleValueFieldTypeId.Value = metricEntityType.SingleValueFieldType.Id.ToString(); FieldTypeCache fieldType = FieldTypeCache.Read( hfSingleValueFieldTypeId.Value.AsInteger() ); entityTypeEditControl = fieldType.Field.EditControl( new Dictionary<string, Rock.Field.ConfigurationValue>(), "entityTypeEditControl" ); if ( entityTypeEditControl is IRockControl ) { ( entityTypeEditControl as IRockControl ).Label = fieldType.Name; } phEntityTypeEntityIdValue.Controls.Add( entityTypeEditControl ); IEntityFieldType entityFieldType = metricEntityType.SingleValueFieldType.Field as IEntityFieldType; if ( entityFieldType != null ) { entityFieldType.SetEditValueFromEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>(), metricValue.EntityId ); } } // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; bool canEdit = UserCanEdit; if ( !canEdit && metricId.HasValue && metricId.Value > 0 ) { var metric = new MetricService( new RockContext() ).Get( metricId.Value ); if ( metric != null && metric.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { canEdit = true; } } if ( !canEdit ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( MetricValue.FriendlyTypeName ); } if ( readOnly ) { lActionTitle.Text = ActionTitle.View( MetricValue.FriendlyTypeName ); btnCancel.Text = "Close"; } ddlMetricValueType.Enabled = !readOnly; tbXValue.ReadOnly = readOnly; tbYValue.ReadOnly = readOnly; tbNote.ReadOnly = readOnly; dpMetricValueDateTime.Enabled = !readOnly; if ( entityTypeEditControl is WebControl ) { ( entityTypeEditControl as WebControl ).Enabled = !readOnly; } btnSave.Visible = !readOnly; }
/// <summary> /// Handles the Click event of the lbEdit 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 lbEdit_Click( object sender, EventArgs e ) { var metricService = new MetricService(); var metric = metricService.Get( hfMetricId.ValueAsInt() ); ShowEdit( metric ); }
/// <summary> /// Gets the primary partition entity identifier from context. /// </summary> /// <returns></returns> private MetricPartitionEntityId GetPrimaryMetricPartitionEntityIdFromContext() { EntityTypeCache entityTypeCache = null; MetricPartitionEntityId result = new MetricPartitionEntityId(); if ( this.MetricId.HasValue ) { using ( var rockContext = new Rock.Data.RockContext() ) { var metric = new Rock.Model.MetricService( rockContext ).Get( this.MetricId ?? 0 ); if ( metric != null ) { // for backwards compatibily, get the first metric partition result.MetricPartition = metric.MetricPartitions.OrderBy( a => a.Order ).First(); entityTypeCache = EntityTypeCache.Read( result.MetricPartition.EntityTypeId ?? 0 ); } } } if ( entityTypeCache != null && this.ContextEntity( entityTypeCache.Name ) != null ) { result.EntityId = this.ContextEntity( entityTypeCache.Name ).Id; } // if Getting the EntityFromContext, and we didn't get it from ContextEntity, get it from the Page Param if ( !result.EntityId.HasValue ) { // figure out what the param name should be ("CampusId, GroupId, etc") depending on metric's entityType var entityParamName = "EntityId"; if ( entityTypeCache != null ) { entityParamName = entityTypeCache.Name + "Id"; } result.EntityId = this.PageParameter( entityParamName ).AsIntegerOrNull(); } return result; }
/// <summary> /// Handles the Click event of the lbSave 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 lbSave_Click( object sender, EventArgs e ) { using ( new Rock.Data.UnitOfWorkScope() ) { int metricId = hfMetricId.ValueAsInt(); var metricService = new MetricService(); Metric metric = null; if ( metricId == 0 ) { metric = new Metric(); metric.IsSystem = false; metricService.Add( metric, CurrentPersonId ); } else { metric = metricService.Get( metricId ); } metric.Category = tbCategory.Text; metric.Title = tbTitle.Text; metric.Subtitle = tbSubtitle.Text; metric.Description = tbDescription.Text; metric.MinValue = tbMinValue.Text.AsType<int?>(); metric.MaxValue = tbMaxValue.Text.AsType<int?>(); metric.Type = cbType.Checked; metric.CollectionFrequencyValueId = Int32.Parse( ddlCollectionFrequency.SelectedValue ); metric.Source = tbSource.Text; metric.SourceSQL = tbSourceSQL.Text; if ( !metric.IsValid ) { // Controls will render the error messages return; } metricService.Save( metric, CurrentPersonId ); hfMetricId.SetValue( metric.Id ); } var savedMetric = new MetricService().Get( hfMetricId.ValueAsInt() ); ShowReadOnly( savedMetric ); }
/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { var metric = new Rock.Model.MetricService( new Rock.Data.RockContext() ).Get( this.MetricId ?? 0 ); if ( string.IsNullOrWhiteSpace( this.XAxisLabel ) && metric != null ) { // if XAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.XAxisLabel this.XAxisLabel = metric.XAxisLabel; } if ( string.IsNullOrWhiteSpace( this.YAxisLabel ) && metric != null ) { // if YAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.YAxisLabel this.YAxisLabel = metric.YAxisLabel; } // setup Rest URL parameters if ( this.MetricId.HasValue ) { _hfRestUrlParams.Value = string.Format( "{0}", this.MetricId ); List<string> filterParams = new List<string>(); List<string> qryParams = new List<string>(); if ( this.StartDate.HasValue ) { filterParams.Add( string.Format( "MetricValueDateTime ge DateTime'{0}'", this.StartDate.Value.ToString( "o" ) ) ); } if ( this.EndDate.HasValue ) { filterParams.Add( string.Format( "MetricValueDateTime lt DateTime'{0}'", this.EndDate.Value.ToString( "o" ) ) ); } if ( this.MetricValueType.HasValue ) { // MetricValueType is an enum, which isn't quite supported for $filters as of Web Api 2.1, so pass it as a regular rest param instead of as part of the odata $filter qryParams.Add( string.Format( "metricValueType={0}", this.MetricValueType ) ); } if ( this.EntityId.HasValue ) { filterParams.Add( string.Format( "(EntityId eq {0} or EntityId eq null)", this.EntityId ) ); } if ( filterParams.Count > 0 ) { qryParams.Add( "$filter=" + filterParams.AsDelimited( " and " ) ); } _hfRestUrlParams.Value += "?" + qryParams.AsDelimited( "&" ); } else { _hfRestUrlParams.Value = string.Empty; } string scriptFormat = @" var restUrl_{0} = $('#{0} .js-rest-url').val() + $('#{0} .js-rest-url-params').val(); $.ajax({{ url: restUrl_{0}, dataType: 'json', contentType: 'application/json' }}) .done( function (chartData) {{ var chartOptions = {1}; var plotSelector = '#{0} .js-chart-placeholder'; var yaxisLabelText = $('#{0} .js-yaxis-value').val(); var getSeriesUrl = $('#{0} .js-seriesname-url').val(); var combineValues = {4}; "; if ( this.GetType() == typeof( PieChart ) ) { scriptFormat += @" Rock.controls.charts.plotPieChartData(chartData, chartOptions, plotSelector); "; } else { scriptFormat += @" Rock.controls.charts.plotChartData(chartData, chartOptions, plotSelector, yaxisLabelText, getSeriesUrl, combineValues); "; } scriptFormat += @" // plothover script (tooltip script) {2} // plotclick script {3} }}) .fail(function (jqXHR, textStatus, errorThrown) {{ //debugger }}); "; string chartOptionsJson = JsonConvert.SerializeObject( this.Options, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore } ); _hbChartOptions.Text = "<div style='white-space: pre; max-height: 120px; overflow-y:scroll' Font-Names='Consolas' Font-Size='8'><br />" + chartOptionsJson + "</div>"; string restUrl = this.ResolveUrl( this.DataSourceUrl ); _hfRestUrl.Value = restUrl; var seriesNameUrl = this.SeriesNameUrl; if ( this.MetricId.HasValue ) { seriesNameUrl = seriesNameUrl ?? "~/api/MetricValues/GetSeriesName/"; } if ( !string.IsNullOrWhiteSpace( seriesNameUrl ) ) { _hfSeriesNameUrl.Value = this.ResolveUrl( seriesNameUrl.EnsureTrailingForwardslash() + this.MetricId + "/" ); } else { _hfSeriesNameUrl.Value = null; } string tooltipScript = ShowTooltip ? string.Format( "Rock.controls.charts.bindTooltip('{0}', {1})", this.ClientID, this.TooltipFormatter ?? "null" ) : null; string chartClickScript = GetChartClickScript(); string script = string.Format( scriptFormat, this.ClientID, // {0} chartOptionsJson, // {1} tooltipScript, // {2} chartClickScript, // {3} this.CombineValues.ToTrueFalse().ToLower() ); // {4} ScriptManager.RegisterStartupScript( this, this.GetType(), "flot-chart-script_" + this.ClientID, script, true ); }
public string GetHtmlForBlock( int blockId, int? entityTypeId = null, int? entityId = null ) { RockContext rockContext = this.Service.Context as RockContext ?? new RockContext(); Block block = new BlockService( rockContext ).Get( blockId ); if ( block != null ) { block.LoadAttributes(); string liquidTemplate = block.GetAttributeValue( "LiquidTemplate" ); var metricCategoryPairList = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs( block.GetAttributeValue( "MetricCategories" ) ); var metricGuids = metricCategoryPairList.Select( a => a.MetricGuid ).ToList(); bool roundYValues = block.GetAttributeValue( "RoundValues" ).AsBooleanOrNull() ?? true; MetricService metricService = new MetricService( rockContext ); var metrics = metricService.GetByGuids( metricGuids ); List<object> metricsData = new List<object>(); if ( metrics.Count() == 0 ) { return @"<div class='alert alert-warning'> Please select a metric in the block settings. </div>"; } MetricValueService metricValueService = new MetricValueService( rockContext ); DateTime firstDayOfYear = new DateTime( RockDateTime.Now.Year, 1, 1 ); DateTime currentDateTime = RockDateTime.Now; DateTime firstDayOfNextYear = new DateTime( RockDateTime.Now.Year + 1, 1, 1 ); foreach ( var metric in metrics ) { var metricYTDData = JsonConvert.DeserializeObject( metric.ToJson(), typeof( MetricYTDData ) ) as MetricYTDData; var qryMeasureValues = metricValueService.Queryable() .Where( a => a.MetricId == metricYTDData.Id ) .Where( a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < currentDateTime ) .Where( a => a.MetricValueType == MetricValueType.Measure ); //// if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId //// Note: if a Metric or it's Metric Value doesn't have a context, include it regardless of Context setting if ( entityTypeId.HasValue && ( metric.EntityTypeId == entityTypeId || metric.EntityTypeId == null ) ) { if ( entityId.HasValue ) { qryMeasureValues = qryMeasureValues.Where( a => a.EntityId == entityId || a.EntityId == null ); } } var lastMetricValue = qryMeasureValues.OrderByDescending( a => a.MetricValueDateTime ).FirstOrDefault(); if ( lastMetricValue != null ) { metricYTDData.LastValue = lastMetricValue.YValue.HasValue ? Math.Round( lastMetricValue.YValue.Value, roundYValues ? 0 : 2 ) : (decimal?)null; metricYTDData.LastValueDate = lastMetricValue.MetricValueDateTime.HasValue ? lastMetricValue.MetricValueDateTime.Value.Date : DateTime.MinValue; } decimal? sum = qryMeasureValues.Sum( a => a.YValue ); metricYTDData.CumulativeValue = sum.HasValue ? Math.Round( sum.Value, roundYValues ? 0 : 2 ) : (decimal?)null; // figure out goal as of current date time by figuring out the slope of the goal var qryGoalValuesCurrentYear = metricValueService.Queryable() .Where( a => a.MetricId == metricYTDData.Id ) .Where( a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < firstDayOfNextYear ) .Where( a => a.MetricValueType == MetricValueType.Goal ); // if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId if ( entityTypeId.HasValue && metric.EntityTypeId == entityTypeId ) { if ( entityId.HasValue ) { qryGoalValuesCurrentYear = qryGoalValuesCurrentYear.Where( a => a.EntityId == entityId ); } } MetricValue goalLineStartPoint = qryGoalValuesCurrentYear.Where( a => a.MetricValueDateTime <= currentDateTime ).OrderByDescending( a => a.MetricValueDateTime ).FirstOrDefault(); MetricValue goalLineEndPoint = qryGoalValuesCurrentYear.Where( a => a.MetricValueDateTime >= currentDateTime ).FirstOrDefault(); if ( goalLineStartPoint != null && goalLineEndPoint != null ) { var changeInX = goalLineEndPoint.DateTimeStamp - goalLineStartPoint.DateTimeStamp; var changeInY = goalLineEndPoint.YValue - goalLineStartPoint.YValue; if ( changeInX != 0 ) { decimal? slope = changeInY / changeInX; decimal goalValue = ( ( slope * ( currentDateTime.ToJavascriptMilliseconds() - goalLineStartPoint.DateTimeStamp ) ) + goalLineStartPoint.YValue ).Value; metricYTDData.GoalValue = Math.Round( goalValue, roundYValues ? 0 : 2 ); } } else { // if there isn't a both a start goal and end goal within the date range, there wouldn't be a goal line shown in a line chart, so don't display a goal in liquid either metricYTDData.GoalValue = null; } metricsData.Add( metricYTDData.ToLiquid() ); } Dictionary<string, object> mergeValues = new Dictionary<string, object>(); mergeValues.Add( "Metrics", metricsData ); string resultHtml = liquidTemplate.ResolveMergeFields( mergeValues ); // show liquid help for debug if ( block.GetAttributeValue( "EnableDebug" ).AsBoolean() ) { resultHtml += mergeValues.lavaDebugInfo(); } return resultHtml; } return string.Format( @"<div class='alert alert-danger'> unable to find block_id: {1} </div>", blockId ); }
/// <summary> /// Shows the edit modal. /// </summary> /// <param name="valueId">The value unique identifier.</param> protected void ShowEdit( int valueId ) { var metricId = hfMetricId.ValueAsInt(); var metric = new MetricService().Get( metricId ); MetricValue metricValue = null; if ( !valueId.Equals( 0 ) ) { metricValue = new MetricValueService().Get( valueId ); if ( metric != null ) { lActionTitle.Text = ActionTitle.Edit( "metric value for " + metric.Title ); } } else { metricValue = new MetricValue { Id = 0 }; metricValue.MetricId = metricId; if ( metric != null ) { lActionTitle.Text = ActionTitle.Add( "metric value for " + metric.Title ); } } hfMetricValueId.SetValue( metricValue.Id ); ddlMetricFilter.SelectedValue = hfMetricId.Value; tbValue.Text = metricValue.Value; tbValueDescription.Text = metricValue.Description; tbXValue.Text = metricValue.xValue; tbLabel.Text = metricValue.Label; cbIsDateBased.Checked = metricValue.isDateBased; mdValueDialog.Show(); }
/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { var metric = new Rock.Model.MetricService(new Rock.Data.RockContext()).Get(this.MetricId ?? 0); if (string.IsNullOrWhiteSpace(this.XAxisLabel) && metric != null) { // if XAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.XAxisLabel this.XAxisLabel = metric.XAxisLabel; } if (string.IsNullOrWhiteSpace(this.YAxisLabel) && metric != null) { // if YAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.YAxisLabel this.YAxisLabel = metric.YAxisLabel; } // setup Rest URL parameters if (this.MetricId.HasValue) { _hfRestUrlParams.Value = string.Format("{0}", this.MetricId); List <string> filterParams = new List <string>(); List <string> qryParams = new List <string>(); if (this.StartDate.HasValue) { filterParams.Add(string.Format("MetricValueDateTime ge DateTime'{0}'", this.StartDate.Value.ToString("o"))); } if (this.EndDate.HasValue) { filterParams.Add(string.Format("MetricValueDateTime lt DateTime'{0}'", this.EndDate.Value.ToString("o"))); } if (this.MetricValueType.HasValue) { // MetricValueType is an enum, which isn't quite supported for $filters as of Web Api 2.1, so pass it as a regular rest param instead of as part of the odata $filter qryParams.Add(string.Format("metricValueType={0}", this.MetricValueType)); } if (this.EntityId.HasValue) { filterParams.Add(string.Format("(EntityId eq {0} or EntityId eq null)", this.EntityId)); } if (filterParams.Count > 0) { qryParams.Add("$filter=" + filterParams.AsDelimited(" and ")); } _hfRestUrlParams.Value += "?" + qryParams.AsDelimited("&"); } else { _hfRestUrlParams.Value = string.Empty; } string scriptFormat = @" var restUrl_{0} = $('#{0} .js-rest-url').val() + $('#{0} .js-rest-url-params').val(); $.ajax({{ url: restUrl_{0}, dataType: 'json', contentType: 'application/json' }}) .done( function (chartData) {{ var chartOptions = {1}; var plotSelector = '#{0} .js-chart-placeholder'; var yaxisLabelText = $('#{0} .js-yaxis-value').val(); var getSeriesUrl = $('#{0} .js-seriesname-url').val(); var combineValues = {4}; "; if (this.GetType() == typeof(PieChart)) { scriptFormat += @" Rock.controls.charts.plotPieChartData(chartData, chartOptions, plotSelector); "; } else { scriptFormat += @" Rock.controls.charts.plotChartData(chartData, chartOptions, plotSelector, yaxisLabelText, getSeriesUrl, combineValues); "; } scriptFormat += @" // plothover script (tooltip script) {2} // plotclick script {3} }}) .fail(function (jqXHR, textStatus, errorThrown) {{ //debugger }}); "; string chartOptionsJson = JsonConvert.SerializeObject(this.Options, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }); _hbChartOptions.Text = "<div style='white-space: pre; max-height: 120px; overflow-y:scroll' Font-Names='Consolas' Font-Size='8'><br />" + chartOptionsJson + "</div>"; string restUrl = this.ResolveUrl(this.DataSourceUrl); _hfRestUrl.Value = restUrl; var seriesNameUrl = this.SeriesNameUrl; if (this.MetricId.HasValue) { seriesNameUrl = seriesNameUrl ?? "~/api/MetricValues/GetSeriesName/"; } if (!string.IsNullOrWhiteSpace(seriesNameUrl)) { _hfSeriesNameUrl.Value = this.ResolveUrl(seriesNameUrl.EnsureTrailingForwardslash() + this.MetricId + "/"); } else { _hfSeriesNameUrl.Value = null; } string tooltipScript = ShowTooltip ? string.Format("Rock.controls.charts.bindTooltip('{0}', {1})", this.ClientID, this.TooltipFormatter ?? "null") : null; string chartClickScript = GetChartClickScript(); string script = string.Format( scriptFormat, this.ClientID, // {0} chartOptionsJson, // {1} tooltipScript, // {2} chartClickScript, // {3} this.CombineValues.ToTrueFalse().ToLower()); // {4} ScriptManager.RegisterStartupScript(this, this.GetType(), "flot-chart-script_" + this.ClientID, script, true); }