/// <summary> /// Handles the SelectItem event of the mpMetricCategoryPicker 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 mpMetricCategoryPicker_SelectItem(object sender, EventArgs e) { var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService(new RockContext()).Get(metricCategoryId ?? 0); CreateDynamicControls(metricCategory != null ? metricCategory.MetricId : (int?)null); }
/// <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) { // create dynamic controls var rockContext = new RockContext(); var metricValue = new MetricValueService(rockContext).Get(hfMetricValueId.Value.AsInteger()); if (metricValue == null) { metricValue = new MetricValue { MetricId = hfMetricId.Value.AsInteger() }; metricValue.Metric = new MetricService(rockContext).Get(metricValue.MetricId); } CreateDynamicControls(metricValue, false, false); } if (!Page.IsPostBack) { int?metricValueId = PageParameter("MetricValueId").AsIntegerOrNull(); // in case called with MetricId as the parent id parameter int?metricId = PageParameter("MetricId").AsIntegerOrNull(); // in case called with MetricCategoryId as the parent id parameter 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(new RockContext()).Get(metricCategoryId.Value); if (metricCategory != null) { metricId = metricCategory.MetricId; } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricCategoryId.Value = metricCategoryId.ToString(); if (metricValueId.HasValue) { ShowDetail(metricValueId.Value, metricId); } else { pnlDetails.Visible = false; } } }
/// <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(); }
/// <summary> /// Sets the value. /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="value">The value.</param> public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value) { if (value != null) { var picker = control as MetricCategoryPicker; if (picker != null) { List <MetricCategory> metricCategories = new List <MetricCategory>(); var guidPairs = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs(value); MetricCategoryService metricCategoryService = new MetricCategoryService(new RockContext()); foreach (var guidPair in guidPairs) { // first try to get each metric from the category that it was selected from var metricCategory = metricCategoryService.Queryable().Where(a => a.Metric.Guid == guidPair.MetricGuid && a.Category.Guid == guidPair.CategoryGuid).FirstOrDefault(); if (metricCategory == null) { // if the metric isn't found in the original category, just the first one, ignoring category metricCategory = metricCategoryService.Queryable().Where(a => a.Metric.Guid == guidPair.MetricGuid).FirstOrDefault(); } if (metricCategory != null) { metricCategories.Add(metricCategory); } } picker.SetValues(metricCategories); } } }
/// <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) { // create dynamic controls FieldTypeCache fieldType = FieldTypeCache.Read(hfSingleValueFieldTypeId.Value.AsInteger()); if (fieldType != null) { var entityTypeEditControl = fieldType.Field.EditControl(new Dictionary <string, Rock.Field.ConfigurationValue>(), "entityTypeEditControl"); phEntityTypeEntityIdValue.Controls.Add(entityTypeEditControl); if (entityTypeEditControl is IRockControl) { (entityTypeEditControl as IRockControl).Label = fieldType.Name; } } } if (!Page.IsPostBack) { int?metricValueId = PageParameter("MetricValueId").AsIntegerOrNull(); // in case called with MetricId as the parent id parameter int?metricId = PageParameter("MetricId").AsIntegerOrNull(); // in case called with MetricCategoryId as the parent id parameter 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(new RockContext()).Get(metricCategoryId.Value); if (metricCategory != null) { metricId = metricCategory.MetricId; } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricCategoryId.Value = metricCategoryId.ToString(); if (metricValueId.HasValue) { ShowDetail(metricValueId.Value, metricId); } else { pnlDetails.Visible = false; } } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( Page.IsPostBack ) { // create dynamic controls FieldTypeCache fieldType = FieldTypeCache.Read( hfSingleValueFieldTypeId.Value.AsInteger() ); if ( fieldType != null ) { var entityTypeEditControl = fieldType.Field.EditControl( new Dictionary<string, Rock.Field.ConfigurationValue>(), "entityTypeEditControl" ); phEntityTypeEntityIdValue.Controls.Add( entityTypeEditControl ); if ( entityTypeEditControl is IRockControl ) { ( entityTypeEditControl as IRockControl ).Label = fieldType.Name; } } } if ( !Page.IsPostBack ) { int? itemId = PageParameter( "MetricValueId" ).AsIntegerOrNull(); // in case called with MetricId as the parent id parameter int? metricId = PageParameter( "MetricId" ).AsIntegerOrNull(); // in case called with MetricCategoryId as the parent id parameter 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( new RockContext() ).Get( metricCategoryId.Value ); if ( metricCategory != null ) { metricId = metricCategory.MetricId; } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricCategoryId.Value = metricCategoryId.ToString(); if ( itemId.HasValue ) { ShowDetail( "MetricValueId", itemId.Value, metricId ); } else { pnlDetails.Visible = false; } } }
/// <summary> /// Handles the SelectedIndexChanged event of the rblSelectOrContext control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void rblSelectOrContext_SelectedIndexChanged(object sender, EventArgs e) { phMetricValuePartitions.Visible = rblSelectOrContext.SelectedValue == "0"; var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService(new RockContext()).Get(metricCategoryId ?? 0); CreateDynamicControls(metricCategory != null ? metricCategory.MetricId : (int?)null); }
/// <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) { // in case called normally int?metricId = PageParameter("MetricId").AsInteger(false); // in case called from CategoryTreeView int? metricCategoryId = PageParameter("MetricCategoryId").AsInteger(false); MetricCategory metricCategory = null; if (metricCategoryId.HasValue) { if (metricCategoryId.Value > 0) { // editing a metric, but get the metricId from the metricCategory metricCategory = new MetricCategoryService(new RockContext()).Get(metricCategoryId.Value); if (metricCategory != null) { hfMetricCategoryId.Value = metricCategory.Id.ToString(); metricId = metricCategory.MetricId; } } else { if (!metricId.HasValue) { // adding a new metric metricId = 0; } } } int?parentCategoryId = PageParameter("ParentCategoryId").AsInteger(false); if (metricId.HasValue) { if (parentCategoryId.HasValue) { ShowDetail("MetricId", metricId.Value, parentCategoryId); } else { ShowDetail("MetricId", metricId.Value); } } else { pnlDetails.Visible = false; } } }
/// <summary> /// Sets the hidden field values. /// </summary> private void SetHiddenFieldValues() { var rockContext = new RockContext(); // in case called normally int?metricId = PageParameter("MetricId").AsIntegerOrNull(); hfEntityTypeName.Value = string.Empty; // 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; if (metricCategory.Metric != null && metricCategory.Metric.EntityType != null) { hfEntityTypeName.Value = metricCategory.Metric.EntityType.FriendlyName; } } } 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> /// Binds the grid. /// </summary> private void BindGrid() { MetricValueService metricValueService = new MetricValueService(new RockContext()); SortProperty sortProperty = gMetricValues.SortProperty; var qry = metricValueService.Queryable(); // in case called normally int?metricId = PageParameter("MetricId").AsInteger(false); // in case called from CategoryTreeView int? metricCategoryId = PageParameter("MetricCategoryId").AsInteger(false); MetricCategory metricCategory = null; if (metricCategoryId.HasValue) { if (metricCategoryId.Value > 0) { // editing a metric, but get the metricId from the metricCategory metricCategory = new MetricCategoryService(new 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(); this.Visible = metricId.HasValue; qry = qry.Where(a => a.MetricId == metricId); if (sortProperty != null) { gMetricValues.DataSource = qry.Sort(sortProperty).ToList(); } else { gMetricValues.DataSource = qry.OrderBy(s => s.Order).ThenBy(s => s.XValue).ThenBy(s => s.MetricValueDateTime).ThenBy(s => s.YValue).ToList(); } gMetricValues.DataBind(); }
/// <summary> /// Handles the SaveClick event of the mdEdit 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 mdEdit_SaveClick(object sender, EventArgs e) { var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService(new RockContext()).Get(metricCategoryId ?? 0); Guid?metricGuid = metricCategory != null ? metricCategory.Metric.Guid : (Guid?)null; Guid?metricCategoryGuid = metricCategory != null ? metricCategory.Category.Guid : (Guid?)null;; // NOTE: Weird storage due to backwards compatible // value stored as pipe delimited: Metric (as Guid) | EntityId (leave null) | GetEntityFromContextEnabled | CombineValues | Metric's Category (as Guid) var metricAttributeValue = string.Format("{0}|{1}|{2}|{3}|{4}", metricGuid, null, rblSelectOrContext.SelectedValue == "1", cbCombineValues.Checked, metricCategoryGuid); SetAttributeValue("Metric", metricAttributeValue); var entityTypeEntityFilters = new List <string>(); if (metricCategory != null) { foreach (var metricPartition in metricCategory.Metric.MetricPartitions.OrderBy(a => a.Order)) { var metricPartitionEntityType = EntityTypeCache.Get(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.Add(string.Format("{0}|{1}", metricPartitionEntityType.Id, entityId)); } } } string metricEntityTypeEntityIdsValue = entityTypeEntityFilters.ToList().AsDelimited(","); SetAttributeValue("MetricEntityTypeEntityIds", metricEntityTypeEntityIdsValue); SetAttributeValue("SlidingDateRange", drpSlidingDateRange.DelimitedValues); SaveAttributeValues(); mdEdit.Hide(); pnlEditModel.Visible = false; LoadChart(); }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues) { var picker = control as MetricCategoryPicker; string result = null; if (picker != null) { var ids = picker.SelectedValuesAsInt(); var metricCategories = new MetricCategoryService(new RockContext()).Queryable().Where(a => ids.Contains(a.Id)); if (metricCategories.Any()) { var guidPairList = metricCategories.Select(a => new { MetricGuid = a.Metric.Guid, CategoryGuid = a.Category.Guid }).ToList(); result = guidPairList.Select(s => string.Format("{0}|{1}", s.MetricGuid, s.CategoryGuid)).ToList().AsDelimited(","); } } return(result); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { var dataMap = context.JobDetail.JobDataMap; _rockContext = new RockContext(); var groupTypeService = new GroupTypeService(_rockContext); _metricService = new MetricService(_rockContext); _metricCategoryService = new MetricCategoryService(_rockContext); _categoryService = new CategoryService(_rockContext); _categoryEntityTypeId = EntityTypeCache.GetId(typeof(MetricCategory)); var rootcategoryCategoryGuid = dataMap.GetString("headcountcategory").AsGuid(); var rootCategory = new CategoryService(_rockContext).Get(rootcategoryCategoryGuid); if (rootCategory == null) { throw new Exception("No root category found to store the headcount metrics in."); } _checkInTemplateId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE).Id; var startingGroupTypes = groupTypeService.Queryable().Where(g => g.GroupTypePurposeValueId == _checkInTemplateId).ToList(); if (!startingGroupTypes.Any()) { return; } foreach (var groupType in startingGroupTypes) { _seenGroupTypeIds.Add(groupType.Id); var descendentGroupTypes = groupType.ChildGroupTypes.Where(cgt => !_seenGroupTypeIds.Contains(cgt.Id)).ToList(); if (descendentGroupTypes.Any()) { ProcessDescendents(descendentGroupTypes, rootCategory); } } _rockContext.SaveChanges(); }
/// <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); }
public IQueryable <CategoryItem> GetMetricChildren(int id, string includedCategoryIds = "") { // Get list of categorized MetricCategory objects from GetChildren(). var metricCategories = GetChildren( id: id, rootCategoryId: 0, getCategorizedItems: true, entityTypeId: EntityTypeCache.Get <MetricCategory>().Id, includedCategoryIds: includedCategoryIds ).ToList(); var metricCategoryService = new MetricCategoryService(new RockContext()); var convertedMetrics = new List <CategoryItem>(); // Translate from MetricCategory to Metric. foreach (var categoryItem in metricCategories) { if (!categoryItem.IsCategory) { // Load the MetricCategory. var metricCategory = metricCategoryService.Get(categoryItem.Id.AsInteger()); if (metricCategory != null) { // Swap the Id to the Metric Id (instead of MetricCategory.Id). categoryItem.Id = metricCategory.MetricId.ToString(); } } categoryItem.Children = new List <Web.UI.Controls.TreeViewItem>(); categoryItem.Children.AddRange(GetAllMetricDescendants(categoryItem, includedCategoryIds, metricCategoryService)); convertedMetrics.Add(categoryItem); } return(convertedMetrics.AsQueryable()); }
/// <summary> /// Handles the SelectItem event of the mpMetricCategoryPicker 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 mpMetricCategoryPicker_SelectItem( object sender, EventArgs e ) { var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService( new RockContext() ).Get( metricCategoryId ?? 0 ); CreateDynamicControls( metricCategory != null ? metricCategory.MetricId : (int?)null ); }
/// <summary> /// Handles the SaveClick event of the mdEdit 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 mdEdit_SaveClick( object sender, EventArgs e ) { var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService( new RockContext() ).Get( metricCategoryId ?? 0 ); Guid? metricGuid = metricCategory != null ? metricCategory.Metric.Guid : (Guid?)null; Guid? metricCategoryGuid = metricCategory != null ? metricCategory.Category.Guid : (Guid?)null; ; // NOTE: Weird storage due to backwards compatible // value stored as pipe delimited: Metric (as Guid) | EntityId (leave null) | GetEntityFromContextEnabled | CombineValues | Metric's Category (as Guid) var metricAttributeValue = string.Format( "{0}|{1}|{2}|{3}|{4}", metricGuid, null, rblSelectOrContext.SelectedValue == "1", cbCombineValues.Checked, metricCategoryGuid ); SetAttributeValue( "Metric", metricAttributeValue ); var entityTypeEntityFilters = new List<string>(); if ( metricCategory != null ) { foreach ( var metricPartition in metricCategory.Metric.MetricPartitions.OrderBy( a => a.Order ) ) { 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.Add( string.Format( "{0}|{1}", metricPartitionEntityType.Id, entityId ) ); } } } string metricEntityTypeEntityIdsValue = entityTypeEntityFilters.ToList().AsDelimited( "," ); SetAttributeValue( "MetricEntityTypeEntityIds", metricEntityTypeEntityIdsValue ); SetAttributeValue( "SlidingDateRange", drpSlidingDateRange.DelimitedValues); SaveAttributeValues(); mdEdit.Hide(); pnlEditModel.Visible = false; LoadChart(); }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues ) { var picker = control as MetricCategoryPicker; string result = null; if ( picker != null ) { var ids = picker.SelectedValuesAsInt(); var metricCategories = new MetricCategoryService( new RockContext() ).Queryable().Where( a => ids.Contains( a.Id ) ); if ( metricCategories.Any() ) { var guidPairList = metricCategories.Select( a => new { MetricGuid = a.Metric.Guid, CategoryGuid = a.Category.Guid } ).ToList(); result = guidPairList.Select( s => string.Format( "{0}|{1}", s.MetricGuid, s.CategoryGuid ) ).ToList().AsDelimited( "," ); } } return result; }
/// <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> /// Sets the value on select. /// </summary> protected override void SetValueOnSelect() { var metricCategory = new MetricCategoryService(new RockContext()).Get(int.Parse(ItemId)); SetValue(metricCategory); }
/// <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> /// Shows the settings. /// </summary> protected void ShowSettings() { flotChart.Visible = false; pnlEditModel.Visible = true; var rockContext = new RockContext(); var metricCategoryService = new MetricCategoryService(rockContext); MetricCategory metricCategory = null; if (this.MetricId.HasValue) { metricCategory = metricCategoryService.Queryable().Where(a => a.MetricId == this.MetricId).FirstOrDefault(); mpMetricCategoryPicker.SetValue(metricCategory); } if (this.GetEntityFromContextEnabled) { rblSelectOrContext.SetValue("1"); } else { rblSelectOrContext.SetValue("0"); } cbCombineValues.Checked = this.CombineValues; rblSelectOrContext_SelectedIndexChanged(null, null); if (metricCategory != null) { var entityTypeEntityIds = (GetAttributeValue("MetricEntityTypeEntityIds") ?? string.Empty).Split(',').Select(a => a.Split('|')).Where(a => a.Length == 2).Select(a => new { EntityTypeId = a[0].AsIntegerOrNull(), EntityId = a[1].AsIntegerOrNull() }).ToList(); int position = 0; foreach (var metricPartition in metricCategory.Metric.MetricPartitions.OrderBy(a => a.Order)) { var metricPartitionEntityType = EntityTypeCache.Get(metricPartition.EntityTypeId ?? 0); var controlId = string.Format("metricPartition{0}_entityTypeEditControl", metricPartition.Id); Control entityTypeEditControl = phMetricValuePartitions.FindControl(controlId); if (entityTypeEntityIds.Count() > position) { var entry = entityTypeEntityIds[position]; if (metricPartitionEntityType != null && metricPartitionEntityType.SingleValueFieldType != null && metricPartitionEntityType.SingleValueFieldType.Field is IEntityFieldType) { if (entry != null && entry.EntityTypeId == metricPartitionEntityType.Id) { (metricPartitionEntityType.SingleValueFieldType.Field as IEntityFieldType).SetEditValueFromEntityId(entityTypeEditControl, new Dictionary <string, ConfigurationValue>(), entry.EntityId); } } } position++; } } drpSlidingDateRange.DelimitedValues = GetAttributeValue("SlidingDateRange"); mdEdit.Show(); }
/// <summary> /// Loads the family data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadMetrics(CSVInstance csvData) { // Required variables var lookupContext = new RockContext(); var metricService = new MetricService(lookupContext); var metricCategoryService = new MetricCategoryService(lookupContext); var categoryService = new CategoryService(lookupContext); var metricSourceTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.METRIC_SOURCE_TYPE)).DefinedValues; var metricManualSource = metricSourceTypes.FirstOrDefault(m => m.Guid == new Guid(Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_MANUAL)); var metricEntityTypeId = EntityTypeCache.Read <Rock.Model.MetricCategory>(false, lookupContext).Id; var campusEntityTypeId = EntityTypeCache.Read <Rock.Model.Campus>(false, lookupContext).Id; var campuses = CampusCache.All(); var allMetrics = metricService.Queryable().AsNoTracking().ToList(); var metricCategories = categoryService.Queryable().AsNoTracking() .Where(c => c.EntityType.Guid == new Guid(Rock.SystemGuid.EntityType.METRICCATEGORY)).ToList(); var defaultMetricCategory = metricCategories.FirstOrDefault(c => c.Name == "Metrics"); if (defaultMetricCategory == null) { defaultMetricCategory = new Category(); defaultMetricCategory.Name = "Metrics"; defaultMetricCategory.IsSystem = false; defaultMetricCategory.EntityTypeId = metricEntityTypeId; defaultMetricCategory.EntityTypeQualifierColumn = string.Empty; defaultMetricCategory.EntityTypeQualifierValue = string.Empty; defaultMetricCategory.IconCssClass = string.Empty; defaultMetricCategory.Description = string.Empty; lookupContext.Categories.Add(defaultMetricCategory); lookupContext.SaveChanges(); metricCategories.Add(defaultMetricCategory); } var metricValues = new List <MetricValue>(); Metric currentMetric = null; int completed = 0; ReportProgress(0, string.Format("Starting metrics import ({0:N0} already exist).", 0)); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { string metricCampus = row[MetricCampus]; string metricName = row[MetricName]; string metricCategoryString = row[MetricCategory]; if (!string.IsNullOrEmpty(metricName)) { decimal? value = row[MetricValue].AsDecimalOrNull(); DateTime?valueDate = row[MetricService].AsDateTime(); var metricCategoryId = defaultMetricCategory.Id; // create the category if it doesn't exist Category newMetricCategory = null; if (!string.IsNullOrEmpty(metricCategoryString)) { newMetricCategory = metricCategories.FirstOrDefault(c => c.Name == metricCategoryString); if (newMetricCategory == null) { newMetricCategory = new Category(); newMetricCategory.Name = metricCategoryString; newMetricCategory.IsSystem = false; newMetricCategory.EntityTypeId = metricEntityTypeId; newMetricCategory.EntityTypeQualifierColumn = string.Empty; newMetricCategory.EntityTypeQualifierValue = string.Empty; newMetricCategory.IconCssClass = string.Empty; newMetricCategory.Description = string.Empty; lookupContext.Categories.Add(newMetricCategory); lookupContext.SaveChanges(); metricCategories.Add(newMetricCategory); } metricCategoryId = newMetricCategory.Id; } if (valueDate.HasValue) { var timeFrame = (DateTime)valueDate; if (timeFrame.TimeOfDay.TotalSeconds > 0) { metricName = string.Format("{0} {1}", timeFrame.ToString("HH:mm"), metricName); } } // create metric if it doesn't exist currentMetric = allMetrics.FirstOrDefault(m => m.Title == metricName && m.MetricCategories.Any(c => c.CategoryId == metricCategoryId)); if (currentMetric == null) { currentMetric = new Metric(); currentMetric.Title = metricName; currentMetric.IsSystem = false; currentMetric.IsCumulative = false; currentMetric.SourceSql = string.Empty; currentMetric.Subtitle = string.Empty; currentMetric.Description = string.Empty; currentMetric.IconCssClass = string.Empty; currentMetric.SourceValueTypeId = metricManualSource.Id; currentMetric.CreatedByPersonAliasId = ImportPersonAliasId; currentMetric.CreatedDateTime = ImportDateTime; metricService.Add(currentMetric); lookupContext.SaveChanges(); if (currentMetric.MetricCategories == null || !currentMetric.MetricCategories.Any(a => a.CategoryId == metricCategoryId)) { metricCategoryService.Add(new MetricCategory { CategoryId = metricCategoryId, MetricId = currentMetric.Id }); lookupContext.SaveChanges(); } allMetrics.Add(currentMetric); } var campusId = campuses.Where(c => c.Name == metricCampus || c.ShortCode == metricCampus) .Select(c => (int?)c.Id).FirstOrDefault(); // create values for this metric var metricValue = new MetricValue(); metricValue.MetricValueType = MetricValueType.Measure; metricValue.CreatedByPersonAliasId = ImportPersonAliasId; metricValue.CreatedDateTime = ImportDateTime; metricValue.MetricValueDateTime = valueDate; metricValue.MetricId = currentMetric.Id; metricValue.Note = string.Empty; metricValue.XValue = string.Empty; metricValue.YValue = value; metricValues.Add(metricValue); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} metrics imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveMetrics(metricValues); ReportPartialProgress(); // Reset lookup context lookupContext = new RockContext(); metricValues.Clear(); } } } // Check to see if any rows didn't get saved to the database if (metricValues.Any()) { SaveMetrics(metricValues); } ReportProgress(0, string.Format("Finished metrics import: {0:N0} metrics added or updated.", completed)); return(completed); }
/// <summary> /// Maps the headcount metrics. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> private int MapMetrics(IQueryable <Row> tableData, long totalRows = 0) { // Required variables var lookupContext = new RockContext(); var metricService = new MetricService(lookupContext); var metricCategoryService = new MetricCategoryService(lookupContext); var categoryService = new CategoryService(lookupContext); var metricSourceTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.METRIC_SOURCE_TYPE)).DefinedValues; var metricManualSource = metricSourceTypes.FirstOrDefault(m => m.Guid == new Guid(Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_MANUAL)); var archivedScheduleCategory = GetCategory(lookupContext, ScheduleEntityTypeId, null, "Archived Schedules"); var scheduleService = new ScheduleService(lookupContext); var scheduleMetrics = scheduleService.Queryable().AsNoTracking().Where(s => s.Category.Guid == archivedScheduleCategory.Guid).ToList(); var allMetrics = metricService.Queryable().AsNoTracking().ToList(); var metricCategories = categoryService.Queryable().AsNoTracking() .Where(c => c.EntityType.Guid == new Guid(Rock.SystemGuid.EntityType.METRICCATEGORY)).ToList(); var defaultCategoryName = "Metrics"; var defaultCategory = metricCategories.FirstOrDefault(c => c.Name == defaultCategoryName); if (defaultCategory == null) { defaultCategory = GetCategory(lookupContext, MetricCategoryEntityTypeId, null, defaultCategoryName); defaultCategory.ForeignKey = string.Format("Category imported {0}", ImportDateTime); metricCategories.Add(defaultCategory); } var metricValues = new List <MetricValue>(); Metric currentMetric = null; var completedItems = 0; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Starting metrics import ({0:N0} already exist).", 0)); foreach (var row in tableData.Where(r => r != null)) { var foreignId = row["Headcount_ID"] as int?; var activityId = row["Activity_ID"] as int?; var rlcId = row["RLC_ID"] as int?; var metricName = row["RLC_name"] as string; var valueDate = row["Start_Date_Time"] as DateTime?; var value = row["Attendance"] as string; var metricNote = row["Meeting_note"] as string; int?metricCampusId = null; if (!string.IsNullOrEmpty(metricName) && !string.IsNullOrWhiteSpace(value)) { var categoryName = string.Empty; var metricCategoryId = defaultCategory.Id; if (activityId.HasValue) { var activityGroup = ImportedGroups.FirstOrDefault(g => g.ForeignId == activityId); if (activityGroup != null && !string.IsNullOrWhiteSpace(activityGroup.Name)) { metricCampusId = metricCampusId ?? GetCampusId(activityGroup.Name); var activityCategory = metricCategories.FirstOrDefault(c => c.Name == activityGroup.Name && c.ParentCategoryId == metricCategoryId); if (activityCategory == null) { activityCategory = GetCategory(lookupContext, MetricCategoryEntityTypeId, metricCategoryId, activityGroup.Name); activityCategory.ForeignKey = string.Format("Category imported {0}", ImportDateTime); metricCategories.Add(activityCategory); } metricCategoryId = activityCategory.Id; } } if (rlcId.HasValue) { var rlcGroup = ImportedGroups.FirstOrDefault(g => g.ForeignId == rlcId); if (rlcGroup != null && !string.IsNullOrWhiteSpace(rlcGroup.Name)) { metricCampusId = metricCampusId ?? GetCampusId(rlcGroup.Name); var rlcCategory = metricCategories.FirstOrDefault(c => c.Name == rlcGroup.Name && c.ParentCategoryId == metricCategoryId); if (rlcCategory == null) { rlcCategory = GetCategory(lookupContext, MetricCategoryEntityTypeId, metricCategoryId, rlcGroup.Name); rlcCategory.ForeignKey = string.Format("Category imported {0}", ImportDateTime); metricCategories.Add(rlcCategory); } metricCategoryId = rlcCategory.Id; } } // create metric if it doesn't exist currentMetric = allMetrics.FirstOrDefault(m => m.Title == metricName && m.MetricCategories.Any(c => c.CategoryId == metricCategoryId)); if (currentMetric == null) { currentMetric = new Metric(); currentMetric.Title = metricName; currentMetric.IsSystem = false; currentMetric.IsCumulative = false; currentMetric.SourceSql = string.Empty; currentMetric.Subtitle = string.Empty; currentMetric.Description = string.Empty; currentMetric.IconCssClass = string.Empty; currentMetric.SourceValueTypeId = metricManualSource.Id; currentMetric.CreatedByPersonAliasId = ImportPersonAliasId; currentMetric.CreatedDateTime = ImportDateTime; currentMetric.ForeignId = foreignId; currentMetric.ForeignKey = foreignId.ToStringSafe(); currentMetric.MetricPartitions = new List <MetricPartition>(); currentMetric.MetricPartitions.Add(new MetricPartition { Label = "Campus", Metric = currentMetric, EntityTypeId = CampusEntityTypeId, EntityTypeQualifierColumn = string.Empty, EntityTypeQualifierValue = string.Empty }); currentMetric.MetricPartitions.Add(new MetricPartition { Label = "Service", Metric = currentMetric, EntityTypeId = ScheduleEntityTypeId, EntityTypeQualifierColumn = string.Empty, EntityTypeQualifierValue = string.Empty }); metricService.Add(currentMetric); lookupContext.SaveChanges(); if (currentMetric.MetricCategories == null || !currentMetric.MetricCategories.Any(a => a.CategoryId == metricCategoryId)) { metricCategoryService.Add(new MetricCategory { CategoryId = metricCategoryId, MetricId = currentMetric.Id }); lookupContext.SaveChanges(); } allMetrics.Add(currentMetric); } // create values for this metric var metricValue = new MetricValue(); metricValue.MetricValueType = MetricValueType.Measure; metricValue.CreatedByPersonAliasId = ImportPersonAliasId; metricValue.CreatedDateTime = ImportDateTime; metricValue.MetricValueDateTime = valueDate; metricValue.MetricId = currentMetric.Id; metricValue.XValue = string.Empty; metricValue.YValue = value.AsDecimalOrNull(); metricValue.ForeignKey = string.Format("Metric Value imported {0}", ImportDateTime); metricValue.Note = metricNote ?? string.Empty; if (valueDate.HasValue) { var metricPartitionScheduleId = currentMetric.MetricPartitions.FirstOrDefault(p => p.Label == "Service").Id; var date = ( DateTime )valueDate; var scheduleName = date.DayOfWeek.ToString(); if (date.TimeOfDay.TotalSeconds > 0) { scheduleName = scheduleName + string.Format(" {0}", date.ToString("hh:mm")) + string.Format("{0}", date.ToString("tt").ToLower()); } var metricSchedule = scheduleMetrics.FirstOrDefault(s => s.Name == scheduleName); if (metricSchedule == null) { metricSchedule = new Schedule(); metricSchedule.Name = scheduleName; metricSchedule.iCalendarContent = CreateCalendarContent(date, "WEEKLY", ImportDateTime); metricSchedule.CategoryId = archivedScheduleCategory.Id; metricSchedule.EffectiveStartDate = ImportDateTime; metricSchedule.CreatedByPersonAliasId = ImportPersonAliasId; metricSchedule.CreatedDateTime = ImportDateTime; metricSchedule.ForeignKey = string.Format("Metric Schedule imported {0}", ImportDateTime); lookupContext.Schedules.Add(metricSchedule); lookupContext.SaveChanges(); scheduleMetrics.Add(metricSchedule); } metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartitionScheduleId, EntityId = metricSchedule.Id, CreatedDateTime = valueDate, ModifiedDateTime = valueDate, CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId }); } if (metricCampusId.HasValue && CampusList.Any(c => c.Id == metricCampusId)) { var metricPartitionCampusId = currentMetric.MetricPartitions.FirstOrDefault(p => p.Label == "Campus").Id; metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartitionCampusId, EntityId = metricCampusId }); } metricValues.Add(metricValue); completedItems++; if (completedItems % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} metrics imported.", completedItems)); } if (completedItems % ReportingNumber < 1) { SaveMetrics(metricValues); ReportPartialProgress(); metricValues.Clear(); } } } // Check to see if any rows didn't get saved to the database if (metricValues.Any()) { SaveMetrics(metricValues); } ReportProgress(0, string.Format("Finished metrics import: {0:N0} metrics added or updated.", completedItems)); return(completedItems); }
/// <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); int metricId = hfMetricId.Value.AsInteger(false) ?? 0; 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; metric.EntityTypeId = etpEntityType.SelectedEntityTypeId; 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; metric.SourceSql = ceSourceSql.Text; metric.DataViewId = ddlDataView.SelectedValueAsId(); if (rblScheduleSelect.SelectedValueAsEnum <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() RockTransactionScope.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; } schedule.iCalendarContent = sbSchedule.iCalendarContent; if (schedule.Id == 0) { scheduleService.Add(schedule); // save to make sure we have a scheduleId rockContext.SaveChanges(); } metric.ScheduleId = schedule.Id; 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) { 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); var orphanedSchedules = scheduleService.Queryable() .Where(a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != schedule.Id) .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").AsInteger(); 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; 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 ) { // 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( new RockContext() ).Get( metricCategoryId.Value ); if ( metricCategory != null ) { hfMetricCategoryId.Value = metricCategory.Id.ToString(); metricId = metricCategory.MetricId; } } else { if ( !metricId.HasValue ) { // adding a new metric metricId = 0; } } } int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull(); if ( metricId.HasValue ) { ShowDetail( metricId.Value, parentCategoryId ); } else { pnlDetails.Visible = false; } } }
/// <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 SelectedIndexChanged event of the rblSelectOrContext control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void rblSelectOrContext_SelectedIndexChanged( object sender, EventArgs e ) { phMetricValuePartitions.Visible = rblSelectOrContext.SelectedValue == "0"; var metricCategoryId = mpMetricCategoryPicker.SelectedValue.AsIntegerOrNull(); var metricCategory = new MetricCategoryService( new RockContext() ).Get( metricCategoryId ?? 0 ); CreateDynamicControls( metricCategory != null ? metricCategory.MetricId : (int?)null ); }
/// <summary> /// Shows the settings. /// </summary> protected void ShowSettings() { flotChart.Visible = false; pnlEditModel.Visible = true; var rockContext = new RockContext(); var metricCategoryService = new MetricCategoryService( rockContext ); MetricCategory metricCategory = null; if ( this.MetricId.HasValue ) { metricCategory = metricCategoryService.Queryable().Where( a => a.MetricId == this.MetricId ).FirstOrDefault(); mpMetricCategoryPicker.SetValue( metricCategory ); } if ( this.GetEntityFromContextEnabled ) { rblSelectOrContext.SetValue( "1" ); } else { rblSelectOrContext.SetValue( "0" ); } cbCombineValues.Checked = this.CombineValues; rblSelectOrContext_SelectedIndexChanged( null, null ); if ( metricCategory != null ) { var entityTypeEntityIds = ( GetAttributeValue( "MetricEntityTypeEntityIds" ) ?? string.Empty ).Split( ',' ).Select( a => a.Split( '|' ) ).Where( a => a.Length == 2 ).Select( a => new { EntityTypeId = a[0].AsIntegerOrNull(), EntityId = a[1].AsIntegerOrNull() } ).ToList(); int position = 0; foreach ( var metricPartition in metricCategory.Metric.MetricPartitions.OrderBy( a => a.Order ) ) { var metricPartitionEntityType = EntityTypeCache.Read( metricPartition.EntityTypeId ?? 0 ); var controlId = string.Format( "metricPartition{0}_entityTypeEditControl", metricPartition.Id ); Control entityTypeEditControl = phMetricValuePartitions.FindControl( controlId ); if ( entityTypeEntityIds.Count() > position ) { var entry = entityTypeEntityIds[position]; if ( metricPartitionEntityType != null && metricPartitionEntityType.SingleValueFieldType != null && metricPartitionEntityType.SingleValueFieldType.Field is IEntityFieldType ) { if ( entry != null && entry.EntityTypeId == metricPartitionEntityType.Id) { ( metricPartitionEntityType.SingleValueFieldType.Field as IEntityFieldType ).SetEditValueFromEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>(), entry.EntityId ); } } } position++; } } drpSlidingDateRange.DelimitedValues = GetAttributeValue( "SlidingDateRange" ); mdEdit.Show(); }
/// <summary> /// Gets all category and non-category item decendents for the provided <see cref="CategoryItem"/>, which should represent a <see cref="Metric"/> or <see cref="MetricCategory"/>. /// </summary> /// <param name="categoryItem">The <see cref="CategoryItem"/>, which should represent a <see cref="Metric"/> or <see cref="MetricCategory"/>.</param> /// <param name="includedCategoryIds">The included category ids.</param> /// <param name="metricCategoryService">The <see cref="MetricCategoryService"/>.</param> /// <returns></returns> private List <CategoryItem> GetAllMetricDescendants(CategoryItem categoryItem, string includedCategoryIds, MetricCategoryService metricCategoryService) { var childCategories = GetChildren( id: categoryItem.Id.AsInteger(), rootCategoryId: 0, getCategorizedItems: true, entityTypeId: EntityTypeCache.Get <MetricCategory>().Id, includedCategoryIds: includedCategoryIds ).ToList(); foreach (var childCategory in childCategories) { if (!childCategory.IsCategory) { // Load the MetricCategory. var metricCategory = metricCategoryService.Get(childCategory.Id.AsInteger()); if (metricCategory != null) { // Swap the Id to the Metric Id (instead of MetricCategory.Id). childCategory.Id = metricCategory.MetricId.ToString(); } } childCategory.Children = new List <Web.UI.Controls.TreeViewItem>(); childCategory.Children.AddRange(GetAllMetricDescendants(childCategory, includedCategoryIds, metricCategoryService)); } return(childCategories); }
/// <summary> /// Sets the values on select. /// </summary> protected override void SetValuesOnSelect() { var metricCategories = new MetricCategoryService(new RockContext()).Queryable().Where(g => ItemIds.Contains(g.Id.ToString())); this.SetValues(metricCategories); }
/// <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> /// Saves the <see cref="MetricValue"/>s and updates the <see cref="IJobExecutionContext"/>'s Result property. /// </summary> /// <param name="context">The <see cref="IJobExecutionContext"/>.</param> /// <exception cref="Exception">Unable to find the "Hosting Metrics" Category ID.</exception> private void SaveMetricValues(IJobExecutionContext context) { var rockContext = new RockContext(); rockContext.Database.CommandTimeout = _commandTimeout; var hostingMetricsCategoryId = CategoryCache.GetId(SystemGuid.Category.METRIC_HOSTING_METRICS.AsGuid()); if (!hostingMetricsCategoryId.HasValue) { throw new Exception(@"Unable to find the ""Hosting Metrics"" Category ID."); } var metricIdsQuery = new MetricCategoryService(rockContext).Queryable() .Where(mc => mc.CategoryId == hostingMetricsCategoryId) .Select(mc => mc.MetricId); // Get all of the Metrics tied to the "Hosting Metrics" Category var metrics = new MetricService(rockContext).Queryable("MetricPartitions") .Where(m => metricIdsQuery.Contains(m.Id)) .ToList(); var metricValues = new List <MetricValue>(); foreach (var metric in metrics) { // Attempt to add any PerformanceCounter MetricValues TryAddPerformanceCounterMetricValue(metric, metricValues); } /* * 2020-04-22 - JPH * * The Metrics being collected by the first revision of this Job each have a single, default MetricPartition. * If we add Metrics to this Job in the future that are more complicated, we'll want to revisit the below logic. * */ var metricValueService = new MetricValueService(rockContext); var metricValuePartitionService = new MetricValuePartitionService(rockContext); foreach (var metricValue in metricValues) { foreach (var metricPartition in metricValue.Metric.MetricPartitions) { metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartition.Id }); } metricValueService.Add(metricValue); } rockContext.SaveChanges(); /* * 2020-05-19 - SK * Removing the old metrics based on Maximum Metric to Retain value * */ if (_maximumMetricsToRetain.HasValue) { foreach (var metric in metrics) { var deleteMetricValuesQry = metricValueService .Queryable() .AsNoTracking() .Where(a => a.MetricId == metric.Id) .OrderByDescending(a => a.MetricValueDateTime) .Skip(_maximumMetricsToRetain.Value); if (deleteMetricValuesQry.Any()) { var metricValuePartitionQry = metricValuePartitionService.Queryable().AsNoTracking().Where(a => deleteMetricValuesQry.Any(u => u.Id == a.MetricValueId)); rockContext.BulkDelete(metricValuePartitionQry); rockContext.BulkDelete(deleteMetricValuesQry); } } } context.Result = $"Calculated a total of {metricValues.Count} metric values for {metrics.Count} metrics"; }
/// <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 ); int metricId = hfMetricId.Value.AsInteger( false ) ?? 0; 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; metric.EntityTypeId = etpEntityType.SelectedEntityTypeId; 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; metric.SourceSql = ceSourceSql.Text; metric.DataViewId = ddlDataView.SelectedValueAsId(); if ( rblScheduleSelect.SelectedValueAsEnum<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() RockTransactionScope.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; } schedule.iCalendarContent = sbSchedule.iCalendarContent; if ( schedule.Id == 0 ) { scheduleService.Add( schedule ); // save to make sure we have a scheduleId rockContext.SaveChanges(); } metric.ScheduleId = schedule.Id; 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 ) { 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 ); var orphanedSchedules = scheduleService.Queryable() .Where( a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != schedule.Id ) .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" ).AsInteger(); 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; NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Loads the family data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadMetrics(CSVInstance csvData) { // Required variables var lookupContext = new RockContext(); var metricService = new MetricService(lookupContext); var metricCategoryService = new MetricCategoryService(lookupContext); var categoryService = new CategoryService(lookupContext); var metricSourceTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.METRIC_SOURCE_TYPE)).DefinedValues; var metricManualSource = metricSourceTypes.FirstOrDefault(m => m.Guid == new Guid(Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_MANUAL)); var scheduleService = new ScheduleService(lookupContext); var scheduleMetrics = scheduleService.Queryable().AsNoTracking() .Where(s => s.Category.Guid == new Guid(Rock.SystemGuid.Category.SCHEDULE_SERVICE_TIMES)).ToList(); var scheduleCategoryId = categoryService.Queryable().AsNoTracking() .Where(c => c.Guid == new Guid(Rock.SystemGuid.Category.SCHEDULE_SERVICE_TIMES)).FirstOrDefault().Id; var metricEntityTypeId = EntityTypeCache.Get <MetricCategory>(false, lookupContext).Id; var campusEntityTypeId = EntityTypeCache.Get <Campus>(false, lookupContext).Id; var scheduleEntityTypeId = EntityTypeCache.Get <Schedule>(false, lookupContext).Id; var allMetrics = metricService.Queryable().AsNoTracking().ToList(); var metricCategories = categoryService.Queryable().AsNoTracking() .Where(c => c.EntityType.Guid == new Guid(Rock.SystemGuid.EntityType.METRICCATEGORY)).ToList(); var defaultMetricCategory = metricCategories.FirstOrDefault(c => c.Name == "Metrics"); if (defaultMetricCategory == null) { defaultMetricCategory = new Category(); defaultMetricCategory.Name = "Metrics"; defaultMetricCategory.IsSystem = false; defaultMetricCategory.EntityTypeId = metricEntityTypeId; defaultMetricCategory.EntityTypeQualifierColumn = string.Empty; defaultMetricCategory.EntityTypeQualifierValue = string.Empty; defaultMetricCategory.IconCssClass = string.Empty; defaultMetricCategory.Description = string.Empty; lookupContext.Categories.Add(defaultMetricCategory); lookupContext.SaveChanges(); metricCategories.Add(defaultMetricCategory); } var metricValues = new List <MetricValue>(); Metric currentMetric = null; int completed = 0; ReportProgress(0, string.Format("Starting metrics import ({0:N0} already exist).", 0)); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { string metricCampus = row[MetricCampus]; string metricName = row[MetricName]; string metricCategoryString = row[MetricCategory]; string metricNote = row[MetricNote]; if (!string.IsNullOrEmpty(metricName)) { decimal? value = row[MetricValue].AsDecimalOrNull(); DateTime?valueDate = row[MetricService].AsDateTime(); var metricCategoryId = defaultMetricCategory.Id; // create the category if it doesn't exist Category newMetricCategory = null; if (!string.IsNullOrEmpty(metricCategoryString)) { newMetricCategory = metricCategories.FirstOrDefault(c => c.Name == metricCategoryString); if (newMetricCategory == null) { newMetricCategory = new Category(); newMetricCategory.Name = metricCategoryString; newMetricCategory.IsSystem = false; newMetricCategory.EntityTypeId = metricEntityTypeId; newMetricCategory.EntityTypeQualifierColumn = string.Empty; newMetricCategory.EntityTypeQualifierValue = string.Empty; newMetricCategory.IconCssClass = string.Empty; newMetricCategory.Description = string.Empty; lookupContext.Categories.Add(newMetricCategory); lookupContext.SaveChanges(); metricCategories.Add(newMetricCategory); } metricCategoryId = newMetricCategory.Id; } // create metric if it doesn't exist currentMetric = allMetrics.FirstOrDefault(m => m.Title == metricName && m.MetricCategories.Any(c => c.CategoryId == metricCategoryId)); if (currentMetric == null) { currentMetric = new Metric(); currentMetric.Title = metricName; currentMetric.IsSystem = false; currentMetric.IsCumulative = false; currentMetric.SourceSql = string.Empty; currentMetric.Subtitle = string.Empty; currentMetric.Description = string.Empty; currentMetric.IconCssClass = string.Empty; currentMetric.SourceValueTypeId = metricManualSource.Id; currentMetric.CreatedByPersonAliasId = ImportPersonAliasId; currentMetric.CreatedDateTime = ImportDateTime; currentMetric.ForeignKey = string.Format("Metric imported {0}", ImportDateTime); currentMetric.MetricPartitions = new List <MetricPartition>(); currentMetric.MetricPartitions.Add(new MetricPartition { Label = "Campus", EntityTypeId = campusEntityTypeId, Metric = currentMetric, Order = 0 }); currentMetric.MetricPartitions.Add(new MetricPartition { Label = "Service", EntityTypeId = scheduleEntityTypeId, Metric = currentMetric, Order = 1 }); metricService.Add(currentMetric); lookupContext.SaveChanges(); if (currentMetric.MetricCategories == null || !currentMetric.MetricCategories.Any(a => a.CategoryId == metricCategoryId)) { metricCategoryService.Add(new MetricCategory { CategoryId = metricCategoryId, MetricId = currentMetric.Id }); lookupContext.SaveChanges(); } allMetrics.Add(currentMetric); } // create values for this metric var metricValue = new MetricValue(); metricValue.MetricValueType = MetricValueType.Measure; metricValue.CreatedByPersonAliasId = ImportPersonAliasId; metricValue.CreatedDateTime = ImportDateTime; metricValue.MetricValueDateTime = valueDate.Value.Date; metricValue.MetricId = currentMetric.Id; metricValue.Note = string.Empty; metricValue.XValue = string.Empty; metricValue.YValue = value; metricValue.ForeignKey = string.Format("Metric Value imported {0}", ImportDateTime); metricValue.Note = metricNote; if (!string.IsNullOrWhiteSpace(metricCampus)) { var campus = CampusList.Where(c => c.Name.Equals(metricCampus, StringComparison.OrdinalIgnoreCase) || c.ShortCode.Equals(metricCampus, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (campus == null) { var newCampus = new Campus(); newCampus.IsSystem = false; newCampus.Name = metricCampus; newCampus.ShortCode = metricCampus.RemoveWhitespace(); newCampus.IsActive = true; lookupContext.Campuses.Add(newCampus); lookupContext.SaveChanges(DisableAuditing); CampusList.Add(newCampus); campus = newCampus; } if (campus != null) { var metricPartitionCampusId = currentMetric.MetricPartitions.FirstOrDefault(p => p.Label == "Campus").Id; metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartitionCampusId, EntityId = campus.Id }); } } if (valueDate.HasValue) { var metricPartitionScheduleId = currentMetric.MetricPartitions.FirstOrDefault(p => p.Label == "Service").Id; var date = ( DateTime )valueDate; var scheduleName = date.DayOfWeek.ToString(); if (date.TimeOfDay.TotalSeconds > 0) { scheduleName = scheduleName + string.Format(" {0}", date.ToString("hh:mm")) + string.Format("{0}", date.ToString("tt").ToLower()); } if (!scheduleMetrics.Any(s => s.Name == scheduleName)) { Schedule newSchedule = new Schedule(); newSchedule.Name = scheduleName; newSchedule.CategoryId = scheduleCategoryId; newSchedule.CreatedByPersonAliasId = ImportPersonAliasId; newSchedule.CreatedDateTime = ImportDateTime; newSchedule.ForeignKey = string.Format("Metric Schedule imported {0}", ImportDateTime); scheduleMetrics.Add(newSchedule); lookupContext.Schedules.Add(newSchedule); lookupContext.SaveChanges(); } var scheduleId = scheduleMetrics.FirstOrDefault(s => s.Name == scheduleName).Id; metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartitionScheduleId, EntityId = scheduleId }); } metricValues.Add(metricValue); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} metrics imported.", completed)); } if (completed % ReportingNumber < 1) { SaveMetrics(metricValues); ReportPartialProgress(); metricValues.Clear(); } } } // Check to see if any rows didn't get saved to the database if (metricValues.Any()) { SaveMetrics(metricValues); } ReportProgress(0, string.Format("Finished metrics import: {0:N0} metrics added or updated.", completed)); return(completed); }
/// <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 ) { // create dynamic controls var rockContext = new RockContext(); var metricValue = new MetricValueService( rockContext ).Get( hfMetricValueId.Value.AsInteger() ); if ( metricValue == null ) { metricValue = new MetricValue { MetricId = hfMetricId.Value.AsInteger() }; metricValue.Metric = new MetricService( rockContext ).Get( metricValue.MetricId ); } CreateDynamicControls( metricValue, false, false ); } if ( !Page.IsPostBack ) { int? metricValueId = PageParameter( "MetricValueId" ).AsIntegerOrNull(); // in case called with MetricId as the parent id parameter int? metricId = PageParameter( "MetricId" ).AsIntegerOrNull(); // in case called with MetricCategoryId as the parent id parameter 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( new RockContext() ).Get( metricCategoryId.Value ); if ( metricCategory != null ) { metricId = metricCategory.MetricId; } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricCategoryId.Value = metricCategoryId.ToString(); if ( metricValueId.HasValue ) { ShowDetail( metricValueId.Value, metricId ); } else { pnlDetails.Visible = false; } } }
/// <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> /// Sets the value on select. /// </summary> protected override void SetValueOnSelect() { var metricCategory = new MetricCategoryService( new RockContext() ).Get( int.Parse( ItemId ) ); SetValue( metricCategory ); }
/// <summary> /// Sets the value. /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="value">The value.</param> public override void SetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues, string value ) { if ( value != null ) { var picker = control as MetricCategoryPicker; if ( picker != null ) { List<MetricCategory> metricCategories = new List<MetricCategory>(); var guidPairs = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs( value ); MetricCategoryService metricCategoryService = new MetricCategoryService( new RockContext() ); foreach (var guidPair in guidPairs) { // first try to get each metric from the category that it was selected from var metricCategory = metricCategoryService.Queryable().Where( a => a.Metric.Guid == guidPair.MetricGuid && a.Category.Guid == guidPair.CategoryGuid ).FirstOrDefault(); if (metricCategory == null) { // if the metric isn't found in the original category, just the first one, ignoring category metricCategory = metricCategoryService.Queryable().Where( a => a.Metric.Guid == guidPair.MetricGuid ).FirstOrDefault(); } if (metricCategory != null) { metricCategories.Add( metricCategory ); } } picker.SetValues( metricCategories ); } } }
/// <summary> /// Sets the values on select. /// </summary> protected override void SetValuesOnSelect() { var metricCategories = new MetricCategoryService( new RockContext() ).Queryable().Where( g => ItemIds.Contains( g.Id.ToString() ) ); this.SetValues( metricCategories ); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { MetricValueService metricValueService = new MetricValueService( new RockContext() ); SortProperty sortProperty = gMetricValues.SortProperty; var qry = metricValueService.Queryable(); // in case called normally int? metricId = PageParameter( "MetricId" ).AsInteger( false ); // in case called from CategoryTreeView int? metricCategoryId = PageParameter( "MetricCategoryId" ).AsInteger( false ); MetricCategory metricCategory = null; if ( metricCategoryId.HasValue ) { if ( metricCategoryId.Value > 0 ) { // editing a metric, but get the metricId from the metricCategory metricCategory = new MetricCategoryService( new 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(); this.Visible = metricId.HasValue; qry = qry.Where( a => a.MetricId == metricId ); if ( sortProperty != null ) { gMetricValues.DataSource = qry.Sort( sortProperty ).ToList(); } else { gMetricValues.DataSource = qry.OrderBy( s => s.Order ).ThenBy( s => s.XValue ).ThenBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ToList(); } gMetricValues.DataBind(); }
/// <summary> /// Sets the hidden field values. /// </summary> private void SetHiddenFieldValues() { var rockContext = new RockContext(); // in case called normally int? metricId = PageParameter( "MetricId" ).AsIntegerOrNull(); hfEntityTypeName.Value = string.Empty; // 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; if ( metricCategory.Metric != null && metricCategory.Metric.EntityType != null ) { hfEntityTypeName.Value = metricCategory.Metric.EntityType.FriendlyName; } } } else { // adding a new metric. Block will (hopefully) not be shown metricId = 0; } } hfMetricId.Value = metricId.ToString(); hfMetricCategoryId.Value = metricCategoryId.ToString(); }