public void Sub(MetricCollection other) { for (int i = 0; i < metrics.Length; i++) { metrics[i].Sub(other.metrics[i]); } }
/// <summary> /// Build a suitable collection of valid Metrics based on the selected MetricSet. /// <remarks>An empty MetricSet will result in all metrics being added, with the exception of Project /// level metrics which are always omitted.</remarks> /// </summary> /// <param name="metricSet">Selected MetricSet, acting as a filter on the columns to be displayed.</param> /// <returns></returns> protected MetricCollection ChooseMetrics(MetricSet metricSet) { MetricCollection rval = new MetricCollection(); foreach (Metric m in KrakatauSettings.Settings.Metrics) { bool include = false; if (m.Level == MetricLevel.Project) { include = false; } else if (metricSet == null) { include = true; } else { include = metricSet.Contains(m); } if (include) { rval.Add(m); } } return(rval); }
public void SetValueFrom(MetricCollection other) { for (int i = 0; i < metrics.Length; i++) { metrics[i].SetValueFrom(other.metrics[i]); } }
/// <summary> /// Retrieve the results from the database, building a crosstab with key Sourcefile attributes followed by all the /// metrics in the selected MetricSet (if any). /// </summary> /// <param name="set">DataSet into which the results should be added.</param> /// <param name="tableName"></param> /// <param name="tableName">Desired name for the results table.</param> /// <param name="metricSet">Selected MetricSet to use as a filter (may be null to include all metrics).</param> public void GetResults(DataSet set, string tableName, MetricSet metricSet) { lock (_semaphore) { if ((_cmdResults == null) || (_cmdResults.Connection != Connection)) { string sql = "SELECT sf.sfid, p.pr_name, sf.sf_shortname, sf.sf_type, cf.status, sm.mid, sm.mvalue " + "FROM sourcefile sf, comparefile cf, project p, sourcemetric sm " + "WHERE cf.sfid = sf.sfid " + "AND p.projid = sf.projid " + "AND sm.sfid = sf.sfid " + "AND sm.mvalue <> 0 " + "ORDER BY sf.sfid, sm.mid"; _cmdResults = new MySqlCommand(sql, Connection); _cmdResults.Prepare(); } } MetricCollection metrics = ChooseMetrics(metricSet); DataTable table = BuildTable(set, tableName, metrics); MySqlDataReader dr = _cmdResults.ExecuteReader(); DataRow row = null; long id; long prevousId = -1; long mid = 0; Metric m = null; while (dr.Read()) { id = long.Parse(dr["sfid"].ToString()); if (id != prevousId) { row = table.NewRow(); table.Rows.Add(row); row["Project"] = dr["pr_name"].ToString(); row["Filename"] = dr["sf_shortname"].ToString(); row["Lang"] = dr["sf_type"].ToString(); row["Status"] = ChurnStatuses.GetShortCode(dr["status"].ToString()); } mid = long.Parse(dr["mid"].ToString()); if (metrics.Contains(mid)) { m = metrics[mid]; if (table.Columns.Contains(m.Code)) { row[m.Code] = double.Parse(dr["mvalue"].ToString()); } } prevousId = id; } }
public void MetricCollection_Ctor_Initializer() { var col = new MetricCollection { new Metric(MetricType.EventLog, "m", true) }; Assert.IsTrue(col.Get(MetricType.EventLog).Title == "m"); }
private void AreEqual(MetricCollection exp, MetricCollection act) { if (exp != null) { for (int i = 0; i < exp.Value.Count; i++) { AreEqual(exp.Value[i], act.Value[i]); } } }
public void MetricCollection_Get() { var metric = new Metric(MetricType.EventLog, "m", true); var col = new MetricCollection { metric }; Assert.AreSame(metric, col.Get(MetricType.EventLog)); }
private void AddExtraMetrics() { _tabIndex = 1; _mets1 = new SortedList(); _mets2 = new SortedList(); // Add the existing "reference" components to the start of the list MetricCollection metrics = KrakatauSettings.Settings.Metrics; Metric firstFile = null; Metric firstChanged = null; foreach (Metric m in metrics) { if (m.Type == MetricType.General && firstFile == null) { firstFile = m; } else if (m.Type == MetricType.Changed && firstChanged == null) { firstChanged = m; } } AddMetric(_mets1, grpFileMet, firstFile, chkMet1, chkLower1, txtLower1, chkUpper1, txtUpper1); AddMetric(_mets2, grpChgMet, firstChanged, chkMet2, chkLower2, txtLower2, chkUpper2, txtUpper2); foreach (Metric m in metrics) { if (m.Type == MetricType.General) { // Add the General metrics if (!_mets1.Contains(m.Id)) { AddMetric(_mets1, grpFileMet, m); } } else { // Add the Changed metrics if (!_mets2.Contains(m.Id)) { AddMetric(_mets2, grpChgMet, m); } } } SetLayout(_mets1, this.grpFileMet); SetLayout(_mets2, this.grpChgMet); this.btnOK.TabIndex = _tabIndex++; this.btnCancel.TabIndex = _tabIndex++; }
private static MetricCollection ReadMetricValues(string collectionSelfLink, string token) { string metricName = "Max RUs Per Second"; string readMetric = string.Format(ConstructUriString(metricName, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddMinutes(-10), "PT1H", collectionSelfLink)); var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var metricValues = client.GetStringAsync(readMetric).Result; MetricCollection results = JsonConvert.DeserializeObject <MetricCollection>(metricValues); return(results); }
/// <summary> /// Method to bind metrics to a TreeView control. /// </summary> private void BindMetrics() { MetricCollection metrics = new MetricCollection(); metrics.LoadByParentID( ArenaContext.Current.Organization.OrganizationID, -1 ); BuildMetricTreeView( metrics, null ); if ( ( tvMetrics.Nodes.Count == 0 ) || ( tvMetrics.Nodes[0].Nodes.Count == 0 ) ) { tvMetrics.Visible = false; } else if ( tvMetrics.Nodes.Count == 1 ) { tvMetrics.Nodes[0].Expanded = true; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, MetricCollection metricCollection, DbContext dbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } _logger.LogInformation("This is from logger"); app.Map("/metrics", Metrics); //default output app.Run(async(context) => { context.Response.ContentType = "text/plain; version=0.0.4; charset=utf-8"; await context.Response.WriteAsync("Prometheus SQL Wrapper"); }); }
protected void PopulateMetrics() { Metrics = new MetricCollection(); // Add the General metrics Metrics.Add(new Metric(100, MetricType.General, "LOC")); Metrics.Add(new Metric(101, MetricType.General, "SLOC")); Metrics.Add(new Metric(102, MetricType.General, "SLOC_NAT")); Metrics.Add(new Metric(103, MetricType.General, "SLOC_TAG")); Metrics.Add(new Metric(104, MetricType.General, "SLOC_HTM")); Metrics.Add(new Metric(105, MetricType.General, "SLOC_SCR")); Metrics.Add(new Metric(106, MetricType.General, "PLOC")); Metrics.Add(new Metric(107, MetricType.General, "LLOC")); Metrics.Add(new Metric(108, MetricType.General, "N1")); Metrics.Add(new Metric(109, MetricType.General, "N2")); Metrics.Add(new Metric(110, MetricType.General, "N1S")); Metrics.Add(new Metric(111, MetricType.General, "N2S")); Metrics.Add(new Metric(112, MetricType.General, "N")); Metrics.Add(new Metric(113, MetricType.General, "NS")); Metrics.Add(new Metric(114, MetricType.General, "V")); Metrics.Add(new Metric(115, MetricType.General, "D")); Metrics.Add(new Metric(116, MetricType.General, "E")); Metrics.Add(new Metric(117, MetricType.General, "B")); Metrics.Add(new Metric(118, MetricType.General, "J_COM")); Metrics.Add(new Metric(119, MetricType.General, "C_COM")); Metrics.Add(new Metric(120, MetricType.General, "CPP_COM")); Metrics.Add(new Metric(121, MetricType.General, "COM_LOC")); Metrics.Add(new Metric(122, MetricType.General, "BYTES")); Metrics.Add(new Metric(123, MetricType.General, "NFILE", MetricLevel.Project)); // Add the Changed metrics Metrics.Add(new Metric(124, MetricType.Changed, "CHG_SLOC")); Metrics.Add(new Metric(125, MetricType.Changed, "DEL_SLOC")); Metrics.Add(new Metric(126, MetricType.Changed, "ADD_SLOC")); Metrics.Add(new Metric(127, MetricType.Changed, "CRN_SLOC")); Metrics.Add(new Metric(128, MetricType.Changed, "CHG_LLOC")); Metrics.Add(new Metric(129, MetricType.Changed, "DEL_LLOC")); Metrics.Add(new Metric(130, MetricType.Changed, "ADD_LLOC")); Metrics.Add(new Metric(131, MetricType.Changed, "CRN_LLOC")); Metrics.Add(new Metric(132, MetricType.Changed, "CHG_FILE", MetricLevel.Project)); Metrics.Add(new Metric(133, MetricType.Changed, "DEL_FILE", MetricLevel.Project)); Metrics.Add(new Metric(134, MetricType.Changed, "ADD_FILE", MetricLevel.Project)); Metrics.Add(new Metric(135, MetricType.Changed, "CRN_FILE", MetricLevel.Project)); }
public MetricCollection AnalyzeSolution(Solution solution) { var namespaces = new HashSet <string>(); var metricCollection = new MetricCollection(solution.FilePath.Split('\\').Last()); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { ConsolePrinter.PrintStatus(Operation.Analyzing, document.FilePath); metricCollection.TotalNumberOfClasses += GetNumberOfClasses(document); metricCollection.TotalNumberOfMethods += GetNumberOfMethods(document); namespaces.UnionWith(GetNumberOfNamespaces(document)); metricCollection.CyclomaticComplexity += CalculateCyclomaticComplexity(document); metricCollection.TotalLinesOfCode += CalculateLinesOfCode(document); } } metricCollection.TotalNumberOfNamespaces = namespaces.Count; return(metricCollection); }
// Adjust lists to include empty methods in diff|base for methods that appear only in base|diff. // Also adjust delta to take these methods into account. public void Reconcile() { List <MethodDelta> reconciles = new List <MethodDelta>(); reconciledBaseMetrics = new MetricCollection(); reconciledDiffMetrics = new MetricCollection(); foreach (MethodInfo m in methodsOnlyInBase) { reconciles.Add(new MethodDelta { name = m.name, baseMetrics = new MetricCollection(m.Metrics), diffMetrics = new MetricCollection(), baseOffsets = m.functionOffsets, diffOffsets = null }); baseMetrics.Add(m.Metrics); reconciledBaseMetrics.Add(m.Metrics); reconciledCountBase++; } foreach (MethodInfo m in methodsOnlyInDiff) { reconciles.Add(new MethodDelta { name = m.name, baseMetrics = new MetricCollection(), diffMetrics = new MetricCollection(m.Metrics), baseOffsets = null, diffOffsets = m.functionOffsets }); diffMetrics.Add(m.Metrics); reconciledDiffMetrics.Add(m.Metrics); reconciledCountDiff++; } methodDeltaList = methodDeltaList.Concat(reconciles); deltaMetrics.Sub(reconciledBaseMetrics); deltaMetrics.Add(reconciledDiffMetrics); }
public void GetMetricsTest() { MetricCollection expectedMetricCollection = GetMetricCollection(ResourceUri); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(expectedMetricCollection.ToJson()) }; RecordedDelegatingHandler handler = new RecordedDelegatingHandler(response); var insightsClient = GetInsightsClient(handler); string filterString = "timeGrain eq duration'PT1M' and startTime eq 2014-01-01T06:00:00Z and endTime eq 2014-01-10T06:00:00Z"; MetricListResponse actualMetrics = (insightsClient.MetricOperations as MetricOperations) .GetMetricsAsync( ResourceUri, filterString, CancellationToken.None).Result; AreEqual(expectedMetricCollection, actualMetrics.MetricCollection); }
private void BuildMetricTreeView( MetricCollection metrics, TreeViewNode parentNode ) { foreach ( Arena.Metric.Metric metric in metrics ) { TreeViewNode node = new TreeViewNode(); if ( metric.Permissions.Allowed( OperationType.View, ArenaContext.Current.User ) ) { node.Text = metric.Title; node.ShowCheckBox = true; node.Value = metric.MetricID.ToString(); node.ID = metric.MetricID.ToString(); node.ImageUrl = "~/images/add_metric.gif"; node.Visible = true; if ( parentNode == null ) { // add the root, parent node tvMetrics.Nodes.Add( node ); } else { parentNode.Nodes.Add( node ); } if ( metric.ChildMetrics.Count > 0 ) { BuildMetricTreeView( metric.ChildMetrics, node ); } } if ( parentNode == null ) { if ( node.Nodes.Count != 0 ) { continue; } tvMetrics.Nodes.Remove( node ); } } }
private void validate() { if (_basePath == null) { _syntaxResult.ReportError("Base path (--base) is required."); } if (_diffPath == null) { _syntaxResult.ReportError("Diff path (--diff) is required."); } if (_metric == null) { _metric = "CodeSize"; } if (!MetricCollection.ValidateMetric(_metric)) { _syntaxResult.ReportError($"Unknown metric '{_metric}'. Available metrics: {MetricCollection.ListMetrics()}"); } }
/// <summary> /// Create the DataTable with appropriate columns based on the MetricsCollection that has been prepared. /// </summary> /// <param name="set">DataSet used to hold the table.</param> /// <param name="tableName">Desired name for the results table.</param> /// <param name="metrics">Collection of metrics to be included in the table.</param> /// <returns></returns> public DataTable BuildTable(DataSet set, string tableName, MetricCollection metrics) { if (set.Tables.Contains(tableName)) { set.Tables.Remove(tableName); } DataTable table = set.Tables.Add(tableName); Type typeString = Type.GetType("System.String"); Type typeLong = Type.GetType("System.Int32"); Type typeDouble = Type.GetType("System.Double"); DataColumn col = table.Columns.Add("Project", typeString); col = table.Columns.Add("Filename", typeString); col = table.Columns.Add("Lang", typeString); col = table.Columns.Add("Status", typeString); foreach (Metric m in metrics) { col = table.Columns.Add(m.Code, typeDouble); } return(table); }
public MethodInfo() { metrics = new MetricCollection(); }
public void MetricCollection_Ctor() { var col = new MetricCollection(); }
public MetricCollection(MetricCollection other) : this() { this.SetValueFrom(other); }
/// <summary> /// The List Metric operation lists the metric value sets for the /// resource metrics. /// </summary> /// <param name='resourceUri'> /// Required. The uri of the target resource to get metrics for. /// </param> /// <param name='filterString'> /// Required. An OData $filter expression that supports querying by the /// name of the metric definition. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric values operation response. /// </returns> public async Task <MetricListResponse> GetMetricsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); Tracing.Enter(invocationId, this, "GetMetricsAsync", tracingParameters); } // Construct URL string url = "/" + resourceUri.Trim() + "/metrics?"; url = url + "api-version=2014-04-01"; if (filterString != null) { url = url + "&$filter=" + Uri.EscapeDataString(filterString != null ? filterString.Trim() : ""); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result MetricListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricCollection metricCollectionInstance = new MetricCollection(); result.MetricCollection = metricCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Metric metricInstance = new Metric(); metricCollectionInstance.Value.Add(metricInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricInstance.Unit = unitInstance; } JToken timeGrainValue = valueValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue)); metricInstance.TimeGrain = timeGrainInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricInstance.StartTime = startTimeInstance; } JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricInstance.EndTime = endTimeInstance; } JToken metricValuesArray = valueValue["metricValues"]; if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null) { foreach (JToken metricValuesValue in ((JArray)metricValuesArray)) { MetricValue metricValueInstance = new MetricValue(); metricInstance.MetricValues.Add(metricValueInstance); JToken timestampValue = metricValuesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); metricValueInstance.Timestamp = timestampInstance; } JToken averageValue = metricValuesValue["average"]; if (averageValue != null && averageValue.Type != JTokenType.Null) { double averageInstance = ((double)averageValue); metricValueInstance.Average = averageInstance; } JToken minimumValue = metricValuesValue["minimum"]; if (minimumValue != null && minimumValue.Type != JTokenType.Null) { double minimumInstance = ((double)minimumValue); metricValueInstance.Minimum = minimumInstance; } JToken maximumValue = metricValuesValue["maximum"]; if (maximumValue != null && maximumValue.Type != JTokenType.Null) { double maximumInstance = ((double)maximumValue); metricValueInstance.Maximum = maximumInstance; } JToken totalValue = metricValuesValue["total"]; if (totalValue != null && totalValue.Type != JTokenType.Null) { double totalInstance = ((double)totalValue); metricValueInstance.Total = totalInstance; } JToken countValue = metricValuesValue["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); metricValueInstance.Count = countInstance; } JToken lastValue = metricValuesValue["last"]; if (lastValue != null && lastValue.Type != JTokenType.Null) { double lastInstance = ((double)lastValue); metricValueInstance.Last = lastInstance; } JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricValueInstance.Properties.Add(propertiesKey, propertiesValue); } } } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricInstance.ResourceId = resourceIdInstance; } JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]); if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in propertiesSequenceElement2) { string propertiesKey2 = ((string)property2.Name); string propertiesValue2 = ((string)property2.Value); metricInstance.Properties.Add(propertiesKey2, propertiesValue2); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public void MetricCollection_Add() { var col = new MetricCollection(); col.Add(new Metric(MetricType.EventLog, "m", true)); }
public void ParseFile() { XmlTextReader txtreader = null; XmlReader reader = null; IEnumerator el, ef, ee = null; try { // Load the reader with the data file and ignore all whitespace nodes. txtreader = new XmlTextReader(UserConfigFile.FullName); txtreader.WhitespaceHandling = WhitespaceHandling.None; reader = XmlReader.Create(txtreader.GetRemainder()); _doc.Load(reader); XmlNode root = _doc.DocumentElement; XmlNode lang; XmlNode ftype; XmlNode ext; XmlNode a, a2, au, al; Hashtable ftypes; Hashtable exts; string sLang, sFiletype; MetricCollection metrics = KrakatauSettings.Settings.Metrics; el = root.ChildNodes.GetEnumerator(); while (el.MoveNext()) { lang = (XmlNode)el.Current; if (lang.Name.Equals("lang")) { a = lang.Attributes.GetNamedItem("name"); if (a != null && !"".Equals(a.Value)) { sLang = a.Value; ftypes = new Hashtable(); _config.Add(sLang, ftypes); ef = lang.ChildNodes.GetEnumerator(); while (ef.MoveNext()) { ftype = (XmlNode)ef.Current; if (ftype.Name.Equals("filetype")) { a = ftype.Attributes.GetNamedItem("name"); if (a != null && !"".Equals(a.Value)) { sFiletype = a.Value; exts = new Hashtable(); ftypes.Add(sFiletype, exts); ee = ftype.ChildNodes.GetEnumerator(); while (ee.MoveNext()) { ext = (XmlNode)ee.Current; a = ext.Attributes.GetNamedItem("name"); a2 = ext.Attributes.GetNamedItem("value"); if (a != null && !"".Equals(a.Value) && a2 != null && !"".Equals(a2.Value)) { Ext e = new Ext(a.Value, a2.Value, sFiletype, sLang); exts.Add(e.Extension, e); _list.Add(e.ToString(), e); } } } } } } } else if (lang.Name.Equals("sets")) { ef = lang.ChildNodes.GetEnumerator(); while (ef.MoveNext()) { ftype = (XmlNode)ef.Current; if (ftype.Name.Equals("set")) { a = ftype.Attributes.GetNamedItem("name"); if (a != null && !"".Equals(a.Value)) { MetricSet ms = new MetricSet(a.Value); _sets.Add(ms.Name, ms); ee = ftype.ChildNodes.GetEnumerator(); while (ee.MoveNext()) { ext = (XmlNode)ee.Current; a = ext.Attributes.GetNamedItem("id"); au = ext.Attributes.GetNamedItem("upper"); al = ext.Attributes.GetNamedItem("lower"); if (a != null && !"".Equals(a.Value)) { MetricDef md = new MetricDef(metrics[long.Parse(a.Value)]); if (au != null && !"".Equals(au.Value)) { md.Upper(long.Parse(au.Value)); } if (al != null && !"".Equals(al.Value)) { md.Lower(long.Parse(al.Value)); } ms.Add(md); } } } } } // Now remove the Metric Sets as they will be rebuilt during application execution. root.RemoveChild(lang); } } } finally { if (reader != null) { reader.Close(); } } }
public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, TraceWriter log) { _subscriptionId = GetEnvironmentVariable("subscriptionId"); _tenantId = GetEnvironmentVariable("tenantId"); _applicationId = GetEnvironmentVariable("applicationId"); _applicationPwd = GetEnvironmentVariable("applicationPwd"); _resourceGroupName = GetEnvironmentVariable("resourceGroupName"); _accountName = GetEnvironmentVariable("accountName"); _accountUri = GetEnvironmentVariable("accountUri"); _accountKey = GetEnvironmentVariable("authKey"); _dbName = GetEnvironmentVariable("dbName"); _collName = GetEnvironmentVariable("collName"); _maxAllowedThroughput = GetEnvironmentVariable("maxAllowedThroughput"); _minAllowedThroughput = GetEnvironmentVariable("minAllowedThroughput"); _throughputStep = GetEnvironmentVariable("throughputStep"); //Console.WriteLine("accountUri: " + _accountUri); log.Info($"Timer trigger function executed at: {DateTime.Now}"); docDbClient = new DocumentClient( new Uri(_accountUri), _accountKey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }); DocumentCollection collection = GetCollection(_dbName, _collName); Uri collectionUri = UriFactory.CreateDocumentCollectionUri(_dbName, collection.Id); FeedResponse <PartitionKeyRange> pkRanges = docDbClient.ReadPartitionKeyRangeFeedAsync( collectionUri).Result; int partitionCount = pkRanges.Count; log.Info($"The number of partitions in the collection is {partitionCount}"); int provisionedThroughput = GetOfferThroughput(collection.SelfLink); log.Info($"Provisioned throughtput is {provisionedThroughput}"); int partitionThroughput = provisionedThroughput / partitionCount; MetricCollection metricList = ReadMetricValues(collection.SelfLink, GetAccessToken()); int throughputIncrease = 0; bool isCollectionBusy = false; bool isCollectionOverProvisioned = true; foreach (var metric in metricList.Value) { foreach (var metricValue in metric.MetricValues) { log.Info($"Max RUs Per Second is {metricValue.Maximum}. Throughtput per partition is {partitionThroughput}"); if (metricValue.Maximum > partitionThroughput) { isCollectionBusy = true; isCollectionOverProvisioned = false; log.Info($"Partition throughput increased more than provisioned at {metricValue.Maximum} - {metricValue.Timestamp}"); throughputIncrease = (int)metricValue.Maximum * partitionCount; break; } else if (partitionThroughput > metricValue.Maximum) { isCollectionOverProvisioned = true; } } } if (isCollectionBusy) { if (throughputIncrease > Int32.Parse(_maxAllowedThroughput)) { log.Info($"Max throughput limit reached - {_maxAllowedThroughput}. Cannot scale up further"); ScaleOffer(_dbName, _collName, Int32.Parse(_maxAllowedThroughput)); return; } log.Info($"Scaling up collection {_collName} throughput to {throughputIncrease}"); ScaleOffer(_dbName, _collName, throughputIncrease); } if (isCollectionOverProvisioned) { throughputIncrease = partitionThroughput - Int32.Parse(_throughputStep); if (Int32.Parse(_minAllowedThroughput) > throughputIncrease) { log.Info($"Min throughput limit reached - {_minAllowedThroughput}. Cannot scale down further"); ScaleOffer(_dbName, _collName, Int32.Parse(_minAllowedThroughput)); return; } log.Info($"Scaling down collection {_collName} throughput to {throughputIncrease}"); ScaleOffer(_dbName, _collName, throughputIncrease); } log.Info($"Completed execution at: {DateTime.Now}"); }