/// <summary> /// Get a list of resource groups. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="subscription">Guid of the subscription</param> /// <returns>List of resource groups. Will be an empty list if there was a problem or there are no resource groups.</returns> public static async Task <List <ResourceGroup> > List(string bearerToken, Guid subscription) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((subscription == Guid.Empty) || (subscription == default)) { throw new ArgumentNullException(nameof(subscription)); } RestApiResponse response = await RestApiClient.GETWithContinuations <ResourceGroup>( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourcegroups", CLIENT_API_VERSION, null, null, new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(new List <ResourceGroup>()); } return(JsonConvert.DeserializeObject <List <ResourceGroup> >(response.Body)); }
private RestApiResponse InnerSignalInvocation(string verb, string actionName, int contentId) { // we want what we return here to map to HttpResponseMessage RestApiResponse restResult = new RestApiResponse(); var signalName = SignalName(verb, actionName); try { var content = _contentManager.Get(contentId); var tokens = new Dictionary <string, object> { { "Content", content }, { "HttpVerb", verb }, { "RESTActionName", actionName }, { SignalActivity.SignalEventName, signalName }, { "RESTApiResponse", restResult } }; _workflowManager .TriggerEvent(SignalActivity.SignalEventName, content, () => tokens); } catch (Exception ex) { Log.Error("CustomApiController.SignalInvocation: " + Environment.NewLine + "verb: " + verb + Environment.NewLine + "actionName: " + actionName + Environment.NewLine + "contentId: " + contentId.ToString() + Environment.NewLine + "signalName: " + signalName + Environment.NewLine + "Exception.Message: " + ex.Message + Environment.NewLine + "Exception.StackTrace: " + ex.StackTrace); return(new RestApiResponse(HttpStatusCode.InternalServerError)); } return(restResult); }
/// <summary> /// Check if a resource exists /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="resourceUri">Absolute resource Id</param> /// <returns>True if exists, False if not, NULL if there was a problem</returns> public static async Task <bool?> Exists(string bearerToken, ResourceUri resourceUri) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((resourceUri == null) || (!resourceUri.IsValid)) { throw new ArgumentNullException(nameof(resourceUri)); } RestApiResponse response = await RestApiClient.HEAD( bearerToken, resourceUri.ToAbsoluteAzureRMEndpointUri(string.Empty), CLIENT_API_VERSION, null, new int[] { 204, 404 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(null); } return(response.HttpStatus == 204); }
/// <summary> /// Delete a resource. Resources are queued for async deletion and status will be available only later. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="resourceUri">Absolute resource Id</param> /// <returns>True if accepted for deletion, false if not or there was a problem</returns> public static async Task <bool> Delete(string bearerToken, ResourceUri resourceUri) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((resourceUri == null) || (!resourceUri.IsValid)) { throw new ArgumentNullException(nameof(resourceUri)); } RestApiResponse response = await RestApiClient.DELETE( bearerToken, resourceUri.ToAbsoluteAzureRMEndpointUri(string.Empty), CLIENT_API_VERSION, null, new int[] { 200, 202, 204 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(false); } return(true); }
/// <summary> /// Get metadata about a single App Service Plan /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the plan is homed in</param> /// <param name="planName">Name of the plan</param> /// <returns>AppServicePlan or NULL</returns> public static async Task <AppServicePlan?> GetAppServicePlan(string bearerToken, Guid subscription, string resourceGroupName, string planName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == default) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(planName)) { throw new ArgumentNullException(nameof(planName)); } RestApiResponse response = await RestApiClient.GET( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/serverfarms/{planName}", CLIENT_API_VERSION, null, null, new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <AppServicePlan>(response.Body)); }
/// <summary> /// Regenerates the provided key and returns the new value /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the account is placed in</param> /// <param name="storageAccountName">Name of the storage account</param> /// <param name="keyName">Name of the key to regenerate</param> /// <returns>New key or NULL</returns> public static async Task <string?> RegenerateKey(string bearerToken, Guid subscription, string resourceGroupName, string storageAccountName, string keyName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(storageAccountName)) { throw new ArgumentNullException(nameof(storageAccountName)); } if (string.IsNullOrWhiteSpace(keyName)) { throw new ArgumentNullException(nameof(keyName)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/regenerateKey", CLIENT_API_VERSION, null, $"{{ \"keyName\" : \"{keyName}\" }}", new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <StorageAccountKeyResponse>(response.Body).Keys.First(k => k.Name.Equals(keyName))?.Key); }
/// <summary> /// Get both account keys for the storage account /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the account is placed in</param> /// <param name="storageAccountName">Name of the storage account</param> /// <returns>List of keys or empty list</returns> public static async Task <List <StorageAccountKey> > ListKeys(string bearerToken, Guid subscription, string resourceGroupName, string storageAccountName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(storageAccountName)) { throw new ArgumentNullException(nameof(storageAccountName)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/listKeys", CLIENT_API_VERSION, null, null, new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(new List <StorageAccountKey>()); } return(JsonConvert.DeserializeObject <StorageAccountKeyResponse>(response.Body).Keys); }
/// <summary> /// Get an SAS token for the service account /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the account is placed in</param> /// <param name="storageAccountName">Name of the storage account</param> /// <param name="properties">Other properties for the request</param> /// <returns>SAS token value (or NULL)</returns> public static async Task <string?> GetSASServiceToken(string bearerToken, Guid subscription, string resourceGroupName, string storageAccountName, SASServiceTokenRequest properties) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(storageAccountName)) { throw new ArgumentNullException(nameof(storageAccountName)); } if (properties == null) { throw new ArgumentNullException(nameof(properties)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/ListServiceSas", CLIENT_API_VERSION, null, properties, new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <SASServiceTokenResponse>(response.Body).Token); }
/// <summary> /// Check if name is available for creation /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the account is to be placed in</param> /// <param name="nameToCheck">Name to check for</param> /// <returns>True if name is available</returns> public static async Task <bool> IsNameAvailable(string bearerToken, Guid subscription, string resourceGroupName, string nameToCheck) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(nameToCheck)) { throw new ArgumentNullException(nameof(nameToCheck)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.Storage/checkNameAvailability", CLIENT_API_VERSION, null, new Request(nameToCheck), new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(false); } return(JsonConvert.DeserializeObject <Response>(response.Body).IsAvailable); }
/// <summary> /// Failover a storage account. Failback is the same call because after failover the primary is marked as the secondary and vice-versa. /// </summary> /// <param name="bearerToken">Azure bearer token</param> /// <param name="subscription">Subscription for authorization</param> /// <param name="resourceGroupName">Name of the resource group the account is placed in</param> /// <param name="storageAccountName">Name of the storage account</param> /// <returns>True if the task was accepted. False if not. NULL if there is a problem</returns> public static async Task <bool?> Failover(string bearerToken, Guid subscription, string resourceGroupName, string storageAccountName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(storageAccountName)) { throw new ArgumentNullException(nameof(storageAccountName)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/failover", CLIENT_API_VERSION, null, null, new int[] { 200, 202 } ); if ((!response.IsExpectedSuccess) || response.WasException) { return(null); } return(response.WasException ? (bool?)null : response.IsExpectedSuccess); }
public async Task <EntityCollection> RetrieveMultipleAsync(string query) { RestApiResponse <EntityCollection, Exceptions> response = await GetAsync <EntityCollection, Exceptions>(query); return(new EntityCollection { Entities = response.Data?.Entities, Exceptions = response.Error, IsSuccessStatusCode = response.IsSuccessStatusCode }); }
/// <summary> /// Create a request to transfer a new domain name /// </summary> /// <param name="bearerToken">The Azure bearer token</param> /// <param name="subscription">Subscription Id for authorization</param> /// <param name="domainName">Domain name to transfer. Note that the Azure App Service Domain only supports /// purchase of selected domain TLDs.</param> /// <param name="transferAuthorization">Authorization code received from current Domain Registrar to authorize this transfer request</param> /// <param name="targetResourceGroupName">The Azure Resource Group to place the registered domain in</param> /// <param name="autoRenew">If set, Azure will auto-renew the domain every year</param> /// <param name="registrationContact">Contact information to use for transfer</param> /// <param name="callerIpAddress">IP address of caller for purchase consent agreement</param> /// <param name="agreementKeyNames">Name of the keys of terms and conditions that have been agreed to</param> /// <param name="useCustomDns">If set, will not use Azure DNS for the domain (if Azure DNS is required later, it will need to be /// configured seperately)</param> /// <param name="existingAzureZone">If an existing Azure DNS Zone is to be tied to this domain, the resource Uri to that zone</param> /// <returns>True if the domain registration task was accepted by Azure. False if not, NULL if there were errors</returns> public static async Task <bool?> TransferDomain(string bearerToken, Guid subscription, string domainName, string transferAuthorization, string targetResourceGroupName, bool autoRenew, DomainRegistrationContact registrationContact, string callerIpAddress, string[] agreementKeyNames, bool useCustomDns = false, ResourceUri?existingAzureZone = null) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(targetResourceGroupName)) { throw new ArgumentNullException(nameof(targetResourceGroupName)); } if (string.IsNullOrWhiteSpace(transferAuthorization)) { throw new ArgumentNullException(nameof(transferAuthorization)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if ((agreementKeyNames == null) || (!agreementKeyNames.Any())) { throw new ArgumentNullException(nameof(agreementKeyNames)); } // validate domain name :-) AvailabilityRequest _ = new AvailabilityRequest(domainName); DomainTransferRequest request = new DomainTransferRequest(transferAuthorization, autoRenew, registrationContact, callerIpAddress, agreementKeyNames); if (useCustomDns) { request.Properties.TypeOfDns = DomainRegistrationDnsTypeEnum.DefaultDomainRegistrarDns; } if (existingAzureZone != null) { if ((!existingAzureZone.IsValid) || (!existingAzureZone.Is(ResourceUriCompareLevel.Provider, "Microsoft.Network")) || (!existingAzureZone.Is(ResourceUriCompareLevel.Type, "dnszones"))) { throw new ArgumentException(nameof(existingAzureZone)); } request.Properties.AzureDnsZoneId = existingAzureZone.ToString(); } RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{targetResourceGroupName}/providers/Microsoft.DomainRegistration/domains/{domainName}", CLIENT_API_VERSION, null, request, new int[] { 200, 202 } ); return(response.WasException ? (bool?)null : response.IsExpectedSuccess); }
/// <summary> /// Get the rate card. This method will take a LONG time to run! It runs with a upstream timeout of 1 min, so /// consuming method should be set to a larger timeout. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="subscription">Guid of the subscription</param> /// <param name="azureSubscriptionOfferId">The Offer Id of the Azure subscription</param> /// <param name="isoCurrencyCode">3-letter ISO currency code (eg: USD)</param> /// <param name="isoLocaleCode">4-letter ISO locale code (eg: en-US)</param> /// <param name="isoRegionCode">2-letter ISO region name (eg: US)</param> /// <returns>The ratecard response, or NULL if there was a problem</returns> public static async Task <RateCardResponse?> GetRates(string bearerToken, Guid subscription, string azureSubscriptionOfferId, string isoCurrencyCode, string isoLocaleCode, string isoRegionCode) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if ((subscription == Guid.Empty) || (subscription == default)) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(azureSubscriptionOfferId)) { throw new ArgumentNullException(nameof(azureSubscriptionOfferId)); } if (string.IsNullOrWhiteSpace(isoCurrencyCode)) { throw new ArgumentNullException(nameof(isoCurrencyCode)); } if (string.IsNullOrWhiteSpace(isoLocaleCode)) { throw new ArgumentNullException(nameof(isoLocaleCode)); } if (string.IsNullOrWhiteSpace(isoRegionCode)) { throw new ArgumentNullException(nameof(isoRegionCode)); } RestApiResponse originalResponse = await RestApiClient.GET( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.Commerce/RateCard", CLIENT_API_VERSION, new Dictionary <string, string>() { { "$filter", $"OfferDurableId eq '{azureSubscriptionOfferId}' and Currency eq '{isoCurrencyCode}' and Locale eq '{isoLocaleCode}' and RegionInfo eq '{isoRegionCode}'" } }, null, new int[] { 302 } ); if ((!originalResponse.IsExpectedSuccess) || originalResponse.WasException || (originalResponse.Headers == null) || (originalResponse.Headers !.Location == null)) { return(null); } RestApiResponse response = await RestApiClient.GETWithoutAuthentication( originalResponse.Headers !.Location.AbsoluteUri, null, null, null, new int[] { 200 }, 60 // set timeout to 1 min ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <RateCardResponse>(response.Body)); }
/// <summary> /// Create a certificate order /// </summary> /// <param name="bearerToken">The Azure bearer token</param> /// <param name="subscription">Subscription Id for authorization</param> /// <param name="resourceGroupName">Name of the resource group to place the new certificate in</param> /// <param name="orderNickname">A nickname for the order</param> /// <param name="certificateRequestText">The text content of a certificate request (CSR)</param> /// <param name="autoRenew">Set to TRUE to autorenew the certificate at the end of the specified validity period</param> /// <param name="type">Type of certificate (WARNING: selection has cost implications!)</param> /// <param name="validityPeriod">Period in years, that the issued certificate will be valid for</param> /// <returns>Details of the placed order</returns> public static async Task <CertificateOrderDetail?> OrderUsingCSR(string bearerToken, Guid subscription, string resourceGroupName, string orderNickname, string certificateRequestText, bool autoRenew = true, CertificateTypesEnum type = CertificateTypesEnum.StandardDomainValidatedSsl, CertificateValidityPeriod validityPeriod = CertificateValidityPeriod.OneYear) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(orderNickname)) { throw new ArgumentNullException(nameof(orderNickname)); } if (string.IsNullOrWhiteSpace(certificateRequestText)) { throw new ArgumentNullException(nameof(certificateRequestText)); } AppServiceCertificateOrderRequest request = new AppServiceCertificateOrderRequest() { Location = "global", Name = orderNickname, Properties = new AppServiceCertificateOrderRequestProperties() { AppServiceDomainName = null, AutoRenew = autoRenew, KeySize = CertificateKeySizesEnum.Default, LastGeneratedCertificateRequestText = certificateRequestText, Type = type, Validity = validityPeriod } }; RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{orderNickname}", CLIENT_API_VERSION, null, request, new int[] { 200, 201 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <CertificateOrderDetail>(response.Body)); }
/// <summary> /// Issue a certificate /// </summary> /// <param name="bearerToken">The Azure bearer token</param> /// <param name="subscription">Subscription Id for authorization</param> /// <param name="resourceGroupName">Name of the resource group the certificate exists in</param> /// <param name="orderNickname">A nickname for the order, specified during order creation</param> /// <param name="certificateName">A name of the certificate to identify it later</param> /// <param name="keyVaultId">Resource Uri to the KeyVault to hold the private key for the certificate</param> /// <param name="privateKeySecretName">Name of the private key for this certificate in the Azure KeyVault</param> /// <returns>The issued certificate or NULL</returns> public static async Task <IssuedCertificate?> Issue(string bearerToken, Guid subscription, string resourceGroupName, string orderNickname, string certificateName, ResourceUri keyVaultId, string privateKeySecretName) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (string.IsNullOrWhiteSpace(orderNickname)) { throw new ArgumentNullException(nameof(orderNickname)); } if (string.IsNullOrWhiteSpace(certificateName)) { throw new ArgumentNullException(nameof(certificateName)); } if ((keyVaultId == null) || (!keyVaultId.IsValid) || (!keyVaultId.Is(ResourceUriCompareLevel.Provider, "Microsoft.KeyVault"))) { throw new ArgumentException(nameof(keyVaultId)); } CertificateIssueRequest request = new CertificateIssueRequest() { Kind = "certificates", Location = "global", Properties = new CertificateIssueRequestProperties() { KeyVaultId = keyVaultId.ToString(), KeyVaultSecretName = privateKeySecretName } }; RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{orderNickname}/certificates/{certificateName}", CLIENT_API_VERSION, null, request, new int[] { 200, 201 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <IssuedCertificate>(response.Body)); }
public async Task <ConfigurationModel> GetByKeyAsync(ISession session, string key) { if (!IsInitialized) { await InitConfigurationAsync(session); } RestApiResponse <ConfigurationModel> response = await _client.GetAsync <ConfigurationModel>(session, $"{_baseServiceUrl}/getByKey/{key}"); return(response.Result); }
private HttpResponseMessage SignalInvocation(string verb, string actionName, int contentId) { // we want what we return here to map to HttpResponseMessage RestApiResponse restResult = InnerSignalInvocation(verb, actionName, contentId); if (restResult == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } return(restResult.ToMessage()); }
/// <summary> /// Request AzureRM API to export the log analytics of a compute resources to the provided SAS-enabled blob /// </summary> /// <param name="bearerToken">The authorization bearer token</param> /// <param name="subscription">Subscription Guid</param> /// <param name="locationName">Internal/short name of the location (eg: "westus") -- logs for all Compute resources in this region will be exported</param> /// <param name="type">Type of log to export</param> /// <param name="startTimeUtc">Start date/time (in UTC) window to fetch the logs from</param> /// <param name="endTimeUtc">End date/time (in UTC) window to fetch the logs upto</param> /// <param name="sasEnabledBlobUri">The SAS URL to a blob that the Azure API can WRITE to</param> /// <param name="intervals">Intervals of time to place in the log data (eg: if set to ThreeMins, log analytics data for every 3 minutes from <paramref name="startTimeUtc"/> will be placed on the blob)</param> /// <param name="grouping">Type of grouping to perform on the exported data</param> /// <returns>Full path to the blob URI where the log file was written. NOTE THAT this will LOSE its SAS data!!!</returns> public static async Task <string?> ExportLogAnalytics(string bearerToken, Guid subscription, string locationName, ComputeAnalyticsLogType type, DateTime startTimeUtc, DateTime endTimeUtc, string sasEnabledBlobUri, ComputeLogAnalyticsRequestIntervals intervals = ComputeLogAnalyticsRequestIntervals.ThreeMins, ComputeAnalyticsLogGrouping grouping = ComputeAnalyticsLogGrouping.None) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(locationName)) { throw new ArgumentNullException(nameof(locationName)); } string apiEndpointName = type switch { ComputeAnalyticsLogType.RequestRate => "getRequestRateByInterval", ComputeAnalyticsLogType.ThrottleRate => "getThrottledRequests", _ => throw new ArgumentOutOfRangeException(nameof(apiEndpointName)) }; ComputeLogAnalyticsRequest request = new ComputeLogAnalyticsRequest() { TimeWindowStart = startTimeUtc, TimeWindowEnd = endTimeUtc, BlobContainerSasUri = sasEnabledBlobUri, Length = intervals, GroupByOperationName = grouping.HasFlag(ComputeAnalyticsLogGrouping.Operation), GroupByResourceName = grouping.HasFlag(ComputeAnalyticsLogGrouping.Resource), GroupByThrottlePolicy = grouping.HasFlag(ComputeAnalyticsLogGrouping.ThrottlePolicy) }; RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription.ToString("d")}/providers/Microsoft.Compute/locations/{locationName}/logAnalytics/apiAccess/{apiEndpointName}", "2019-03-01", null, request, new int[] { 200, 202 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } return(JsonConvert.DeserializeObject <ComputeLogAnalyticsResponse>(response.Body).Properties?.OutputFileUri); } }
public async Task <CompteModel> LoginAsync(ISession session, string username, string password) { RestApiResponse <CompteModel> response = await _client.PostAsync <CompteModel, CompteModel>(session, $"{_baseServiceUrl}/login", new CompteModel { Username = username, Password = password }); session.SetString(RestAPIClient.TokenKey, response.Result.Token); session.SetString(CompteSessionKey, JsonConvert.SerializeObject(response.Result)); return(response.Result); }
/// <summary> /// Create/register a new extension. If the extension is already present/registered, updates the registration with the /// provided values. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="virtualMachineExtension">The prepopulated Virtual Machine Extension object.</param> /// <returns>VMExtension object if successful, else NULL</returns> public static async Task <VMExtension?> CreateOrUpdate(string bearerToken, VMExtension virtualMachineExtension) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(virtualMachineExtension)); } if (virtualMachineExtension == null) { throw new ArgumentNullException(nameof(virtualMachineExtension)); } RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/{virtualMachineExtension.ResourceId[1..]}",
/// <summary> /// Create a virtual machine availability set. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="availabilitySettings">Settings of the VM availability set to create or update. Note that not all settings work!</param> /// <returns>Virtual Machine availability set. NULL if there was a problem</returns> public static async Task <AvailabilitySet?> Update(string bearerToken, AvailabilitySet availabilitySettings) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (availabilitySettings == null) { throw new ArgumentNullException(nameof(availabilitySettings)); } RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/{availabilitySettings.ResourceId[1..]}",
public virtual async Task <TEntity> GetAsync(ISession session, long?id, long?secondId = null) { RestApiResponse <TEntity> result = null; if (secondId == null) { result = await _client.GetAsync <TEntity>(session, $"{_baseServiceUrl}/{id}"); } else { result = await _client.GetAsync <TEntity>(session, $"{_baseServiceUrl}/{id}/{secondId}"); } return(result.Result); }
public async Task <Entity> RetrieveAsync(string entityName, Guid id, ColumnSet columnSet) { string query = $"{GetEntitySetName(entityName)}({id})?$select={string.Join(",", columnSet.Columns)}"; RestApiResponse <Entity, Exceptions> response = await GetAsync <Entity, Exceptions>(query); Entity returnEntity = response.Data ?? new Entity(); returnEntity.LogicalName = entityName; returnEntity.Exceptions = response.Error; returnEntity.IsSuccessStatusCode = response.IsSuccessStatusCode; return(returnEntity); }
public SchemaValidatorControllerShould() { _jsonValidatorMock = new Mock <IJsonValidator>(); _loggerMock = new Mock <ILogger>(); _apiEndpoint = "http://localhost:7675"; _restApiResponse = new RestApiResponse() { Data = string.Empty }; _restApiClientMock = new Mock <IRestApiClient>(); _restApiClientMock.Setup(x => x.GetDataFromUrl(_apiEndpoint)).Returns(_restApiResponse); _controller = new SchemaValidatorController(_jsonValidatorMock.Object, _loggerMock.Object, _restApiClientMock.Object); }
public async Task <RestApiResponse> Patch(Uri url, string body, string mediaOrContentType, Dictionary <string, string> headers, X509Certificate certificates, ILogger logger = null, NetworkCredential creds = null, string accessToken = null) { var currentRetryCount = 0; var currentWaitTime = 0; var returnResponse = new RestApiResponse(); do { try { Thread.Sleep(currentWaitTime); this.httpClient.Setup(headers, certificates, creds, accessToken); var content = new StringContent(body, Encoding.UTF8, mediaOrContentType); var response = await this.httpClient.Patch(url, content).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); content.Dispose(); returnResponse = new RestApiResponse { Content = result, StatusCode = response.StatusCode, IsSuccessStatusCode = response.IsSuccessStatusCode, }; } catch (Exception exception) { logger?.LogError(exception, $"Discord.JonSnowBot.Common.Services.HttpService.Patch: An exception occured during HTTP PATCH request. URL: {url}. Body: {body}."); returnResponse = new RestApiResponse { Content = ExceptionHelper.GetAllExceptionText(exception), StatusCode = HttpStatusCode.InternalServerError, IsSuccessStatusCode = false, }; } finally { if (!returnResponse.IsSuccessStatusCode) { logger?.LogWarning($"Discord.JonSnowBot.Common.Services.HttpService.Patch: An error occured during HTTP PATCH request. URL: {url}. Body: {body}. currentRetryCount: {currentRetryCount}. currentWaitTime: {currentWaitTime}"); currentRetryCount++; currentWaitTime += currentRetryCount * this.retryWaitDuration; } } }while (!returnResponse.IsSuccessStatusCode && currentRetryCount < this.retryLimit); return(returnResponse); }
/// <summary> /// Get a single disk image /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="imageResourceId">Absolute resource Id of the disk image</param> /// <returns>Disk image or NULL</returns> public static async Task <DiskImage?> Get(string bearerToken, string imageResourceId) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (string.IsNullOrWhiteSpace(imageResourceId) || ((!imageResourceId.StartsWith("/subscriptions/")) && (!imageResourceId.StartsWith("subscriptions/")))) { throw new ArgumentException("imageResourceId must be an absolute resource Id."); } RestApiResponse response = await RestApiClient.GET( bearerToken, $"https://management.azure.com/{(imageResourceId.StartsWith("/") ? imageResourceId[1..] : imageResourceId)}",
/// <summary> /// Take or update a snapshot. If the snapshot already exists, it is replaced. /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="virtualMachineSnapshot">The prepopulated Virtual Machine Snapshot object</param> /// <returns>VMSnapshot object if successful, else NULL</returns> public static async Task <VMSnapshot?> Take(string bearerToken, VMSnapshot virtualMachineSnapshot) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(virtualMachineSnapshot)); } if (virtualMachineSnapshot == null) { throw new ArgumentNullException(nameof(virtualMachineSnapshot)); } RestApiResponse response = await RestApiClient.PUT( bearerToken, $"https://management.azure.com/{virtualMachineSnapshot.ResourceId[1..]}",
/// <summary> /// Check if the provided name is available for creating a new resource /// </summary> /// <param name="bearerToken">Authorization bearer token</param> /// <param name="subscription">Subscription Guid</param> /// <param name="nameToCheck">The name to check for availabilit</param> /// <param name="type">Type of resource that <paramref name="nameToCheck"/> is for</param> /// <param name="isNameFQDN">Set TRUE if the <paramref name="nameToCheck"/> is a fully qualified domain name. FALSE if it is only the 'hostname' (ARM will append the /// appropriate domain)</param> /// <returns>NULL: Invalid or other problem, TRUE: Available, FALSE: Not available (used)</returns> public static async Task <bool?> IsNameAvailable(string bearerToken, Guid subscription, string nameToCheck, AppServiceResourceTypesEnum type, bool isNameFQDN = false) { if (string.IsNullOrWhiteSpace(bearerToken)) { throw new ArgumentNullException(nameof(bearerToken)); } if (subscription == Guid.Empty) { throw new ArgumentNullException(nameof(subscription)); } if (string.IsNullOrWhiteSpace(nameToCheck)) { throw new ArgumentNullException(nameof(nameToCheck)); } if (!Enum.IsDefined(typeof(AppServiceResourceTypesEnum), type)) { throw new ArgumentOutOfRangeException(nameof(type)); } RestApiResponse response = await RestApiClient.POST( bearerToken, $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.Web/checknameavailability", "2019-08-01", null, new ResourceNameAvailabilityRequest() { Name = nameToCheck, IsFullyQualifiedDomainName = isNameFQDN, Type = Enum.GetName(typeof(AppServiceResourceTypesEnum), type)?.Replace("__", "/")?.Replace("_", ".") ?? "Site" }, new int[] { 200 } ); if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body)) { return(null); } ResourceNameAvailabilityResponse results = JsonConvert.DeserializeObject <ResourceNameAvailabilityResponse>(response.Body); return(results.Result switch { true => true, false => results.ResultReason switch { ResourceNameUnavailabilityReason.AlreadyExists => false, _ => null } });
public void SetupEntitySetNames() { if (_entitySetNames.Count == 0) { string query = "EntityDefinitions?$select=LogicalName,EntitySetName&$filter=IsPrivate eq false"; RestApiResponse <EntityCollection, Error> response = GetAsync <EntityCollection, Error>(query).Result; if (response.IsSuccessStatusCode) { response.Data.Entities.ForEach(e => { _entitySetNames.Add(e.Get <string>("LogicalName"), e.Get <string>("EntitySetName")); }); } } }
public async Task <bool> ExistsUsername(ISession session, string username) { try { RestApiResponse <WSBaseResult> result = await _client.GetAsync <WSBaseResult>(session, $"{_baseServiceUrl}/existsUSername/{username}"); if (result != null && result.Result != null) { return(result.Result.Exists); } } catch (Exception) { return(false); } return(false); }