{"id":23327,"date":"2015-12-17T03:10:00","date_gmt":"2015-12-17T11:10:00","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=23327"},"modified":"2015-12-17T03:10:00","modified_gmt":"2015-12-17T11:10:00","slug":"monitor-azure-resource-usage-and-predict-expenses","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/monitor-azure-resource-usage-and-predict-expenses\/","title":{"rendered":"Monitor Azure Resource Usage and Predict Expenses"},"content":{"rendered":"<p>\t\t\t\t<img decoding=\"async\" class=\"alignright wp-image-23351 size-thumbnail\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Graph-150x150.png\" alt=\"AzureTracker-02\" width=\"150\" height=\"150\" \/>As organizations continue moving\u00a0to the cloud, it&#8217;s increasingly important to monitor resource usage and predict expenses with the &#8216;Pay-As-You-Go&#8217; model. This common payment model in cloud technology can be used to save expenses, but can often turn into a white elephant if not monitored properly. To achieve maximum cost saving, Microsoft introduced the Azure Billing API. In this blog post, we&#8217;re going to learn how to utilize these APIs to build our own Azure consumption tracking application for iOS, Android, and Windows using Xamarin.Forms.<\/p>\n<h2>Step 1: Register and Provide API\u00a0Access to Mobile Apps<\/h2>\n<p><a href=\"https:\/\/blog.xamarin.com\/authenticate-xamarin-mobile-apps-using-azure-active-directory\/\">Authenticating mobile apps using Azure Active Directory<\/a> is super easy with Xamarin. In this particular scenario,\u00a0we need to give access to the &#8220;Windows Azure Service Management API&#8221;. Click &#8220;add application&#8221; and provide access to all of the APIs you wish to use in your resource manager. To get started, click &#8220;Add application&#8221; and provide access to the APIs below in the Azure Portal. Be sure to keep &#8220;Windows Azure Active Directory&#8221; permissions as they are, without making any changes. Be sure to write down your &#8220;ClientId&#8221; and &#8220;Redirect Uri&#8221;, as it will be required in a later step.<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2015-12-10-at-12.20.55-PM.png\"><img decoding=\"async\" class=\"alignnone size-large wp-image-23328\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2015-12-10-at-12.20.55-PM-1024x252.png\" alt=\"AzureTracker-01\" width=\"1024\" height=\"252\" \/><\/a><\/p>\n<h2>Step 2: Define Variables and\u00a0Authenticate Your App with ADAL<\/h2>\n<p>Now that all of the server-side configuration has been taken care of, it&#8217;s time to get started\u00a0building our\u00a0consumption tracking app!\u00a0Create a new class to handle communication between the Azure Billing API and your app and add the following variables to your class. Be sure to enter your ClientId and Redirect Uri from Step 1.<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:csharp decode:true\">public static string ClientId = \"&lt;your-client-id&gt;\";\npublic static string LoginAuthority = \"https:\/\/login.microsoftonline.com\/&lt;your-tenant-id&gt;\";\npublic static string ReturnUri = \"&lt;your-redirect-uri&gt;\";\npublic static string GraphResourceUri = \"https:\/\/graph.windows.net\/\";\npublic static string ManagementResourceUri = \"https:\/\/management.core.windows.net\/\";\npublic static AuthenticationResult AuthenticationResult = null;\npublic static Subscription SelectedSubscription { get; set; }\n<\/pre>\n<p>We will use the same interface here to handle our authentication as we did for the IAuthenticator interface while using the <a href=\"https:\/\/blog.xamarin.com\/put-adal-xamarin-forms\/\">Active Directory Authentication Library (ADAL)<\/a> in Xamarin.Forms. The Authenticate method should return an AuthenticateResult object from ADAL, which contains the AccessToken and other required details for further API calls. The AuthenticateSilently method is used to re-authenticate with the API, without having to request new access tokens.<\/p>\n<pre class=\"lang:csharp decode:true\">public interface IAuthenticator\n{\n   Task&lt;AuthenticationResult&gt; Authenticate(string authority, string resource, string clientId, string returnUri);\n   Task&lt;AuthenticationResult&gt; AuthenticateSilently(string tenantId, string resource, string clientId);\n}\n<\/pre>\n<p>Next, implement the IAuthenticator interface. We&#8217;ve already done the heavy lifting for you by <a href=\"https:\/\/blog.xamarin.com\/put-adal-xamarin-forms\/\">implementing the Authenticate method<\/a>, which requires a per-platform implementation. It is not required to write AuthenticateSilently on a per-platform basis:<\/p>\n<pre class=\"lang:csharp decode:true\">public async Task&lt;AuthenticationResult&gt; AuthenticateSilently (string tenantId, string resource, string clientId)\n{\n   var loginAuthnority = \"https:\/\/login.microsoftonline.com\/\" + tenantId;\n   var authContext = new AuthenticationContext (loginAuthnority);\n   var authResult = await authContext.AcquireTokenSilentAsync(resource, clientId, \n        new UserIdentifier(App.AuthenticationResult.UserInfo.UniqueId, UserIdentifierType.UniqueId));\n   return authResult;\n}\n<\/pre>\n<h2>Step 3: Call Azure Usage APIs<\/h2>\n<p>Once authenticated, we can get tenants by calling the <a href=\"https:\/\/msdn.microsoft.com\/en-in\/library\/azure\/dn790568.aspx\" target=\"_blank\">Azure Resource Management (ARM) API<\/a>.\u00a0Each tenant may have Azure subscriptions, so we&#8217;ll need to call the GetSubscriptions method for each one. Once we have a list of subscriptions, we can call the Azure Usage API to get usage details for each subscription:<\/p>\n<pre class=\"lang:csharp decode:true\">private async Task GetTenants()\n{\n   var requestUrl = \"https:\/\/management.azure.com\/tenants?api-version=2015-01-01\";\n   try {\n      var tenantResponse = await client.GetStringAsync(requestUrl);\n      tenantCollection = JsonConvert.DeserializeObject&lt;TenantResponse&gt; (tenantResponse); \n   }\n   catch (Exception ex) {\n      await DisplayAlert(\"Error!\", ex.Message, \"Dismiss\"); \n   }\n   foreach (var tenant in tenantCollection.TenantCollection) {\n         await GetSubscriptions (tenant.TenantId);\n   }\n}\n\nprivate async Task GetSubscriptions(string tenantId) \n{\n   var requestUrl = \"https:\/\/management.azure.com\/subscriptions?api-version=2015-01-01\";\n   try {\n      var data = await DependencyService.Get&lt;IAuthenticator&gt; ().AuthenticateSilently (tenantId, \n                 App.ManagementResourceUri, App.ClientId);\n    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(\"Bearer\", data.AccessToken);\n    var subsriptionResponse = await client.GetStringAsync (requestUrl);\n    var subscriptions = JsonConvert.DeserializeObject&lt;SubscriptionResponse&gt;(subsriptionResponse);\n    foreach (var subscription in subscriptions.SubscriptionCollection) {\n       SubscriptionCollection.Add(subscription); }\n    IsFirstRunComplete = true; }\n    catch (Exception ex) {\n    await DisplayAlert(\"Error!\", ex.Message, \"Dismiss\"); }\n}\n<\/pre>\n<p>Once you get the list of subscriptions, you can select one and fetch usage details for that particular subscription:<\/p>\n<pre class=\"lang:csharp decode:true\">var requestUrl = String.Format(\"https:\/\/management.azure.com\/subscriptions\/{0}\/providers\/Microsoft.Commerce\/UsageAggregates?\n          api-version=2015-06-01-preview&amp;reportedStartTime={1}&amp;reportedEndTime={2}&amp;aggregationGranularity=Daily&amp;showDetails=false\",\n          App.SelectedSubscription.SubscriptionId, startTime, endTime); \nvar usageData = await client.GetStringAsync (requestUrl);\nvar data = JsonConvert.DeserializeObject&lt;AzureTracker.Model.UsageResponse&gt; (usageData);\n<\/pre>\n<p>After you have the details, you can show them in a list or fetch\u00a0more details about each subscription individually.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-23354 size-full\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AzureTracker-02.png\" alt=\"AzureTracker-03\" width=\"1216\" height=\"667\" \/><\/p>\n<h2>Bring Your Consumption Tracker to the Next Level<\/h2>\n<p>To see the Azure Billing API in action, download our sample and get started building your own <a href=\"https:\/\/github.com\/mayur-tendulkar\/AzureConsumptionTracker\">Azure Consumption Tracker for iOS, Android, and Windows today<\/a>! You can also add features like predicting future expenses or charts and graphs to help analyze usage thus far to make the app your own.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As organizations continue moving\u00a0to the cloud, it&#8217;s increasingly important to monitor resource usage and predict expenses with the &#8216;Pay-As-You-Go&#8217; model. This common payment model in cloud technology can be used to save expenses, but can often turn into a white elephant if not monitored properly. To achieve maximum cost saving, Microsoft introduced the Azure Billing [&hellip;]<\/p>\n","protected":false},"author":549,"featured_media":23354,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-23327","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>As organizations continue moving\u00a0to the cloud, it&#8217;s increasingly important to monitor resource usage and predict expenses with the &#8216;Pay-As-You-Go&#8217; model. This common payment model in cloud technology can be used to save expenses, but can often turn into a white elephant if not monitored properly. To achieve maximum cost saving, Microsoft introduced the Azure Billing [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/23327","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/549"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=23327"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/23327\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=23327"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=23327"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=23327"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}