├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── Program.cs
├── README.md
└── project.json
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # MSTest test Results
33 | [Tt]est[Rr]esult*/
34 | [Bb]uild[Ll]og.*
35 |
36 | # NUNIT
37 | *.VisualState.xml
38 | TestResult.xml
39 |
40 | # Build Results of an ATL Project
41 | [Dd]ebugPS/
42 | [Rr]eleasePS/
43 | dlldata.c
44 |
45 | # .NET Core
46 | project.lock.json
47 | project.fragment.lock.json
48 | artifacts/
49 | **/Properties/launchSettings.json
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 | *.VC.db
88 | *.VC.VC.opendb
89 |
90 | # Visual Studio profiler
91 | *.psess
92 | *.vsp
93 | *.vspx
94 | *.sap
95 |
96 | # TFS 2012 Local Workspace
97 | $tf/
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 | *.DotSettings.user
106 |
107 | # JustCode is a .NET coding add-in
108 | .JustCode
109 |
110 | # TeamCity is a build add-in
111 | _TeamCity*
112 |
113 | # DotCover is a Code Coverage Tool
114 | *.dotCover
115 |
116 | # Visual Studio code coverage results
117 | *.coverage
118 | *.coveragexml
119 |
120 | # NCrunch
121 | _NCrunch_*
122 | .*crunch*.local.xml
123 | nCrunchTemp_*
124 |
125 | # MightyMoose
126 | *.mm.*
127 | AutoTest.Net/
128 |
129 | # Web workbench (sass)
130 | .sass-cache/
131 |
132 | # Installshield output folder
133 | [Ee]xpress/
134 |
135 | # DocProject is a documentation generator add-in
136 | DocProject/buildhelp/
137 | DocProject/Help/*.HxT
138 | DocProject/Help/*.HxC
139 | DocProject/Help/*.hhc
140 | DocProject/Help/*.hhk
141 | DocProject/Help/*.hhp
142 | DocProject/Help/Html2
143 | DocProject/Help/html
144 |
145 | # Click-Once directory
146 | publish/
147 |
148 | # Publish Web Output
149 | *.[Pp]ublish.xml
150 | *.azurePubxml
151 | # TODO: Comment the next line if you want to checkin your web deploy settings
152 | # but database connection strings (with potential passwords) will be unencrypted
153 | *.pubxml
154 | *.publishproj
155 |
156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
157 | # checkin your Azure Web App publish settings, but sensitive information contained
158 | # in these scripts will be unencrypted
159 | PublishScripts/
160 |
161 | # NuGet Packages
162 | *.nupkg
163 | # The packages folder can be ignored because of Package Restore
164 | **/packages/*
165 | # except build/, which is used as an MSBuild target.
166 | !**/packages/build/
167 | # Uncomment if necessary however generally it will be regenerated when needed
168 | #!**/packages/repositories.config
169 | # NuGet v3's project.json files produces more ignorable files
170 | *.nuget.props
171 | *.nuget.targets
172 |
173 | # Microsoft Azure Build Output
174 | csx/
175 | *.build.csdef
176 |
177 | # Microsoft Azure Emulator
178 | ecf/
179 | rcf/
180 |
181 | # Windows Store app package directories and files
182 | AppPackages/
183 | BundleArtifacts/
184 | Package.StoreAssociation.xml
185 | _pkginfo.txt
186 |
187 | # Visual Studio cache files
188 | # files ending in .cache can be ignored
189 | *.[Cc]ache
190 | # but keep track of directories ending in .cache
191 | !*.[Cc]ache/
192 |
193 | # Others
194 | ClientBin/
195 | ~$*
196 | *~
197 | *.dbmdl
198 | *.dbproj.schemaview
199 | *.jfm
200 | *.pfx
201 | *.publishsettings
202 | orleans.codegen.cs
203 |
204 | # Since there are multiple workflows, uncomment next line to ignore bower_components
205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
206 | #bower_components/
207 |
208 | # RIA/Silverlight projects
209 | Generated_Code/
210 |
211 | # Backup & report files from converting an old project file
212 | # to a newer Visual Studio version. Backup files are not needed,
213 | # because we have git ;-)
214 | _UpgradeReport_Files/
215 | Backup*/
216 | UpgradeLog*.XML
217 | UpgradeLog*.htm
218 |
219 | # SQL Server files
220 | *.mdf
221 | *.ldf
222 | *.ndf
223 |
224 | # Business Intelligence projects
225 | *.rdl.data
226 | *.bim.layout
227 | *.bim_*.settings
228 |
229 | # Microsoft Fakes
230 | FakesAssemblies/
231 |
232 | # GhostDoc plugin setting file
233 | *.GhostDoc.xml
234 |
235 | # Node.js Tools for Visual Studio
236 | .ntvs_analysis.dat
237 | node_modules/
238 |
239 | # Typescript v1 declaration files
240 | typings/
241 |
242 | # Visual Studio 6 build log
243 | *.plg
244 |
245 | # Visual Studio 6 workspace options file
246 | *.opt
247 |
248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
249 | *.vbw
250 |
251 | # Visual Studio LightSwitch build output
252 | **/*.HTMLClient/GeneratedArtifacts
253 | **/*.DesktopClient/GeneratedArtifacts
254 | **/*.DesktopClient/ModelManifest.xml
255 | **/*.Server/GeneratedArtifacts
256 | **/*.Server/ModelManifest.xml
257 | _Pvt_Extensions
258 |
259 | # Paket dependency manager
260 | .paket/paket.exe
261 | paket-files/
262 |
263 | # FAKE - F# Make
264 | .fake/
265 |
266 | # JetBrains Rider
267 | .idea/
268 | *.sln.iml
269 |
270 | # CodeRush
271 | .cr/
272 |
273 | # Python Tools for Visual Studio (PTVS)
274 | __pycache__/
275 | *.pyc
276 |
277 | # Cake - Uncomment if you are using it
278 | # tools/**
279 | # !tools/packages.config
280 |
281 | # Telerik's JustMock configuration file
282 | *.jmconfig
283 |
284 | # BizTalk build output
285 | *.btp.cs
286 | *.btm.cs
287 | *.odx.cs
288 | *.xsd.cs
289 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## Azure-Samples/monitor-dotnet-metrics-api Changelog
2 |
3 |
4 | # 1.0.2 (2017-10-09)
5 |
6 | *Features*
7 | * Initial release of the code sample
8 | * Retrieves metrics and metric definitions using the Monitor's single-dimensional metrics API.
9 |
10 | *Bug Fixes*
11 | * Adding some documentation and new CONTRIBUTING.md, CHANGELOG.md (this file,) and LICENSE.md files.
12 |
13 | *Breaking Changes*
14 | * None
15 |
16 |
17 | # 1.0.1 (2017-09-21)
18 |
19 | *Features*
20 | * Initial release of the code sample
21 | * Retrieves metrics and metric definitions using the Monitor's single-dimensional metrics API.
22 |
23 | *Bug Fixes*
24 | * Fixed error in $filter parameters of the metric definitions call sample.
25 |
26 | *Breaking Changes*
27 | * None
28 |
29 |
30 | # 1.0.0 (2017-06-08)
31 |
32 | *Features*
33 | * Initial release of the code sample
34 | * Retrieves metrics and metric definitions using the Monitor's single-dimensional metrics API.
35 |
36 | *Bug Fixes*
37 | * None
38 |
39 | *Breaking Changes*
40 | * None
41 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Azure-Samples/monitor-dotnet-metrics-api
2 |
3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a
4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
5 | the rights to use your contribution. For details, visit https://cla.microsoft.com.
6 |
7 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
8 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
9 | provided by the bot. You will only need to do this once across all repos using our CLA.
10 |
11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
14 |
15 | - [Code of Conduct](#coc)
16 | - [Issues and Bugs](#issue)
17 | - [Feature Requests](#feature)
18 | - [Submission Guidelines](#submit)
19 |
20 | ## Code of Conduct
21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
22 |
23 | ## Found an Issue?
24 | If you find a bug in the source code or a mistake in the documentation, you can help us by
25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
26 | [submit a Pull Request](#submit-pr) with a fix.
27 |
28 | ## Want a Feature?
29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
30 | Repository. If you would like to *implement* a new feature, please submit an issue with
31 | a proposal for your work first, to be sure that we can use it.
32 |
33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
34 |
35 | ## Submission Guidelines
36 |
37 | ### Submitting an Issue
38 | Before you submit an issue, search the archive, maybe your question was already answered.
39 |
40 | If your issue appears to be a bug, and hasn't been reported, open a new issue.
41 | Help us to maximize the effort we can spend fixing issues and adding new
42 | features, by not reporting duplicate issues. Providing the following information will increase the
43 | chances of your issue being dealt with quickly:
44 |
45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
46 | * **Version** - what version is affected (e.g. 0.1.2)
47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
48 | * **Browsers and Operating System** - is this a problem with all browsers?
49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps
50 | * **Related Issues** - has a similar issue been reported before?
51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
52 | causing the problem (line of code or commit)
53 |
54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
55 |
56 | ### Submitting a Pull Request (PR)
57 | Before you submit your Pull Request (PR) consider the following guidelines:
58 |
59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
60 | that relates to your submission. You don't want to duplicate effort.
61 |
62 | * Make your changes in a new git fork:
63 |
64 | * Commit your changes using a descriptive commit message
65 | * Push your fork to GitHub:
66 | * In GitHub, create a pull request
67 | * If we suggest changes then:
68 | * Make the required updates.
69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
70 |
71 | ```shell
72 | git rebase master -i
73 | git push -f
74 | ```
75 |
76 | That's it! Thank you for your contribution!
77 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation. All rights reserved.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE
--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading;
5 | using System.Threading.Tasks;
6 |
7 | // Azure Management dependencies
8 | using Microsoft.Rest.Azure.Authentication;
9 | using Microsoft.Rest.Azure.OData;
10 |
11 | // These examples correspond to the Monitor .Net SDK versions 0.16.0-preview and 0.16.1-preview
12 | // Those versions include the single-dimensional metrics API.
13 | using Microsoft.Azure.Management.Monitor;
14 | using Microsoft.Azure.Management.Monitor.Models;
15 |
16 | namespace AzureMonitorCSharpExamples
17 | {
18 | public class Program
19 | {
20 | private static MonitorClient readOnlyClient;
21 |
22 | public static void Main(string[] args)
23 | {
24 | if (args.Length < 1)
25 | {
26 | throw new ArgumentException("Usage: AzureMonitorCSharpExamples ");
27 | }
28 |
29 | var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
30 | var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
31 | var secret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
32 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
33 | if (new List { tenantId, clientId, secret, subscriptionId }.Any(i => String.IsNullOrEmpty(i)))
34 | {
35 | Console.WriteLine("Please provide environment variables for AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_SUBSCRIPTION_ID.");
36 | }
37 | else
38 | {
39 | readOnlyClient = AuthenticateWithReadOnlyClient(tenantId, clientId, secret, subscriptionId).Result;
40 | var resourceId = args[1];
41 |
42 | RunMetricDefinitionsSample(readOnlyClient, resourceId).Wait();
43 | RunMetricsSample(readOnlyClient, resourceId).Wait();
44 | }
45 | }
46 |
47 | #region Authentication
48 | private static async Task AuthenticateWithReadOnlyClient(string tenantId, string clientId, string secret, string subscriptionId)
49 | {
50 | // Build the service credentials and Monitor client
51 | var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
52 | var monitorClient = new MonitorClient(serviceCreds);
53 | monitorClient.SubscriptionId = subscriptionId;
54 |
55 | return monitorClient;
56 | }
57 | #endregion
58 |
59 | #region Examples
60 | private static async Task RunMetricDefinitionsSample(MonitorClient readOnlyClient, string resourceUri)
61 | {
62 | // Get metrics definitions
63 | IEnumerable metricDefinitions = await readOnlyClient.MetricDefinitions.ListAsync(resourceUri: resourceUri, cancellationToken: new CancellationToken());
64 | EnumerateMetricDefinitions(metricDefinitions);
65 |
66 | // The $filter can contain a propositional logic expression, specifically, a disjunction of the format: name.value eq '' or name.value eq '' ...
67 | var odataFilterMetricDef = new ODataQuery("name.value eq 'CpuPercentage'");
68 | metricDefinitions = await readOnlyClient.MetricDefinitions.ListAsync(resourceUri: resourceUri, odataQuery: odataFilterMetricDef, cancellationToken: new CancellationToken());
69 |
70 | EnumerateMetricDefinitions(metricDefinitions);
71 | }
72 |
73 | private static async Task RunMetricsSample(MonitorClient readOnlyClient, string resourceUri)
74 | {
75 | Write("Call without filter parameter (i.e. $filter = null)");
76 | IEnumerable metrics = await readOnlyClient.Metrics.ListAsync(resourceUri: resourceUri, cancellationToken: CancellationToken.None);
77 | EnumerateMetrics(metrics);
78 |
79 | // The $filter can contain a propositional logic expression, specifically, a disjunction of the format: [(]name.value eq '' or name.value eq '' ...[)]
80 | var metricNames = "name.value eq 'CpuPercentage'"; // could be concatenated with " or name.value eq ''" ... inside parentheses for more than one name.
81 |
82 | // The $filter can include time grain, which is optional when metricNames is present. The is forms a conjunction with the list of metric names described above.
83 | string timeGrain = " and timeGrain eq duration'PT5M'";
84 |
85 | // The $filter can also include a time range for the query; also a conjunction with the list of metrics and/or the time grain. Defaulting to 3 hours before the time of execution for these datetimes
86 | string startDate = string.Format(" and startTime eq {0}", DateTime.Now.AddHours(-3).ToString("o"));
87 | string endDate = string.Format(" and endTime eq {0}", DateTime.Now.ToString("o"));
88 |
89 | var odataFilterMetrics = new ODataQuery(
90 | string.Format(
91 | "{0}{1}{2}{3}",
92 | metricNames,
93 | timeGrain,
94 | startDate,
95 | endDate));
96 |
97 | Write("Call with filter parameter (i.e. $filter = {0})", odataFilterMetrics);
98 | metrics = await readOnlyClient.Metrics.ListAsync(resourceUri: resourceUri, odataQuery: odataFilterMetrics, cancellationToken: CancellationToken.None);
99 | EnumerateMetrics(metrics);
100 | }
101 | #endregion
102 |
103 | #region Helpers
104 | private static void Write(string format, params object[] items)
105 | {
106 | Console.WriteLine(string.Format(format, items));
107 | }
108 |
109 | private static void EnumerateMetricDefinitions(IEnumerable metricDefinitions, int maxRecords = 5)
110 | {
111 | var numRecords = 0;
112 | /* Structure of MetricDefinition
113 | string ResourceId
114 | LocalizableString Name
115 | Unit? Unit
116 | AggregationType? PrimaryAggregationType
117 | IList MetricAvailabilities
118 | string Id
119 | */
120 | foreach (var metricDefinition in metricDefinitions)
121 | {
122 | Write(
123 | "Id: {0}\n Name: {1}, {2}\nResourceId: {3}\nUnit: {4}\nPrimary aggregation type: {5}\nList of metric availabilities: {6}",
124 | metricDefinition.Id,
125 | metricDefinition.Name.Value,
126 | metricDefinition.Name.LocalizedValue,
127 | metricDefinition.ResourceId,
128 | metricDefinition.Unit,
129 | metricDefinition.PrimaryAggregationType,
130 | metricDefinition.MetricAvailabilities);
131 |
132 | // Display only maxRecords records at most
133 | numRecords++;
134 | if (numRecords >= maxRecords)
135 | {
136 | break;
137 | }
138 | }
139 | }
140 |
141 | private static void EnumerateMetrics(IEnumerable metrics, int maxRecords = 5)
142 | {
143 | var numRecords = 0;
144 | /* Structure of MetricMetric
145 | string ResourceId
146 | LocalizableString Name
147 | Unit? Unit
148 | string Type
149 | IList Data
150 | string Id
151 | */
152 | Write("Id\tName.Value\tName.Localized\tType\tUnit\tData");
153 | foreach (var metric in metrics)
154 | {
155 | Write(
156 | "{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
157 | metric.Id,
158 | metric.Name.Value,
159 | metric.Name.LocalizedValue,
160 | metric.Type,
161 | metric.Unit,
162 | metric.Data);
163 |
164 | // Display only 5 records at most
165 | numRecords++;
166 | if (numRecords >= maxRecords)
167 | {
168 | break;
169 | }
170 | }
171 | }
172 | #endregion
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This sample explains how to retrieve Monitor metrics and metric definitions using the Azure .NET SDK releases 0.16.0-preview and 0.16.1-preview."
8 | urlFragment: monitor-dotnet-metrics-api
9 | ---
10 |
11 | # Retrieve Azure Monitor metrics with .NET
12 |
13 | This sample explains how to retrieve Monitor metrics and metric definitions using the Azure .NET SDK releases 0.16.0-preview and 0.16.1-preview.
14 |
15 | **NOTE**: please refer to the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct).
16 |
17 | **NOTE**: for contributions refer to the [CONTRIBUTING.md](https://github.com/Azure-Samples/monitor-dotnet-metrics-api/blob/master/CONTRIBUTING.md) file.
18 |
19 | **On this page**
20 |
21 | - [Run this sample](#run)
22 | - [What is program.cs doing?](#example)
23 | - [List metric definitions for a resource](#list-metricdefinitions)
24 | - [List metrics for a resource](#list-metrics)
25 |
26 |
27 | ## Run this sample
28 |
29 | 1. If you don't have it, install the [.NET Core SDK](https://www.microsoft.com/net/core).
30 |
31 | 1. Clone the repository.
32 |
33 | ```
34 | git clone https://github.com/Azure-Samples/monitor-dotnet-metrics-api.git
35 | ```
36 |
37 | 1. Install the dependencies.
38 |
39 | ```
40 | dotnet restore
41 | ```
42 |
43 | 1. Create an Azure service principal either through
44 | [Azure CLI](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/),
45 | [PowerShell](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal/)
46 | or [the portal](https://azure.microsoft.com/documentation/articles/resource-group-create-service-principal-portal/).
47 |
48 | 1. Export these environment variables using your subscription id and the tenant id, client id and client secret from the service principal that you created.
49 |
50 | ```
51 | export AZURE_TENANT_ID={your tenant id}
52 | export AZURE_CLIENT_ID={your client id}
53 | export AZURE_CLIENT_SECRET={your client secret}
54 | export AZURE_SUBSCRIPTION_ID={your subscription id}
55 | ```
56 |
57 | 1. Run the sample.
58 |
59 | ```
60 | dotnet run program
61 | ```
62 |
63 |
64 | ## What is program.cs doing?
65 |
66 | The sample retrieves metric definitions and metrics for a given resource.
67 | It starts by setting up a MonitorClient object using your subscription and credentials.
68 |
69 | ```csharp
70 | // Build the service credentials and Monitor client
71 | var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
72 | var monitorClient = new MonitorClient(serviceCreds);
73 | monitorClient.SubscriptionId = subscriptionId;
74 | ```
75 |
76 |
77 | ### List metric definitions for a resource
78 |
79 | List the metric definitions for the given resource, which is defined in the current subscription.
80 |
81 | ```csharp
82 | IEnumerable metricDefinitions = await readOnlyClient.MetricDefinitions.ListAsync(resourceUri: resourceUri, cancellationToken: new CancellationToken());
83 | ```
84 |
85 | or using a filter
86 |
87 | ```csharp
88 | var odataFilterMetricDef = new ODataQuery("name.value eq 'CpuPercentage'");
89 | metricDefinitions = await readOnlyClient.MetricDefinitions.ListAsync(resourceUri: resourceUri, odataQuery: odataFilterMetricDef, cancellationToken: new CancellationToken());
90 | ```
91 |
92 |
93 | ### List metrics for a resource
94 |
95 | ```csharp
96 | IEnumerable metrics = await readOnlyClient.Metrics.ListAsync(resourceUri: resourceUri, cancellationToken: CancellationToken.None);
97 | ```
98 |
99 | or with a filter
100 |
101 | ```csharp
102 | // The comma-separated list of metric names must be present if a filter is used
103 | var metricNames = "name.value eq 'CpuPercentage'"; // could be concatenated with " or name.value eq ''" ...
104 |
105 | // Time grain is optional when metricNames is present
106 | string timeGrain = " and timeGrain eq duration'PT5M'";
107 |
108 | // Defaulting to 3 hours before the time of execution for these datetimes
109 | string startDate = string.Format(" and startTime eq {0}", DateTime.Now.AddHours(-3).ToString("o"));
110 | string endDate = string.Format(" and endTime eq {0}", DateTime.Now.ToString("o"));
111 |
112 | var odataFilterMetrics = new ODataQuery(
113 | string.Format(
114 | "{0}{1}{2}{3}",
115 | metricNames,
116 | timeGrain,
117 | startDate,
118 | endDate));
119 |
120 | Write("Call with filter parameter (i.e. $filter = {0})", odataFilterMetrics);
121 | metrics = await readOnlyClient.Metrics.ListAsync(resourceUri: resourceUri, odataQuery: odataFilterMetrics, cancellationToken: CancellationToken.None);
122 | ```
123 |
--------------------------------------------------------------------------------
/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "1.0.0-*",
3 | "buildOptions": {
4 | "debugType": "portable",
5 | "emitEntryPoint": true
6 | },
7 | "dependencies": {
8 | "Microsoft.Azure.Management.Monitor": "0.16.1.0-preview",
9 | "Microsoft.Rest.ClientRuntime": "2.3.9",
10 | "Microsoft.Rest.ClientRuntime.Azure": "3.3.9",
11 | "Microsoft.Rest.ClientRuntime.Azure.Authentication": "2.2.9-preview"
12 | },
13 | "frameworks": {
14 | "netcoreapp1.0": {
15 | "dependencies": {
16 | "Microsoft.NETCore.App": {
17 | "type": "platform",
18 | "version": "1.0.0"
19 | }
20 | },
21 | "imports": "dnxcore50"
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------