/// <summary> /// Get the number of cores for specified Azure VM Size /// </summary> /// <param name="cspCreds">CSP Account credentials object. A token will be generated using these credentials and used for making the online ARM API call</param> /// <param name="vmSize">Azure VM Size</param> /// <param name="location">Azure Location</param> /// <returns> Returns the number of cores for the specified Azure VM Size</returns> public static int GetCoresForVmSize(CSPAccountCreds cspCreds, string vmSize, string location) { int numberOfCores = -1; try { // Get AAD Token string aadToken = AuthManager.GetAzureADTokenAppUser(cspCreds.CSPNativeAppClientId, cspCreds.CSPAdminAgentUserName, cspCreds.CSPAdminAgentPassword, cspCreds.CSPCustomerTenantId, false); string url = APIURLConstants.VMGetVMSizesAPIsUrl; var path = string.Format(url, APIURLConstants.ARMAPIURL, cspCreds.CSPAzureSubscriptionId, location, APIURLConstants.ARMComputeAPIVersion); // Make the ARM API call using the Online Helper class method VMSizeList sizeList = ARMAPIHelper.GetARMCall <VMSizeList>(aadToken, path, APIResponseTimeLimitConstants.APICallDefaultLimit); VMSizeListItem listItem = sizeList.Value.FirstOrDefault(x => x.Name.Equals(vmSize, StringComparison.OrdinalIgnoreCase)); if (listItem != null) { numberOfCores = listItem.NumberOfCores; } } catch (Exception e) { throw new Exception(ExceptionLogger.GenerateLoggerTextForOnlineHelperCall("Number of Cores", e.Message)); } return(numberOfCores); }
/// <summary> /// Gets the Meters for the Azure CSP Rate Card /// </summary> /// <param name="cspCreds">CSP Account credentials object. A token will be generated using these credentials and used for making the online Partner Center API call</param> /// <returns> Returns the list of Azure Meters</returns> public static List <Meter> GetRateCard(CSPAccountCreds cspCreds) { List <Meter> meterList = null; try { if (cspCreds == null) { throw new Exception(ExceptionLogger.GenerateLoggerTextForInternalError("CSP Account Credentials is null")); } // Fetch the AzureAD Token string aadToken = AuthManager.GetAzureADTokenAppUser(cspCreds.CSPClientId, cspCreds.CSPAdminAgentUserName, cspCreds.CSPAdminAgentPassword, cspCreds.CSPResellerTenantID, true); // Create the HttpClient Object HttpClient client = new HttpClient(); // Set the request header values client.DefaultRequestHeaders.Add("Authorization", "Bearer " + aadToken); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("MS-CorrelationId", Guid.NewGuid().ToString()); client.DefaultRequestHeaders.Add("MS-RequestId", Guid.NewGuid().ToString()); client.DefaultRequestHeaders.Add("X-Locale", Constants.CSPLocale); client.Timeout = new TimeSpan(0, APIResponseTimeLimitConstants.RateCardFetchLimit, 0); // Set the path var path = string.Format("{0}/v1/ratecards/azure?currency={1}®ion={2}", APIURLConstants.PCAPIUrl, cspCreds.CSPCurrency, cspCreds.CSPRegion); Uri uri = new Uri(path); // Make the API Call to fetch the Rate Card HttpResponseMessage response = client.GetAsync(uri).Result; if (response.IsSuccessStatusCode) { string jsonResult = response.Content.ReadAsStringAsync().Result; RateCard card = JsonConvert.DeserializeObject <RateCard>(jsonResult); meterList = card.Meters; } else { string jsonResult = response.Content.ReadAsStringAsync().Result; new Exception(ExceptionLogger.GenerateLoggerTextForOnlineHelperCall("CSP Rate Card", string.Format("Error while fetching the Rate Card: {0}", jsonResult))); } } catch (Exception) { throw; } return(meterList); }
/// <summary> /// Fetches the VM image SKU Version Info for the specified SKU Version of the Azure VM Image /// </summary> /// <param name="token">Azure AD Token to make the ARM API Call</param> /// <param name="skuVersionID">ID of the SKU Version</param> /// <returns> Returns the SKU Version info of the specified Azure VM Image SKU</returns> private static VMSKUVersion GetVMImageSKUVersionDetails(string token, string skuVersionID) { VMSKUVersion skuVersion = null; try { string url = APIURLConstants.VMSKUGetVersionDetailsAPIsUrl; var path = string.Format(url, APIURLConstants.ARMAPIURL, skuVersionID, APIURLConstants.ARMComputeAPIVersion); // Make the ARM API call using the Online Helper class method skuVersion = ARMAPIHelper.GetARMCall <VMSKUVersion>(token, path, APIResponseTimeLimitConstants.APICallDefaultLimit); } catch (Exception e) { throw new Exception(ExceptionLogger.GenerateLoggerTextForOnlineHelperCall("VM SKU Version Details", e.Message)); } return(skuVersion); }
/// <summary> /// Fetches the VM image SKU List for the specified Publisher, Offer and SKU of the Azure VM Image /// </summary> /// <param name="token">Azure AD Token to make the ARM API Call</param> /// <param name="subscriptionId">CSP Azure Subscription Id</param> /// <param name="publisher">Publisher of the Azure VM Image</param> /// <param name="offer">Offer of the Azure VM Image</param> /// <param name="sku">SKU of the Azure VM Image</param> /// <param name="location">Azure Location</param> /// <returns> Returns the list of Azure VM Image SKUs</returns> private static List <VMSKUVersionListItem> GetVMImageSKUS(string token, string subscriptionId, string publisher, string offer, string sku, string location) { List <VMSKUVersionListItem> skuVersionList = null; try { string url = APIURLConstants.VMSKUGetVersionsAPIsUrl; var path = string.Format(url, APIURLConstants.ARMAPIURL, subscriptionId, location, publisher, offer, sku, APIURLConstants.ARMComputeAPIVersion); // Make the ARM API call using the Online Helper class method skuVersionList = ARMAPIHelper.GetARMCall <List <VMSKUVersionListItem> >(token, path, APIResponseTimeLimitConstants.APICallDefaultLimit); } catch (Exception e) { throw new Exception(ExceptionLogger.GenerateLoggerTextForOnlineHelperCall("VM SKU Version", e.Message)); } return(skuVersionList); }
/// <summary> /// Gets the Azure AD Token using the App + User Authentication option /// </summary> /// <param name="appId">The Application ID</param> /// <param name="userName">UserName of the User</param> /// <param name="password">Password of the User</param> /// <param name="tenantID">TenantID of the Azure AD from which the token is to be fetched</param> /// <param name="isResourcePCAPI">Set to true if resource for token is Partner Center API, false if resource if ARM API</param> /// <returns> Returns the Azure AD Token in String format</returns> public static string GetAzureADTokenAppUser(string appId, string userName, string password, string tenantID, bool isResourcePCAPI) { string token = null; string cacheitemNameForToken = string.Empty; if (isResourcePCAPI) { cacheitemNameForToken = "AzureADTokenAppUserAuthPC"; } else { cacheitemNameForToken = "AzureADTokenAppUserAuthARM"; } try { ObjectCache cache = MemoryCache.Default; // Fetch from cache if available if (cache.Contains(cacheitemNameForToken)) { token = cache.Get(cacheitemNameForToken) as string; } else { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json"); client.Timeout = new TimeSpan(0, APIResponseTimeLimitConstants.TokenFetchLimit, 0); string resourceURL; // Set the Resource URL if (isResourcePCAPI) { resourceURL = APIURLConstants.PCAPIUrl; } else { resourceURL = APIURLConstants.ARMAPIResourceURL; } var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("resource", resourceURL), new KeyValuePair <string, string>("client_id", appId), new KeyValuePair <string, string>("grant_type", "password"), new KeyValuePair <string, string>("username", userName), new KeyValuePair <string, string>("password", password), new KeyValuePair <string, string>("scope", "openid") }); string aadTokenURL = string.Format("{0}/{1}/oauth2/token", APIURLConstants.GraphAPILoginURL, tenantID); Uri uri = new Uri(aadTokenURL); var response = client.PostAsync(uri, content).Result; if (response.IsSuccessStatusCode) { // Get the result and Add to cache string result = response.Content.ReadAsStringAsync().Result; AADTokenDetails details = JsonConvert.DeserializeObject <AADTokenDetails>(result); token = details.Access_token; DateTimeOffset expiryTime = DateTime.Now.AddSeconds(details.Expires_in).AddSeconds(-60); cache.Add(cacheitemNameForToken, token, expiryTime); } else { string jsonResult = response.Content.ReadAsStringAsync().Result; throw new Exception(jsonResult); } } } } catch (Exception ex) { throw new Exception(ExceptionLogger.GenerateLoggerTextForOnlineHelperCall("Azure AD Token", ex.Message)); } return(token); }