private void CompareExpectedListResultCommon(StorageAccountListResponse response) { StorageAccountModel result = response.StorageAccounts[2]; Assert.Equal(result.Properties.AccountType, StorageAccountType.StandardLRS); Assert.Equal(result.Properties.CreationTime, "Thu, 20 Aug 2015 16:09:18 GMT"); Assert.Equal(result.Properties.TenantAccountName, "705mystorageaccount3"); Assert.Equal(result.Properties.State, StorageAccountState.Created); Assert.Equal(result.Properties.PrimaryLocation, "DevFabric"); Assert.Equal(result.Properties.StatusOfPrimary, RegionStatus.Available); result = response.StorageAccounts[0]; Assert.Equal(result.Properties.AccountStatus, StorageAccountStatus.OutOfRetentionPeriod); Assert.NotNull(result.Properties.DeletedTime); Assert.Null(result.Properties.RecycledTime); Assert.Equal(result.Properties.CurrentOperation, StorageAccountOperation.Delete); Assert.Equal(result.Properties.PrimaryEndpoints.Count, 3); }
private StorageAccount TryToChooseExistingStandardStorageAccount(StorageManagementClient client) { StorageAccountListResponse storageAccountList = client.StorageAccounts.ListByResourceGroup(this.ResourceGroupName); if (storageAccountList == null || storageAccountList.Count() == 0) { storageAccountList = (StorageAccountListResponse)client.StorageAccounts.List().Where(e => e.Location.Canonicalize().Equals(this.Location.Canonicalize())); if (storageAccountList == null || storageAccountList.Count() == 0) { return(null); } } try { return(storageAccountList.StorageAccounts.First( e => e.AccountType.HasValue && !e.AccountType.Value.ToString().ToLowerInvariant().Contains("premium"))); } catch (InvalidOperationException e) { WriteWarning(string.Format( Properties.Resources.ErrorDuringChoosingStandardStorageAccount, e.Message)); return(null); } }
protected override void Execute() { StorageAccountUndeleteParameters undeleteParam = new StorageAccountUndeleteParameters { NewAccountName = NewAccountName }; if (ShouldProcess( string.Format(CultureInfo.InvariantCulture, Resources.StorageAccountAdminView, AccountId), string.Format(CultureInfo.InvariantCulture, Resources.UndeleteOperation))) { var response = Client.StorageAccounts.Undelete(ResourceGroupName, FarmName, AccountId, undeleteParam); if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, Resources.FailedToUndeleteAccount)); } // get recovered account to set parameters for resource sync WriteVerbose(Resources.RetrieveUndeletedStorageAccount); StorageAccountListResponse accounts = Client.StorageAccounts.List(ResourceGroupName, FarmName, "{accountid eq '" + AccountId + "'}", true); if (accounts.StatusCode != System.Net.HttpStatusCode.OK || accounts.StorageAccounts.Count == 0 || accounts.StorageAccounts[0].Properties == null || accounts.StorageAccounts[0].Properties.TenantSubscriptionId.Equals(Guid.Empty) == true || accounts.StorageAccounts[0].Properties.TenantViewId == null || accounts.StorageAccounts[0].Properties.TenantResourceGroupName == null || accounts.StorageAccounts[0].Location == null) { throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, Resources.FailedToGetAccount)); } // trigger resource sync WriteVerbose(Resources.TriggerResourceSync); StorageAccountSyncRequest req = new StorageAccountSyncRequest(); if (StorageAccountApiVersion == null) { StorageAccountApiVersion = SyncDefaultStorageAccountApiVersion; } if (string.IsNullOrEmpty(ResourceAdminApiVersion)) { ResourceAdminApiVersion = SyncDefaultResourceAdminApiVersion; } req.ApiVersion = StorageAccountApiVersion; req.TargetOperaton = SyncTargetOperation; req.ResourceLocation = accounts.StorageAccounts[0].Location; req.Id = accounts.StorageAccounts[0].Properties.TenantViewId; Client.StorageAccounts.Sync(accounts.StorageAccounts[0].Properties.TenantSubscriptionId.ToString(), accounts.StorageAccounts[0].Properties.TenantResourceGroupName, ResourceAdminApiVersion, req); WriteWarning(Resources.WaitAfterArmSync); } }
public void EnumerateAzureStorageTest() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); StorageAccountListResponse azureStorageListResponse = client.Storages.ListAzureStorages(client.Credentials.SubscriptionId); Assert.True(azureStorageListResponse.StorageAccounts.Count > 0, "Storage accounts count can't be less than 1"); Assert.True(!string.IsNullOrEmpty(azureStorageListResponse.StorageAccounts.First().Properties.Location), "Storage account location shouldn't be null/empty unless it is in some affinity group"); Assert.Equal(HttpStatusCode.OK, azureStorageListResponse.StatusCode); } }
private void CompareExpectedListResultWacProperties(StorageAccountListResponse response, bool isSummary) { StorageAccountModel result = response.StorageAccounts[2]; if (isSummary) { Assert.Null(result.Properties.WacInternalState); Assert.Null(result.Properties.AccountId); Assert.Null(result.Properties.Permissions); } else { Assert.Equal(result.Properties.WacInternalState, WacAccountStates.Active); Assert.Equal(result.Properties.AccountId, (ulong)999); Assert.Equal(result.Properties.Permissions, WacAccountPermissions.Full); } }
private async Task <Dictionary <string, string> > ListStorageAccounts() { Dictionary <string, string> accountDictionary = new Dictionary <string, string>(); CertificateCloudCredentials creds = new CertificateCloudCredentials(_id, _certificate); StorageManagementClient client = new StorageManagementClient(creds); StorageAccountListResponse accounts = await client.StorageAccounts.ListAsync(); foreach (var account in accounts) { StorageAccountGetKeysResponse keys = await client.StorageAccounts.GetKeysAsync(account.Name); accountDictionary.Add(account.Name, keys.PrimaryKey); } return(accountDictionary); }
private static void ListStorageAccounts(ManagementControllerParameters managementControllerParameters, int step) { using (var controller = new ManagementController(managementControllerParameters)) { Console.WriteLine("\n{0}. List Storage Accounts in subscription.", step); ConsoleContinuePrompt("List Storage Accounts"); StorageAccountListResponse lr = controller.ListStorageAccounts(); foreach (var r in lr) { Console.WriteLine(" Account Name: {0}", r.Name, r.Uri); } Console.WriteLine("\n Additional properties are available via .Properties for each account.\n"); Console.WriteLine("...Complete"); } }
/// <summary> /// Gets list of storage account operation response from MS azure using API call. /// </summary> /// <param name="credentials">Source Subscription Credentials</param> /// <returns>list of storage account</returns> internal StorageAccountListResponse GetStorageAccountListResponseFromMSAzure(SubscriptionCloudCredentials credentials) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; dcMigration.ReportProgress(ProgressResources.GetStorageAccountsFromMSAzureStarted); try { Logger.Info(methodName, ProgressResources.GetStorageAccountsFromMSAzureStarted, ResourceType.StorageAccount.ToString()); using (var client = new StorageManagementClient(credentials)) { // Call management API to get list of storage accounts. StorageAccountListResponse storageResponse = Retry.RetryOperation(() => client.StorageAccounts.List(), (BaseParameters)exportParameters, ResourceType.StorageAccount); Logger.Info(methodName, ProgressResources.GetStorageAccountsFromMSAzureCompleted, ResourceType.StorageAccount.ToString()); return(storageResponse); } } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.StorageAccount.ToString()); throw; } }
/// <summary> /// Get the list of all storages for the subscription /// </summary> /// <param name='subscriptionId'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Storage Accounts operation response. /// </returns> public async Task <StorageAccountListResponse> ListAzureStoragesAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); TracingAdapter.Enter(invocationId, this, "ListAzureStoragesAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (subscriptionId != null) { url = url + Uri.EscapeDataString(subscriptionId); } url = url + "/services/storageservices"; 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("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.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) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result StorageAccountListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageAccountListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement storageServicesSequenceElement = responseDoc.Element(XName.Get("StorageServices", "http://schemas.microsoft.com/windowsazure")); if (storageServicesSequenceElement != null) { foreach (XElement storageServicesElement in storageServicesSequenceElement.Elements(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure"))) { StorageAccountListResponse.StorageAccount storageServiceInstance = new StorageAccountListResponse.StorageAccount(); result.StorageAccounts.Add(storageServiceInstance); XElement urlElement = storageServicesElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); storageServiceInstance.Uri = urlInstance; } XElement serviceNameElement = storageServicesElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; storageServiceInstance.Name = serviceNameInstance; } XElement storageServicePropertiesElement = storageServicesElement.Element(XName.Get("StorageServiceProperties", "http://schemas.microsoft.com/windowsazure")); if (storageServicePropertiesElement != null) { StorageAccountListResponse.StorageAccountProperties storageServicePropertiesInstance = new StorageAccountListResponse.StorageAccountProperties(); storageServiceInstance.Properties = storageServicePropertiesInstance; XElement descriptionElement = storageServicePropertiesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { bool isNil = false; XAttribute nilAttribute = descriptionElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance")); if (nilAttribute != null) { isNil = nilAttribute.Value == "true"; } if (isNil == false) { string descriptionInstance = descriptionElement.Value; storageServicePropertiesInstance.Description = descriptionInstance; } } XElement affinityGroupElement = storageServicePropertiesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; storageServicePropertiesInstance.AffinityGroup = affinityGroupInstance; } XElement locationElement = storageServicePropertiesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; storageServicePropertiesInstance.Location = locationInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Exports Subscription metadata. /// </summary> /// <returns>Subscription details/></returns> internal Subscription ExportSubscriptionMetadata() { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); Subscription subscription = new Subscription() { Name = exportParameters.SourceSubscriptionSettings.Name }; Logger.Info(methodName, string.Format(ProgressResources.ExportDataCenterStarted, exportParameters.SourceDCName), ResourceType.DataCenter.ToString(), exportParameters.SourceDCName); dcMigration.ReportProgress(string.Format(ProgressResources.ExportDataCenterStarted, exportParameters.SourceDCName)); AffinityGroupListResponse affinityGroupResponse = GetAffinityGroupListResponseFromMSAzure(exportParameters.SourceSubscriptionSettings.Credentials); HostedServiceListResponse cloudserviceResponse = GetCloudServiceListResponseFromMSAzure(exportParameters.SourceSubscriptionSettings.Credentials, exportParameters.SourceSubscriptionSettings.ServiceUrl); NetworkGetConfigurationResponse networkResponse = GetNetworkConfigurationFromMSAzure(exportParameters.SourceSubscriptionSettings.Credentials, exportParameters.SourceSubscriptionSettings.ServiceUrl); StorageAccountListResponse storageAccountResponse = GetStorageAccountListResponseFromMSAzure(exportParameters.SourceSubscriptionSettings.Credentials); // Create an instance of data center. var dataCenter = new DataCenter { LocationName = exportParameters.SourceDCName, }; // Get all affinity groups. Logger.Info(methodName, ProgressResources.ExportAffinityGroupStarted, ResourceType.AffinityGroup.ToString()); dcMigration.ReportProgress(ProgressResources.ExportAffinityGroupStarted); var affinityGroups = ExportAffinityGroups(affinityGroupResponse); dataCenter.AffinityGroups.AddRange(affinityGroups.ToList()); int stageCount = 1; Logger.Info(methodName, string.Format(ProgressResources.CompletedStages, stageCount, Constants.ExportTotalStages)); dcMigration.ReportProgress(string.Format(ProgressResources.CompletedStages, stageCount, Constants.ExportTotalStages)); List <string> affinityGroupNamesInDC = affinityGroups.Select(ag => ag.AffinityGroupDetails.Name).ToList(); Logger.Info(methodName, ProgressResources.ExportVNetConfigurationStarted, ResourceType.VirtualNetwork.ToString()); dcMigration.ReportProgress(ProgressResources.ExportVNetConfigurationStarted); // Filter and Export network configuration file. dataCenter.NetworkConfiguration = ExportVNetConfiguration(networkResponse, affinityGroupNamesInDC); Logger.Info(methodName, string.Format(ProgressResources.CompletedStages, ++stageCount, Constants.ExportTotalStages)); dcMigration.ReportProgress(string.Format(ProgressResources.CompletedStages, stageCount, Constants.ExportTotalStages)); Logger.Info(methodName, ProgressResources.ExportCloudServicesStarted, ResourceType.CloudService.ToString()); dcMigration.ReportProgress(ProgressResources.ExportCloudServicesStarted); // Get cloud services for affinityGroupNamesInDC or for SourceDCName dataCenter.CloudServices.AddRange(ExportCloudServices(affinityGroupNamesInDC, cloudserviceResponse)); Logger.Info(methodName, string.Format(ProgressResources.CompletedStages, ++stageCount, Constants.ExportTotalStages)); dcMigration.ReportProgress(string.Format(ProgressResources.CompletedStages, stageCount, Constants.ExportTotalStages)); Logger.Info(methodName, ProgressResources.ExportStorageAccountStarted, ResourceType.StorageAccount.ToString()); dcMigration.ReportProgress(ProgressResources.ExportStorageAccountStarted); // Get list of storage accounts dataCenter.StorageAccounts.AddRange(ExportStorageAccounts(affinityGroupNamesInDC, storageAccountResponse)); Logger.Info(methodName, string.Format(ProgressResources.CompletedStages, ++stageCount, Constants.ExportTotalStages)); dcMigration.ReportProgress(string.Format(ProgressResources.CompletedStages, stageCount, Constants.ExportTotalStages)); // Add the data center into subscription. subscription.DataCenters.Add(dataCenter); Logger.Info(methodName, string.Format(ProgressResources.ExportDataCenterCompleted, dataCenter.LocationName), ResourceType.DataCenter.ToString()); Logger.Info(methodName, ProgressResources.ExecutionCompleted); return(subscription); }
/// <summary> /// Exports list of production cloud services. /// </summary> /// <param name="dcAffinityGroupNames">Affinity group names for which storage accounts to be filtered out</param> /// <param name="storageAccounts">StorageAccountListResponse to filter accounts by SourceDC account names</param> /// <returns>List of production cloud services</returns> private List <Azure.DataCenterMigration.Models.StorageAccount> ExportStorageAccounts(List <string> dcAffinityGroupNames, StorageAccountListResponse storageAccounts) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExportStorageAccountStarted, ResourceType.StorageAccount.ToString()); try { List <Azure.DataCenterMigration.Models.StorageAccount> storageAccountsInDC = (from account in storageAccounts where ((string.Compare(account.Properties.Location, exportParameters.SourceDCName, StringComparison.CurrentCultureIgnoreCase) == 0) || (account.Properties.Location == null && (dcAffinityGroupNames.Contains(account.Properties.AffinityGroup)))) select new Azure.DataCenterMigration.Models.StorageAccount { IsImported = false, StorageAccountDetails = account, Containers = ExportStorageAccountContainers(account) } ).ToList(); Logger.Info(methodName, ProgressResources.ExportStorageAccountCompleted, ResourceType.StorageAccount.ToString()); return(storageAccountsInDC); } catch (Exception ex) { Logger.Error(methodName, ex); throw; } }
/// <summary> /// Validates whether the storage belongs to the currently logged account or not. /// </summary> /// <param name="azureSubscription">Subscription ID</param> /// <param name="azureStorageAccount">Storage Account details</param> /// <param name="vaultLocation">Current Vault Location</param> /// <param name="validationSuccessful">Out variable to indicate if validation was successful</param> /// <param name="locationValid">Out variable to indicate if location of storage account is valid</param> public void ValidateStorageAccountAssociation( string azureSubscription, string azureStorageAccount, string vaultLocation, out bool validationSuccessful, out bool locationValid) { if (string.IsNullOrEmpty(azureSubscription)) { throw new InvalidOperationException( string.Format( Properties.Resources.SubscriptionIdIsNotValid)); } if (string.IsNullOrEmpty(azureStorageAccount)) { throw new InvalidOperationException( string.Format( Properties.Resources.StorageAccountNameIsNotValid)); } bool associatedAccount = false; StorageAccountListResponse azureStorageListResponse = null; StorageAccountListResponse.StorageAccount currentStorageAccount = null; try { azureStorageListResponse = this.GetSiteRecoveryClient().Storages.ListAzureStorages(azureSubscription); } catch (Exception) { validationSuccessful = false; locationValid = false; return; } foreach (var storage in azureStorageListResponse.StorageAccounts) { if (string.Compare( azureStorageAccount, storage.Name, StringComparison.OrdinalIgnoreCase) == 0) { associatedAccount = true; currentStorageAccount = storage; break; } } if (!associatedAccount) { validationSuccessful = false; locationValid = false; return; } // Validate that the Geo Location of the storage account is the same as that of the vault. if (string.IsNullOrEmpty(currentStorageAccount.Properties.Location)) { validationSuccessful = false; locationValid = false; return; } if (0 != string.Compare( currentStorageAccount.Properties.Location, vaultLocation, StringComparison.OrdinalIgnoreCase)) { validationSuccessful = true; locationValid = false; return; } validationSuccessful = true; locationValid = true; }
/// <summary> /// Exports list of production cloud services. /// </summary> /// <param name="dcAffinityGroupNames">Affinity group names for which storage accounts to be filtered out</param> /// <param name="storageAccounts">StorageAccountListResponse to filter accounts by SourceDC account names</param> /// <returns>List of production cloud services</returns> private List<Azure.DataCenterMigration.Models.StorageAccount> ExportStorageAccounts(List<string> dcAffinityGroupNames, StorageAccountListResponse storageAccounts) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExportStorageAccountStarted, ResourceType.StorageAccount.ToString()); try { List<Azure.DataCenterMigration.Models.StorageAccount> storageAccountsInDC = (from account in storageAccounts where ((string.Compare(account.Properties.Location, exportParameters.SourceDCName, StringComparison.CurrentCultureIgnoreCase) == 0) || (account.Properties.Location == null && (dcAffinityGroupNames.Contains(account.Properties.AffinityGroup)))) select new Azure.DataCenterMigration.Models.StorageAccount { IsImported = false, StorageAccountDetails = account, Containers = ExportStorageAccountContainers(account) } ).ToList(); Logger.Info(methodName, ProgressResources.ExportStorageAccountCompleted, ResourceType.StorageAccount.ToString()); return storageAccountsInDC; } catch (Exception ex) { Logger.Error(methodName, ex); throw; } }