Example #1
0
 private static void Submit(string metricName, string applicationName, TimeSpan elapsed, bool cache)
 {
     if (!cache)
     {
         using (var service = new MetricService())
         {
             service.Add(new MetricDTO {
                 Duration = elapsed, ApplicationName = applicationName, MetricName = metricName
             });
         }
     }
     else
     {
         _cachedMetrics.Add(new MetricDTO {
             Duration = elapsed, ApplicationName = applicationName, MetricName = metricName
         });
     }
 }
Example #2
0
        private void ProcessDescendents(IEnumerable <GroupType> descendentGroupTypes, Category rootCategory)
        {
            foreach (var groupType in descendentGroupTypes)
            {
                _seenGroupTypeIds.Add(groupType.Id);
                if (!groupType.Groups.Any() && !groupType.ChildGroupTypes.Any(g => g.Groups.Any()))
                {
                    continue;
                }
                {
                    var category = _categoryService.Queryable().FirstOrDefault(c => c.ForeignGuid == groupType.Guid) ??
                                   MakeGroupTypeCategory(groupType, rootCategory);
                    var groups = groupType.Groups.ToList();
                    foreach (var group in groups)
                    {
                        if (
                            !_metricService.Queryable()
                            .Any(
                                m =>
                                m.MetricCategories.Any(c => c.CategoryId == category.Id) &&
                                m.ForeignGuid != null && m.ForeignGuid == group.Guid))
                        {
                            var metric = MakeGroupMetric(group);
                            _metricService.Add(metric);
                            var metricCategory = new MetricCategory
                            {
                                CategoryId = category.Id,
                                Metric     = metric
                            };
                            _metricCategoryService.Add(metricCategory);
                        }
                    }
                    _rockContext.SaveChanges();

                    if (groupType.ChildGroupTypes != null)
                    {
                        ProcessDescendents(
                            groupType.ChildGroupTypes.Where(
                                g => g.GroupTypePurposeValueId == _checkInTemplateId && !_seenGroupTypeIds.Contains(g.Id))
                            .ToList(), category);
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                int    metricId      = hfMetricId.ValueAsInt();
                var    metricService = new MetricService();
                Metric metric        = null;

                if (metricId == 0)
                {
                    metric          = new Metric();
                    metric.IsSystem = false;
                    metricService.Add(metric, CurrentPersonId);
                }
                else
                {
                    metric = metricService.Get(metricId);
                }

                metric.Category    = tbCategory.Text;
                metric.Title       = tbTitle.Text;
                metric.Subtitle    = tbSubtitle.Text;
                metric.Description = tbDescription.Text;
                metric.MinValue    = tbMinValue.Text.AsType <int?>();
                metric.MaxValue    = tbMaxValue.Text.AsType <int?>();
                metric.Type        = cbType.Checked;
                metric.CollectionFrequencyValueId = Int32.Parse(ddlCollectionFrequency.SelectedValue);
                metric.Source    = tbSource.Text;
                metric.SourceSQL = tbSourceSQL.Text;

                if (!metric.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                metricService.Save(metric, CurrentPersonId);
                hfMetricId.SetValue(metric.Id);
            }

            var savedMetric = new MetricService().Get(hfMetricId.ValueAsInt());

            ShowReadOnly(savedMetric);
        }
        /// <summary>
        /// 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);
        }
Example #5
0
        /// <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);
        }
Example #6
0
        /// <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>
        /// 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);
        }
Example #8
0
        /// <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);
        }