/// <summary> /// Handles the Click event of the btnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnCancel_Click(object sender, EventArgs e) { if (hfMetricId.Value.Equals("0")) { int?parentCategoryId = PageParameter("ParentCategoryId").AsIntegerOrNull(); if (parentCategoryId.HasValue) { // Cancelling on Add, and we know the parentCategoryId, so we are probably in treeview mode, so navigate to the current page var qryParams = new Dictionary <string, string>(); qryParams["CategoryId"] = parentCategoryId.ToString(); NavigateToPage(RockPage.Guid, qryParams); } else { // Cancelling on Add. Return to Grid NavigateToParentPage(); } } else { // Cancelling on Edit. Return to Details MetricService metricService = new MetricService(new RockContext()); Metric metric = metricService.Get(hfMetricId.Value.AsInteger()); ShowReadonlyDetails(metric); } }
/// <summary> /// Handles the Click event of the lbEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void lbEdit_Click(object sender, EventArgs e) { var metricService = new MetricService(); var metric = metricService.Get(hfMetricId.ValueAsInt()); ShowEdit(metric); }
public void WritesCorrectMetricsToElasticSearch() { var redisConnection = new Mock <IConnectionMultiplexer>(); var endpoint = new Mock <EndPoint>(); endpoint.SetupGet(e => e.AddressFamily).Returns(AddressFamily.Unknown); var endpoints = new[] { endpoint.Object }; redisConnection.Setup(c => c.GetEndPoints(It.IsAny <bool>())).Returns(endpoints); var redisServer = new Mock <IServer>(); var serverInfoList = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("keyspace_hits", "1"), new KeyValuePair <string, string>("keyspace_misses", "1") }; var serverInfo = serverInfoList.GroupBy(g => g.Key).ToArray(); redisServer.Setup(r => r.Info(It.IsAny <RedisValue>(), It.IsAny <CommandFlags>())).Returns(serverInfo); redisConnection.Setup(r => r.GetServer(endpoint.Object, It.IsAny <object>())) .Returns(redisServer.Object); var elasticClient = new Mock <IElasticClient>(); var metricService = new MetricService(redisConnection.Object, elasticClient.Object); metricService.GetInstanceMetrics("keyspace_hits,keyspace_misses"); redisConnection.Verify(r => r.GetServer(It.Is <EndPoint>(x => x.Equals(endpoint.Object)), null)); elasticClient.Verify(e => e.Index(It.Is <Dictionary <string, string> >(x => x.Count == 5 && x["keyspace_hits"] == "1" && x["keyspace_misses"] == "1" && x["hit_rate"] == "0.5"), It.IsAny <Func <IndexDescriptor <Dictionary <string, string> >, IIndexRequest> >())); }
/// <summary> /// Creates a new instance of the eventbus /// </summary> /// <param name="pipelineFactory"></param> /// <param name="pipelineId"></param> public EventBus(IPipelineFactory pipelineFactory, string pipelineId) { _pipelineFactory = pipelineFactory; PipelineId = pipelineId; var storage = GlobalConfiguration.Configuration.Resolve <IStorage>(); _metricService = new MetricService(storage, pipelineId); _queue = new EventQueue(); _logger = LoggerConfiguration.Setup ( s => { s.AddWriter(new ProcessedEventMetricCounter(_metricService, pipelineId)); s.AddWriter(new ActiveWorkersLogWriter(pipelineId)); s.AddWriter(new LogEventStatisticWriter(pipelineId)); } ); _metricService.SetMetric(new Metric(MetricType.ThreadCount, "Active Workers", _processors.Count)); _metricService.SetMetric(new Metric(MetricType.QueueSize, "Events in Queue", _queue.Count)); _metricService.SetPipelineHeartbeat(); var options = _pipelineFactory.Options.Merge(GlobalConfiguration.Configuration.GetOptions()); _minProcessors = options.MinProcessors; _cleanupLock = new DispatcherLock(); _dispatcher = new EventBusPorcessDispatcher(_processors, _queue, () => new EventProcessor(new EventPipelineWorker(_queue, () => _pipelineFactory.Setup(), _logger, _metricService), CleanupProcessors, _logger), _logger, _metricService, options); RunDispatcher(); }
/// <summary> /// Handles the Click event of the btnEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnEdit_Click(object sender, EventArgs e) { MetricService metricService = new MetricService(new RockContext()); Metric metric = metricService.Get(hfMetricId.Value.AsInteger()); ShowEditDetails(metric); }
public async Task ReturnsMetric() { // Arrange var context = _serviceProvider.GetRequiredService <IDataContext>(); await context.Metrics.AddAsync( new Metric { Type = Metrics.CpuLoad.AsInt(), Source = "existing-source", CurrentValue = 10 } ); await context.SaveChangesAsync(); var metricService = new MetricService(context, new Mock <ILogger <MetricService> >().Object); // Act var metric = await metricService.GetOrCreateMetricAsync(Metrics.CpuLoad, "existing-source"); // Assert Assert.NotNull(metric); Assert.Equal(Metrics.CpuLoad.AsInt(), metric.Type); Assert.Equal("existing-source", metric.Source); Assert.Equal(10, metric.CurrentValue); Assert.True( await context.Metrics.AnyAsync( mt => mt.Type == Metrics.CpuLoad.AsInt() && mt.Source == "existing-source" ) ); }
public async Task CreatesMetric() { // Arrange var context = _serviceProvider.GetRequiredService <IDataContext>(); await context.AbstractMetrics.AddAsync(new AbstractMetric { Type = Metrics.CpuLoad.AsInt() }); await context.AutoLabels.AddAsync(new AutoLabel { Id = AutoLabels.Normal.AsInt() }); await context.ManualLabels.AddAsync(new ManualLabel { Id = ManualLabels.None.AsInt() }); await context.SaveChangesAsync(); var metricService = new MetricService(context, new Mock <ILogger <MetricService> >().Object); // Act var metric = await metricService.GetOrCreateMetricAsync(Metrics.CpuLoad, "the-source"); // Assert Assert.NotNull(metric); Assert.Equal(Metrics.CpuLoad.AsInt(), metric.Type); Assert.Equal("the-source", metric.Source); Assert.True( await context.Metrics.AnyAsync(mt => mt.Type == Metrics.CpuLoad.AsInt() && mt.Source == "the-source") ); }
public string GetSeriesName(int metricId, int seriesId) { var rockContext = new RockContext(); int?entityTypeId = new MetricService(rockContext).Queryable().Where(a => a.Id == metricId).Select(s => s.EntityTypeId).FirstOrDefault(); if (entityTypeId.HasValue) { var entityTypeCache = EntityTypeCache.Read(entityTypeId.Value); if (entityTypeCache != null) { Type[] modelType = { entityTypeCache.GetEntityType() }; Type genericServiceType = typeof(Rock.Data.Service <>); Type modelServiceType = genericServiceType.MakeGenericType(modelType); var serviceInstance = Activator.CreateInstance(modelServiceType, new object[] { rockContext }) as IService; MethodInfo getMethod = serviceInstance.GetType().GetMethod("Get", new Type[] { typeof(int) }); var result = getMethod.Invoke(serviceInstance, new object[] { seriesId }); if (result != null) { return(result.ToString()); } } } return(null); }
/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { drpDates.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); ddlGoalMeasure.Items.Clear(); ddlGoalMeasure.Items.Add( new ListItem( string.Empty, string.Empty ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Goal.ConvertToString(), MetricValueType.Goal.ConvertToInt().ToString() ) ); ddlGoalMeasure.Items.Add( new ListItem( MetricValueType.Measure.ConvertToString(), MetricValueType.Measure.ConvertToInt().ToString() ) ); ddlGoalMeasure.SelectedValue = gfMetricValues.GetUserPreference( "Goal/Measure" ); var metric = new MetricService( new RockContext() ).Get( hfMetricId.Value.AsInteger() ); epEntity.Visible = metric != null; if ( metric != null ) { epEntity.EntityTypeId = metric.EntityTypeId; epEntity.EntityTypePickerVisible = false; var parts = gfMetricValues.GetUserPreference( this.EntityPreferenceKey ).Split( '|' ); if ( parts.Length >= 2 ) { epEntity.EntityId = parts[1].AsIntegerOrNull(); } } }
/// <summary> /// Creates the entity value lookups. /// </summary> /// <param name="metricID">The metric identifier.</param> private void CreateEntityValueLookups(int?metricID) { Metric metric = new MetricService(new RockContext()).Get(metricID ?? 0); if (metric != null) { var rockContext = new RockContext(); _entityTypeEntityNameLookup = new Dictionary <int, Dictionary <int, string> >(); _entityTypeEntityLookupQry = new Dictionary <int, IQueryable <IEntity> >(); foreach (var metricPartition in metric.MetricPartitions.Where(a => a.EntityTypeId.HasValue)) { var entityTypeCache = EntityTypeCache.Get(metricPartition.EntityTypeId ?? 0); _entityTypeEntityNameLookup.AddOrIgnore(entityTypeCache.Id, new Dictionary <int, string>()); _entityTypeEntityLookupQry.AddOrIgnore(entityTypeCache.Id, null); if (entityTypeCache != null) { if (entityTypeCache.GetEntityType() == typeof(Rock.Model.Group)) { _entityTypeEntityLookupQry[entityTypeCache.Id] = new GroupService(rockContext).Queryable(); } else { Type[] modelType = { entityTypeCache.GetEntityType() }; Type genericServiceType = typeof(Rock.Data.Service <>); Type modelServiceType = genericServiceType.MakeGenericType(modelType); var serviceInstance = Activator.CreateInstance(modelServiceType, new object[] { rockContext }) as IService; MethodInfo qryMethod = serviceInstance.GetType().GetMethod("Queryable", new Type[] { }); _entityTypeEntityLookupQry[entityTypeCache.Id] = qryMethod.Invoke(serviceInstance, new object[] { }) as IQueryable <IEntity>; } } } } }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = string.Empty; if (!string.IsNullOrWhiteSpace(value)) { var valueParts = value.Split('|'); if (valueParts.Length > 0) { var service = new MetricService(new RockContext()); var metric = service.Get(new Guid(valueParts[0])); if (metric != null) { formattedValue = metric.Title; var entityType = EntityTypeCache.Read(metric.EntityTypeId ?? 0); if (entityType != null && entityType.SingleValueFieldType != null) { if (valueParts.Length > 1) { formattedValue = string.Format("{0} - EntityId:{1}", metric.Title, valueParts[1].AsIntegerOrNull()); } } } } } return(base.FormatValue(parentControl, formattedValue, null, condensed)); }
/// <summary> /// Gets the edit value as the IEntity.Id /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues) { Guid guid = GetEditValue(control, configurationValues).AsGuid(); var item = new MetricService(new RockContext()).Get(guid); return(item != null ? item.Id : (int?)null); }
/// <summary> /// Handles the ApplyFilterClick event of the gfMetricValues control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void gfMetricValues_ApplyFilterClick(object sender, EventArgs e) { gfMetricValues.SaveUserPreference("Date Range", drpDates.DelimitedValues); gfMetricValues.SaveUserPreference("Goal/Measure", ddlGoalMeasure.SelectedValue); var metric = new MetricService(new RockContext()).Get(hfMetricId.Value.AsInteger()); var entityTypeEntityFilters = new Dictionary <int, int?>(); foreach (var metricPartition in metric.MetricPartitions) { var metricPartitionEntityType = EntityTypeCache.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.AddOrIgnore(metricPartitionEntityType.Id, entityId); } } var entityTypeEntityUserPreferenceValue = entityTypeEntityFilters .Select(a => new { EntityTypeId = a.Key, EntityId = a.Value }) .Select(a => string.Format("{0}|{1}", a.EntityTypeId, a.EntityId)) .ToList().AsDelimited(","); gfMetricValues.SaveUserPreference(this.EntityTypeEntityPreferenceKey, entityTypeEntityUserPreferenceValue); BindGrid(); }
/// <summary> /// Sets the edit value from IEntity.Id value /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id) { var item = new MetricService(new RockContext()).Get(id ?? 0); string guidValue = item != null?item.Guid.ToString() : string.Empty; SetEditValue(control, configurationValues, guidValue); }
public ResiliencePatterns(ConfigurationSection configurationSection, MetricService metricService) { _configurationSection = configurationSection; _metricService = metricService; CreateRetryPolicy(); CreateCircuitBreakerPolicy(); }
/// <summary> /// Reads new values entered by the user for the field /// returns Metric.Guid /// </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 MetricItemPicker; if (picker != null) { int?id = picker.SelectedValue.AsIntegerOrNull(); if (id.HasValue) { using (var rockContext = new RockContext()) { var metric = new MetricService(rockContext).GetNoTracking(id.Value); if (metric != null) { return(metric.Guid.ToString()); } } } return(string.Empty); } return(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) { // Options for Chart var chartOptions = ChartOptions.Default; chartOptions.vAxis.title = this.Title; if (!string.IsNullOrWhiteSpace(this.Subtitle)) { chartOptions.vAxis.title += Environment.NewLine + this.Subtitle; } hfOptions.Value = (chartOptions as object).ToJson(); List <ColumnDefinition> columnDefinitions = new List <ColumnDefinition>(); columnDefinitions.Add(new ColumnDefinition("Date", ColumnDataType.date)); columnDefinitions.Add(new ColumnDefinition("Attendance", ColumnDataType.number)); columnDefinitions.Add(new ChartTooltip()); hfColumns.Value = columnDefinitions.ToJson(); // Data for Chart Guid attendanceMetricGuid = new Guid("D4752628-DFC9-4681-ADB3-01936B8F38CA"); int metricId = new MetricService(new RockContext()).Get(attendanceMetricGuid).Id; DateTime?startDate = new DateTime(2013, 1, 1); DateTime?endDate = new DateTime(2014, 1, 1); int? entityId = null; hfRestUrlParams.Value = string.Format("{0}?startDate={1}&endDate={2}", metricId, startDate ?? DateTime.MinValue, endDate ?? DateTime.MaxValue); if (entityId.HasValue) { hfRestUrlParams.Value += string.Format("&entityId={0}", entityId); } } }
public RequestHandle(IResiliencePatterns resiliencePatterns, ConfigurationSection configurationSection, MetricService metrics) { _resiliencePatterns = resiliencePatterns; _configurationSection = configurationSection; _metrics = metrics; CreateCustomMetric(); }
public ViridianUtils() { VSMS = VirtualSystemManagementService.GetInstances().First(); IMS = ImageManagementService.GetInstances().First(); VSSS = VirtualSystemSnapshotService.GetInstances().First(); MS = MetricService.GetInstances().First(); VESMS = VirtualEthernetSwitchManagementService.GetInstances().First(); }
public void MetricService_GetMetricValue() { _storage.Setup(exp => exp.Get <Metric>(It.Is <StorageKey>(k => k.Key == $"metric:{MetricType.ProcessedEvents}"))).Returns(() => new Metric(MetricType.ProcessedEvents, "stats", 1)); var metrics = new MetricService(_storage.Object, "stats_GetMetric"); var metric = metrics.GetMetricValue <int>(MetricType.ProcessedEvents); Assert.AreEqual(1, metric); }
public void MetricService_SetMetric() { var metrics = new MetricService(_storage.Object, "metric_SetMetric"); var metric = new Metric(MetricType.ProcessedEvents, "stats", true); metrics.SetMetric(metric); _storage.Verify(exp => exp.Set(It.Is <StorageKey>(k => k.Key == $"metric:{MetricType.ProcessedEvents}"), It.Is <IMetric>(m => (bool)m.Value == true)), Times.Once); }
protected void bbAdd_OnClick(object sender, EventArgs e) { int?metricId = hfMetricId.ValueAsInt(); var dateTimeArray = ddlInstanceTwo.SelectedValue.Split(','); var dateTime = dateTimeArray[0].AsDateTime(); var value = nbValue.Text.AsIntegerOrNull(); if (metricId == 0 || !dateTime.HasValue || !value.HasValue) { nbWarning.Text = "Unable to save. Please check you have selected an instance and input a value. Also ask your administrator to double check your Headcount Metric Sync Groups job is running."; nbWarning.Visible = true; return; } var rockContext = new RockContext(); var metricValueService = new MetricValueService(rockContext); var existingMetricValue = metricValueService.Queryable().FirstOrDefault(v => v.MetricValueDateTime.HasValue && v.MetricValueDateTime.Value == dateTime.Value && v.MetricId == metricId); if (existingMetricValue != null && !string.IsNullOrWhiteSpace(existingMetricValue.MetricValuePartitionEntityIds) && existingMetricValue.MetricValuePartitionEntityIds.Split(',').Any(partition => partition.Split('|')[0].AsInteger() == EntityTypeCache.Get(typeof(Campus)).Id&& partition.Split('|')[1].AsInteger() == ddlCampuses.SelectedValueAsId())) { nbWarning.Text = String.Format( "A metric value already existed for the {0}, the old value of {1} has been changed to {2}", dateTime.Value, Decimal.ToInt32(existingMetricValue.YValue.Value), value); nbWarning.Visible = true; existingMetricValue.YValue = value; } else { var metric = new MetricService(rockContext).Get(metricId.Value); var metricValue = new MetricValue(); metricValue.MetricValueDateTime = dateTime; metricValue.YValue = value; metricValue.MetricValuePartitions = new List <MetricValuePartition>(); var metricPartitionsByPosition = metric.MetricPartitions.OrderBy(a => a.Order).ToList(); foreach (var metricPartition in metricPartitionsByPosition) { var metricValuePartition = new MetricValuePartition(); metricValuePartition.MetricPartition = metricPartition; metricValuePartition.MetricPartitionId = metricPartition.Id; metricValuePartition.MetricValue = metricValue; metricValuePartition.EntityId = ddlCampuses.SelectedValueAsId(); metricValue.MetricValuePartitions.Add(metricValuePartition); } metricValue.MetricId = metricId.Value; metricValue.Note = "Input as a headcount metric value"; metricValueService.Add(metricValue); nbWarning.Text = ""; nbWarning.Visible = false; } nbValue.Text = ""; rockContext.SaveChanges(); BindGrid(); }
private FileTypeDetectionResponse DetectFromBytes(byte[] bytes) { TimeMetricTracker.Restart(); var fileTypeResponse = _fileTypeDetector.DetermineFileType(bytes); TimeMetricTracker.Stop(); MetricService.Record(Metric.DetectFileTypeTime, TimeMetricTracker.Elapsed); return(fileTypeResponse); }
private MetricService CreateService() { var service = new MetricService( _mockHttpClient.Object.ToHttpClient(), _mockAdobeAuthorizationService.Object); service.SetAuthValues(_authValues); return(service); }
public StatsCommand( TelegramService telegramService, MetricService metricService, BotService botService ) { _telegramService = telegramService; _metricService = metricService; _botService = botService; }
/// <summary> /// Binds the metric filter. /// </summary> private void BindMetricFilter() { ddlMetricFilter.Items.Clear(); var metricList = new MetricService().Queryable().OrderBy(m => m.Title).ToList(); foreach (Metric metric in metricList) { ddlMetricFilter.Items.Add(new ListItem(metric.Title, metric.Id.ToString())); } }
private Rock.Model.MetricValue BuildMetricValue(RockContext rockContext, DateTime requestDate) { var metric = new MetricService(rockContext).Queryable().First(); var metricValue = new Rock.Model.MetricValue(); metricValue.ForeignKey = metricValueForeignKey; metricValue.MetricValueDateTime = requestDate; metricValue.MetricId = metric.Id; return(metricValue); }
private string AnalyseFromBytes(ContentManagementFlags contentManagementFlags, string fileType, byte[] bytes) { contentManagementFlags = contentManagementFlags.ValidatedOrDefault(); TimeMetricTracker.Restart(); var response = _fileAnalyser.GetReport(contentManagementFlags, fileType, bytes); TimeMetricTracker.Stop(); MetricService.Record(Metric.AnalyseTime, TimeMetricTracker.Elapsed); return(response); }
private IFileProtectResponse RebuildFromBytes(ContentManagementFlags contentManagementFlags, string fileType, byte[] bytes) { contentManagementFlags = contentManagementFlags.ValidatedOrDefault(); TimeMetricTracker.Restart(); var response = _fileProtector.GetProtectedFile(contentManagementFlags, fileType, bytes); TimeMetricTracker.Stop(); MetricService.Record(Metric.RebuildTime, TimeMetricTracker.Elapsed); return(response); }
public static void CommitCache() { if (!_cachedMetrics.Any()) { throw new InvalidOperationException("No cached metrics to commit"); } using (var service = new MetricService()) { service.AddRange(_cachedMetrics); } }
protected override void ExecuteTest() { service = new MetricService<SomeMetricInstanceSetRequest>(metricMetadataTreeService, metricDataService, metricInstanceTreeFactory, metricNodeResolver); metricBase = service.Get(suppliedMetricInstanceSetRequest); }