private static HttpStatusCode UploadNewManagementCert(string subscriptionId, X509Certificate2 existingCertificate, string newCertificateCerFilePath) { var statusCode = HttpStatusCode.Unused; var newCertificate = new X509Certificate2(newCertificateCerFilePath); var creds = new CertificateCloudCredentials(subscriptionId, existingCertificate); var client = new ManagementClient(creds); var parm = new ManagementCertificateCreateParameters() { Data = newCertificate.RawData, PublicKey = newCertificate.GetPublicKey(), Thumbprint = newCertificate.Thumbprint }; //Hyak throws an exception for a Created result, which is actually the success code try { var response = client.ManagementCertificates.Create(parm); } catch (CloudException ex) { statusCode = ex.Response.StatusCode; } return statusCode; }
public TestClientProvider(ManagementClient mgmtClient, ComputeManagementClient computeClient, StorageManagementClient storageClient, NetworkManagementClient networkClient) { this.managementClient = mgmtClient; this.computeManagementClient = computeClient; this.storageManagementClient = storageClient; this.networkManagementClient = networkClient; }
public static string GetTestLocation(ManagementClient managementClient) { string location = managementClient.GetDefaultLocation("Storage", "Compute"); const string usWestLocStr = "West US"; if (managementClient.Locations.List().Any( c => string.Equals(c.Name, usWestLocStr, StringComparison.OrdinalIgnoreCase))) { location = usWestLocStr; } return location; }
public ManagementController(ManagementControllerParameters parameters) { _parameters = parameters; // To authenticate against the Microsoft Azure service management API we require management certificate // load this from a publish settings file and later use it with the Service Management Libraries var credentials = GetSubscriptionCloudCredentials(parameters.PublishSettingsFilePath); // Create a management client and a virtual network management client _managementClient = CloudContext.Clients.CreateManagementClient(credentials); _virtualNetworkManagementClient = CloudContext.Clients.CreateVirtualNetworkManagementClient(credentials); }
public void ManagementClientReturnsLocationList() { // Import certificate CertificateEnrollmentManager.ImportPfxDataAsync(_certificateString, _certificatePassword, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "test").AsTask().Wait(); var credentials = new CertificateCloudCredentials(_subscription); var client = new ManagementClient(credentials); var result = client.Locations.List(); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsTrue(result.Locations.Count > 0); }
public VMManagement(string subscriptionId, byte[] managementCertificate, string certificateKey, string blobStorageName, string blobStorageKey, ILogger logger) { _managementCertificate = new X509Certificate2(managementCertificate, certificateKey, X509KeyStorageFlags.MachineKeySet); _subscriptionId = subscriptionId; CertificateCloudCredentials cloudCredentials = new CertificateCloudCredentials(_subscriptionId, _managementCertificate); _datacenter = new ManagementClient(cloudCredentials);// CloudContext.Clients.CreateManagementClient(cloudCredentials); //var roleSizes = _datacenter.RoleSizes.List(); _compute = new ComputeManagementClient(cloudCredentials);// CloudContext.Clients.CreateComputeManagementClient(cloudCredentials); _storage = new StorageManagementClient(cloudCredentials);// CloudContext.Clients.CreateStorageManagementClient(cloudCredentials); }
private static X509Certificate2 GetExistingManagementCertificate(string subscriptionId) { var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); var azureCerts = certStore.Certificates.Find(X509FindType.FindByIssuerName, "Windows Azure Tools", false); foreach (var cert in azureCerts) { var creds = new CertificateCloudCredentials(subscriptionId, cert); var client = new ManagementClient(creds); try { var v = client.Locations.List(); return cert; } catch (CloudException) { } } return null; }
private async void GetRegionList() { StatusMessage = "Getting Regions"; using (var client = new ManagementClient( new CertificateCloudCredentials(SelectedSubscription.SubscriptionId, new X509Certificate2(Convert.FromBase64String( SelectedSubscription.ManagementCertificate))))) { var result = await client.Locations.ListAsync(); Locations = result.Locations; } StatusMessage = "Regions Loaded"; }
internal CloudServiceClient( AzureSubscription subscription, ManagementClient managementClient, StorageManagementClient storageManagementClient, ComputeManagementClient computeManagementClient) : this((string)null, null, null, null) { Subscription = subscription; CurrentDirectory = null; DebugStream = null; VerboseStream = null; WarningStream = null; CloudBlobUtility = new CloudBlobUtility(); ManagementClient = managementClient; StorageClient = storageManagementClient; ComputeClient = computeManagementClient; }
///<summary> /// Deletes the affinity group if it is started creating and the corresponding task is got cancelled later. /// </summary> /// <param name="resourceType">Resource Type</param> /// <param name="affinityGroupName">Affinity Group Name</param> internal void DeleteAffinityGroupIfTaskCancelled(ResourceType resourceType, string affinityGroupName) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; AffinityGroupListResponse affinityGroupResponse = GetAffinityGroupListResponseFromMSAzure( importParameters.DestinationSubscriptionSettings.Credentials); var affinityGroupInDestinationSubscription = (from ag in affinityGroupResponse.AffinityGroups where (string.Compare(ag.Name, affinityGroupName, StringComparison.CurrentCultureIgnoreCase) == 0) select ag).FirstOrDefault(); if (affinityGroupInDestinationSubscription != null) { Logger.Info(methodName, string.Format(ProgressResources.DeleteAGOnTaskCancelled, affinityGroupName), ResourceType.AffinityGroup.ToString(), affinityGroupName); using (var client = new ManagementClient(importParameters.DestinationSubscriptionSettings.Credentials, importParameters.DestinationSubscriptionSettings.ServiceUrl)) { try { client.AffinityGroups.Delete(affinityGroupName); } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.AffinityGroup.ToString(), affinityGroupName); // Ignore the exception if occurs in cleanup process } } } }
/// <summary> /// Exports list of SubscriptionId specific dataCenters. /// </summary> ///<param name="credentials"> Subscription credentials</param> /// <param name="retryCount"> No. of times to retry in case of exception</param> /// <param name="minBackOff">Minimum backoff in seconds</param> /// <param name="maxBackOff">Maximum backoff in seconds</param> /// <param name="deltaBackOff">Delta Backoff in seconds</param> /// <returns>List of SubscriptionId specific dataCenters.</returns> private static List<string> ExportDataCenterLocations(SubscriptionCloudCredentials credentials, int retryCount, double minBackOff, double maxBackOff, double deltaBackOff) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); try { using (var client = new ManagementClient(credentials)) { BaseParameters baseParams = new BaseParameters() { RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff) }; // Call management API to get list of locations. var locations = Retry.RetryOperation(() => client.Locations.List(), baseParams, ResourceType.None); Logger.Info(methodName, ProgressResources.ExecutionCompleted); return locations.Select(l => l.Name).ToList(); } } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.None.ToString()); throw; } }
/// <summary> /// Validates and converts input paramters into <see cref="ImportParameters"/> class. /// </summary> /// <param name="parameters">Collection of input parameters stored in key value pairs /// <example> Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" /// DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationDCName "West US" /// SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" DestinationPrefixName "dc" QuietMode "True" /// RollBackOnFailure "True" ResumeImport "True" </example> </param> /// <param name="validateForImport">True if the function will be called for imort functionality. /// False if it is called for Migrate functionality</param> /// <returns>Parameters required for import functionality</returns> internal static ImportParameters ValidateAndConvertImportParameters(IDictionary<string, string> parameters, bool validateForImport) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); Logger.Info(methodName, ProgressResources.ParameterValidationStarted); #region Check for missing required parameters // SourcePublishSettingsFilePath/ CertificateThumbprint if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.SourceCertificateThumbprint)) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments)); } // DestinationPublishSettingsFilePath if (!parameters.Keys.Contains(Constants.Parameters.DestinationPublishSettingsFilePath) && !parameters.Keys.Contains(Constants.Parameters.DestinationCertificateThumbprint)) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments)); } // SourceSubscriptionID if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments)); } // DestinationSubscriptionID if (!parameters.Keys.Contains(Constants.Parameters.DestinationSubscriptionID)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.DestinationSubscriptionID, Constants.AppConfigArguments)); } // DestinationDCName if (!parameters.Keys.Contains(Constants.Parameters.DestinationDCName)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.DestinationDCName, Constants.AppConfigArguments)); } //DestinationPrefixName & MapperXmlFilePath. if (!validateForImport) { if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.DestinationPrefixName, Constants.AppConfigArguments)); } } else { if (!parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) && !parameters.Keys.Contains(Constants.Parameters.MapperXmlFilePath)) { throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix, StringResources.Destination, Constants.AppConfigArguments)); } } #endregion #region Check for null or empty values //SourcePublishSettingsFilePath if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath])) || (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint]))) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments)); } // DestinationPublishSettingsFilePath if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPublishSettingsFilePath])) || (parameters.ContainsKey(Constants.Parameters.DestinationCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationCertificateThumbprint]))) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Destination, Constants.AppConfigArguments)); } // ImportMetadataFilePath if (validateForImport && (string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath]))) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.ImportMetadataFilePath)); } // DestinationSubscriptionID if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationSubscriptionID])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationSubscriptionID)); } // DestinationDCName if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationDCName])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationDCName)); } //DestinationPrefixName & MapperXmlFilePath. if (!validateForImport) { if (string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.DestinationPrefixName)); } } else { if ((parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) && string.IsNullOrEmpty(parameters[Constants.Parameters.DestinationPrefixName])) || (parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.MapperXmlFilePath]))) { throw new ValidationException(string.Format(StringResources.MissingMapperAndPrefix, StringResources.Destination, Constants.AppConfigArguments)); } } #endregion #region Validate parameter's value. // Validate SourcePublishSettingsFilePath if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath]))) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.SourcePublishSettingsFilePath), new FileNotFoundException(StringResources.PublishSettingsFilePathParamException)); } // Validate DestinationPublishSettingsFilePath if ((parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]))) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.DestinationPublishSettingsFilePath), new FileNotFoundException(StringResources.PublishSettingsFilePathParamException)); } string importMapperXmlFilePath = string.Empty; string destinationPrefix = string.Empty; // Validate MapperXmlFilePath if provided if (validateForImport && parameters.ContainsKey(Constants.Parameters.MapperXmlFilePath)) { importMapperXmlFilePath = parameters[Constants.Parameters.MapperXmlFilePath]; if (!File.Exists(importMapperXmlFilePath)) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.MapperXmlFilePath), new FileNotFoundException(StringResources.MapperFilePathParamException)); } if (!Path.GetExtension(importMapperXmlFilePath).Equals(Constants.MapperFileExtension, StringComparison.InvariantCultureIgnoreCase)) { throw new ValidationException(string.Format(StringResources.InvalidExtensionMapperFile, Constants.Parameters.MapperXmlFilePath), new FileNotFoundException(StringResources.MapperFilePathParamException)); } } destinationPrefix = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ? parameters[Constants.Parameters.DestinationPrefixName].ToLower() : Constants.DestinationPrefixValue; // Validate ImportMetadataFilePath if (validateForImport) { if (!string.IsNullOrEmpty(parameters[Constants.Parameters.ImportMetadataFilePath])) { string filePath = parameters[Constants.Parameters.ImportMetadataFilePath]; if (!File.Exists(filePath)) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.ImportMetadataFilePath), new FileNotFoundException(StringResources.ImportMetadataFilePathParamException)); } if (!Path.GetExtension(filePath).Equals(Constants.MetadataFileExtension, StringComparison.InvariantCultureIgnoreCase)) { throw new ValidationException(string.Format(StringResources.InvalidExtensionMetadataFile, Constants.Parameters.ImportMetadataFilePath), new FileNotFoundException(StringResources.ImportMetadataFilePathParamException)); } } } bool rollBackBoolValue; bool resumeImportBoolValue; int retryCount; Double minBackOff; Double maxBackOff; Double deltaBackOff; if (!parameters.Keys.Contains(Constants.Parameters.RollBackOnFailure)) { rollBackBoolValue = false; } else { bool.TryParse(parameters[Constants.Parameters.RollBackOnFailure], out rollBackBoolValue); } if (!parameters.Keys.Contains(Constants.Parameters.ResumeImport)) { resumeImportBoolValue = false; } else { bool.TryParse(parameters[Constants.Parameters.ResumeImport], out resumeImportBoolValue); } if (!parameters.Keys.Contains(Constants.Parameters.RetryCount)) { retryCount = Int32.Parse(Constants.RetryCountDefault); } else { Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount); } if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff)) { minBackOff = Double.Parse(Constants.MinBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff); } if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff)) { maxBackOff = Double.Parse(Constants.MaxBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff); } if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff)) { deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff); } // Validate SourcePublishSettings File PublishSettings sourcePublishSettingsFile = null; PublishSetting sourceSubscription = null; if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath)) { try { var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]); sourcePublishSettingsFile = new PublishSettings(fileContents); } catch (Exception xmlEx) { throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message, parameters[Constants.Parameters.SourcePublishSettingsFilePath])); } // Check whether sourceSubscriptionId exists in publish settings file sourceSubscription = sourcePublishSettingsFile.Subscriptions.FirstOrDefault(a => string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0); if (sourceSubscription == null) { throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath])); } } else { string thumbprint = parameters[Constants.Parameters.SourceCertificateThumbprint]; X509Certificate2 certificate = GetStoreCertificate(thumbprint); if (!certificate.HasPrivateKey) { throw new ValidationException(string.Format( StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint)); } var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID], certificate); string sourceSubscriptionName = null; using (var client = new ManagementClient(sourceCredentials)) { BaseParameters baseParams = new BaseParameters() { RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff) }; SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None); sourceSubscriptionName = subscriptionResponse.SubscriptionName; } sourceSubscription = new PublishSetting() { Id = parameters[Constants.Parameters.SourceSubscriptionID], Name = sourceSubscriptionName, ServiceUrl = new Uri(Constants.ServiceManagementUrlValue), Credentials = sourceCredentials }; } // Validate DestinationPublishSettings File PublishSettings destPublishSettingsFile = null; PublishSetting destSubscription = null; if (parameters.ContainsKey(Constants.Parameters.DestinationPublishSettingsFilePath)) { try { var fileContents = File.ReadAllText(parameters[Constants.Parameters.DestinationPublishSettingsFilePath]); destPublishSettingsFile = new PublishSettings(fileContents); } catch (Exception xmlEx) { throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message, parameters[Constants.Parameters.DestinationPublishSettingsFilePath])); } // Check whether destSubscriptionId exists in publish settings file destSubscription = destPublishSettingsFile.Subscriptions.FirstOrDefault(a => string.Compare(a.Id, parameters[Constants.Parameters.DestinationSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0); if (destSubscription == null) { throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.DestinationSubscriptionID], parameters[Constants.Parameters.DestinationPublishSettingsFilePath])); } } else { string thumbprint = parameters[Constants.Parameters.DestinationCertificateThumbprint]; X509Certificate2 certificate = GetStoreCertificate(thumbprint); if (!certificate.HasPrivateKey) { throw new ValidationException(string.Format( StringResources.MissingPrivateKeyInCertificate, StringResources.Destination, thumbprint)); } var destCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.DestinationSubscriptionID], certificate); string destSubscriptionName = null; using (var client = new ManagementClient(destCredentials)) { BaseParameters baseParams = new BaseParameters() { RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff) }; SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None); destSubscriptionName = subscriptionResponse.SubscriptionName; } destSubscription = new PublishSetting() { Id = parameters[Constants.Parameters.DestinationSubscriptionID], Name = destSubscriptionName, ServiceUrl = new Uri(Constants.ServiceManagementUrlValue), Credentials = destCredentials }; } // Check whether DestinationDCName exists in subscription List<string> locations = ExportDataCenterLocations(destSubscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff); bool destinationLocationNamePresent = locations.Any((l => string.Compare(l, parameters[Constants.Parameters.DestinationDCName], StringComparison.CurrentCultureIgnoreCase) == 0)); if (!destinationLocationNamePresent) { throw new ValidationException(string.Format(StringResources.DCParamException, parameters[Constants.Parameters.DestinationDCName])); } // Valiadte DestinationPrefixName if (parameters.ContainsKey(Constants.Parameters.DestinationPrefixName) && (parameters[Constants.Parameters.DestinationPrefixName].Length < 1 || parameters[Constants.Parameters.DestinationPrefixName].Length > 5)) { throw new ValidationException(string.Format(StringResources.InvalidDestinationPrefixName, parameters[Constants.Parameters.DestinationPrefixName])); } #endregion // Stores validated parameters in class. ImportParameters importParams = new ImportParameters() { DestinationDCName = parameters[Constants.Parameters.DestinationDCName], ImportMetadataFilePath = (!validateForImport) ? null : parameters[Constants.Parameters.ImportMetadataFilePath], MapperXmlFilePath = importMapperXmlFilePath, DestinationPrefixName = destinationPrefix, DestinationSubscriptionSettings = destSubscription, RollBackOnFailure = rollBackBoolValue, ResumeImport = resumeImportBoolValue, RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff), SourceSubscriptionSettings = sourceSubscription }; Logger.Info(methodName, ProgressResources.ParametersValidationCompleted); return importParams; }
/// <summary> /// Gets list of affinity group operation response from MS azure using API call. /// </summary> /// <param name="credentials">credentials</param> /// <returns>List of affinity group operation response for subscription </returns> private AffinityGroupListResponse GetAffinityGroupListResponseFromMSAzure(SubscriptionCloudCredentials credentials) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureStarted, ResourceType.AffinityGroup.ToString()); dcMigration.ReportProgress(ProgressResources.GetAffinityGroupsFromMSAzureStarted); try { using (var client = new ManagementClient(credentials)) { //// Call management API to get list of affinity groups. AffinityGroupListResponse agResponse = Retry.RetryOperation(() => client.AffinityGroups.List(),(BaseParameters)exportParameters,ResourceType.AffinityGroup); Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureCompleted, ResourceType.AffinityGroup.ToString()); return agResponse; } } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.AffinityGroup.ToString()); throw; } }
/// <summary> /// Creates affinity groups. /// </summary> /// <param name="affinityGroups">List of affinity groups.</param> /// <param name="response">Source affinity groups with details from which the required affinity groups will be filtered and created</param> private void CreateAffinityGroups(List<AffinityGroup> affinityGroups, AffinityGroupListResponse response) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted, ResourceType.AffinityGroup.ToString()); Stopwatch swTotalAG = new Stopwatch(); swTotalAG.Start(); using (var client = new ManagementClient(importParameters.DestinationSubscriptionSettings.Credentials)) { Parallel.ForEach(affinityGroups, affinityGroup => { try { // Check if affinity group is already imported, if not create new affinity group if (!affinityGroup.IsImported) { Logger.Info(methodName, string.Format(ProgressResources.ImportAffinityGroupStarted, affinityGroup.AffinityGroupDetails.Name), ResourceType.AffinityGroup.ToString(), affinityGroup.AffinityGroupDetails.Name); Stopwatch swSingleAG = new Stopwatch(); swSingleAG.Start(); OperationResponse createAffinityGroupResult = Retry.RetryOperation(() => client.AffinityGroups.Create( new AffinityGroupCreateParameters { Description = affinityGroup.AffinityGroupDetails.Description, Label = null, // Label is set automatically. Location = importParameters.DestinationDCName, Name = affinityGroup.AffinityGroupDetails.Name }), (BaseParameters)importParameters, ResourceType.AffinityGroup, affinityGroup.AffinityGroupDetails.Name, () => DeleteAffinityGroupIfTaskCancelled(ResourceType.AffinityGroup, affinityGroup.AffinityGroupDetails.Name) ); UpdateMedatadaFile(ResourceType.AffinityGroup, affinityGroup.AffinityGroupDetails.Name); swSingleAG.Stop(); Logger.Info(methodName, string.Format(ProgressResources.ImportAffinityGroupCompleted, affinityGroup.AffinityGroupDetails.Name, swSingleAG.Elapsed.Days, swSingleAG.Elapsed.Hours, swSingleAG.Elapsed.Minutes, swSingleAG.Elapsed.Seconds), ResourceType.AffinityGroup.ToString(), affinityGroup.AffinityGroupDetails.Name); } } catch (AggregateException exAgg) { foreach (var ex in exAgg.InnerExceptions) { Logger.Error(methodName, ex, ResourceType.AffinityGroup.ToString(), affinityGroup.AffinityGroupDetails.Name); } throw; } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.AffinityGroup.ToString(), affinityGroup.AffinityGroupDetails.Name); throw; } }); } Logger.Info(methodName, string.Format(ProgressResources.ExecutionCompletedWithTime, swTotalAG.Elapsed.Days, swTotalAG.Elapsed.Hours, swTotalAG.Elapsed.Minutes, swTotalAG.Elapsed.Seconds), ResourceType.AffinityGroup.ToString()); }
public StoreClient( WindowsAzureSubscription subscription, ComputeManagementClient compute, StoreManagementClient store, MarketplaceClient marketplace, ManagementClient management) { Validate.ValidateStringIsNullOrEmpty(subscription.SubscriptionId, null, true); this.subscriptionId = subscription.SubscriptionId; computeClient = compute; storeClient = store; MarketplaceClient = marketplace; managementClient = management; }
/// <summary> /// Rollback all imported affinity groups. /// </summary> /// <param name="affinityGroups">Affinity groups to be deleted.</param> private void RollBackAffinityGroups(List<string> affinityGroups) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted, ResourceType.AffinityGroup.ToString()); dcMigrationManager.ReportProgress(ProgressResources.RollbackAffinityGroups); Logger.Info(methodName, ProgressResources.RollbackAffinityGroups, ResourceType.AffinityGroup.ToString()); Stopwatch swTotalAffGrp = new Stopwatch(); swTotalAffGrp.Start(); if (affinityGroups.Count > 0) { using (var client = new ManagementClient(importParameters.DestinationSubscriptionSettings.Credentials, importParameters.DestinationSubscriptionSettings.ServiceUrl)) { Parallel.ForEach(affinityGroups, affinityGroup => { Stopwatch swAffinityGroup = new Stopwatch(); swAffinityGroup.Start(); try { Retry.RetryOperation(() => client.AffinityGroups.Delete(affinityGroup), (BaseParameters)importParameters, ResourceType.AffinityGroup, affinityGroup, ignoreResourceNotFoundEx: true); resourceImporter.UpdateMedatadaFile(ResourceType.AffinityGroup, affinityGroup, false); swAffinityGroup.Stop(); Logger.Info(methodName, string.Format(ProgressResources.RollbackAffinityGroup, affinityGroup,swAffinityGroup.Elapsed.Days, swAffinityGroup.Elapsed.Hours, swAffinityGroup.Elapsed.Minutes, swAffinityGroup.Elapsed.Seconds), ResourceType.AffinityGroup.ToString(), affinityGroup); } catch (AggregateException exAgg) { foreach (var ex in exAgg.InnerExceptions) { Logger.Error(methodName, exAgg, ResourceType.AffinityGroup.ToString(), affinityGroup); } throw; } }); dcMigrationManager.ReportProgress(ProgressResources.RollbackAffinityGroupsWaiting); Logger.Info(methodName, ProgressResources.RollbackAffinityGroupsWaiting, ResourceType.AffinityGroup.ToString()); Task.Delay(Constants.DelayTimeInMilliseconds_Rollback).Wait(); } } swTotalAffGrp.Stop(); Logger.Info(methodName, string.Format(ProgressResources.ExecutionCompletedWithTime, swTotalAffGrp.Elapsed.Days, swTotalAffGrp.Elapsed.Hours, swTotalAffGrp.Elapsed.Minutes, swTotalAffGrp.Elapsed.Seconds), ResourceType.AffinityGroup.ToString()); }
// Enumerating services, from http://www.scip.be/index.php?Page=ArticlesNET39&Lang=EN public List<AzureInfo> GetForSubscription(Subscription Subscription) { List<AzureInfo> results = new List<AzureInfo>(); CertificateCloudCredentials creds = this.GetCredentials(Subscription); string subscriptionName; string subscriptionStatus; using (ManagementClient mgmtClient = new ManagementClient(creds)) { SubscriptionGetResponse subscription = mgmtClient.Subscriptions.Get(); subscriptionName = subscription.SubscriptionName; subscriptionStatus = subscription.SubscriptionStatus.ToString(); } using (ComputeManagementClient vmClient = new ComputeManagementClient(creds)) { List<HostedServiceListResponse.HostedService> vms = vmClient.HostedServices.List().ToList(); results.AddRange( from vm in vms let vmDetails = vmClient.Deployments.GetByName(vm.ServiceName, vm.ServiceName) select new AzureInfo { SubscriptionId = Subscription.SubscriptionId, SubscriptionName = subscriptionName, SubscriptionStatus = subscriptionStatus, AzureType = AzureType.VirtualMachine, Name = vm.ServiceName, Uri = vm.Uri, Urls = new List<string> { vmDetails.Uri.OriginalString }.Union((from i in vmDetails.VirtualIPAddresses select i.Address)).ToList(), CreationStatus = vm.Properties.Status.ToString(), Status = vmDetails.Status.ToString(), Location = vm.Properties.Location, AffinityGroup = vm.Properties.AffinityGroup, Label = vm.Properties.Label, Online = vmDetails.Status == DeploymentStatus.Running } ); } using (ComputeManagementClient vmClient = new ComputeManagementClient(creds)) { List<VirtualMachineDiskListResponse.VirtualMachineDisk> disks = vmClient.VirtualMachineDisks.ListDisks().ToList(); results.AddRange( from disk in disks select new AzureInfo { SubscriptionId = Subscription.SubscriptionId, SubscriptionName = subscriptionName, SubscriptionStatus = subscriptionStatus, AzureType = AzureType.VirtualDisk, Name = disk.Name, Location = disk.Location, AffinityGroup = disk.AffinityGroup, Label = disk.Label, MaxSizeGb = disk.LogicalSizeInGB, TypeDescription = disk.OperatingSystemType, HostedServiceName = disk.UsageDetails.HostedServiceName, DeploymentName = disk.UsageDetails.DeploymentName, VirtualMachineName = disk.UsageDetails.RoleName, Urls = new List<string>{disk.MediaLinkUri.OriginalString}, Status = "Running", Online = !(disk.IsCorrupted ?? false) } ); } using (WebSiteManagementClient siteClient = new WebSiteManagementClient(creds)) { WebSpacesListResponse spaces = siteClient.WebSpaces.List(); results.AddRange( from space in spaces let sites = siteClient.WebSpaces.ListWebSites(space.Name, new WebSiteListParameters { PropertiesToInclude = {}}) from site in sites let ws = siteClient.WebSites.Get(space.Name, site.Name, new WebSiteGetParameters()).WebSite select new AzureInfo { SubscriptionId = Subscription.SubscriptionId, SubscriptionName = subscriptionName, SubscriptionStatus = subscriptionStatus, AzureType = AzureType.WebApp, Name = site.Name, Uri = ws.Uri, Urls = site.HostNames.ToList(), Status = (site.RuntimeAvailabilityState != WebSiteRuntimeAvailabilityState.Normal) ? (site.RuntimeAvailabilityState ?? WebSiteRuntimeAvailabilityState.NotAvailable).ToString() : site.State, CreationStatus = "Created", Location = space.Name, TypeDescription = site.ServerFarm, // == ws.ServerFarm Online = (site.Enabled ?? false) && (site.RuntimeAvailabilityState == WebSiteRuntimeAvailabilityState.Normal) && (site.State == "Running") } ); } using (StorageManagementClient storageClient = CloudContext.Clients.CreateStorageManagementClient(creds)) { List<StorageAccount> storages = storageClient.StorageAccounts.List().ToList(); results.AddRange( from storage in storages select new AzureInfo { SubscriptionId = Subscription.SubscriptionId, SubscriptionName = subscriptionName, SubscriptionStatus = subscriptionStatus, AzureType = AzureType.Storage, Name = storage.Name, Uri = storage.Uri, Location = storage.Properties.Location, AffinityGroup = storage.Properties.AffinityGroup, Label = storage.Properties.Label, TypeDescription = storage.Properties.Description, Status = "Running", Online = storage.Properties.Status == StorageAccountStatus.Created, CreationStatus = storage.Properties.Status.ToString(), Redundancy = storage.Properties.AccountType, Urls = ( from i in storage.Properties.Endpoints select i.OriginalString ).ToList() } ); } using (SqlManagementClient sqlClient = CloudContext.Clients.CreateSqlManagementClient(creds)) { List<Server> servers = sqlClient.Servers.List().ToList(); results.AddRange( from server in servers let dbs = sqlClient.Databases.List(server.Name).ToList() from db in dbs select new AzureInfo { SubscriptionId = Subscription.SubscriptionId, SubscriptionName = subscriptionName, SubscriptionStatus = subscriptionStatus, AzureType = AzureType.SqlDatabase, Name = db.Name, Status = server.State, CreationStatus = server.State, Online = server.State == "Ready", Location = server.Location, TypeDescription = db.Edition, MaxSizeGb = db.MaximumDatabaseSizeInGB, ServerName = server.Name, HostedServiceName = server.FullyQualifiedDomainName, } ); }; return results; }
/// <summary> /// Validates and converts input paramters into <see cref="ExportParameters"/> class. /// </summary> /// <param name="parameters">Collection of input parameters stored in key value pairs /// <example> Operation "Export" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" SourceDCName "East Asia" /// ExportMetadataFolderPath "D:\\DataCenterMigration" SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" /// QuietMode "True" </example> </param> /// <returns>Parameters required for export functionality</returns> internal static ExportParameters ValidateAndConvertExportParameters(IDictionary<string, string> parameters) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); Logger.Info(methodName, ProgressResources.ParameterValidationStarted); #region Check for missing required parameters // PublishSettingsFilePath / CertificateThumbprint if (!parameters.Keys.Contains(Constants.Parameters.SourcePublishSettingsFilePath) && !parameters.Keys.Contains( Constants.Parameters.SourceCertificateThumbprint)) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments)); } // ExportMetadataFolderPath if (!parameters.Keys.Contains(Constants.Parameters.ExportMetadataFolderPath)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.ExportMetadataFolderPath, Constants.AppConfigArguments)); } // SourceSubscriptionID if (!parameters.Keys.Contains(Constants.Parameters.SourceSubscriptionID)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.SourceSubscriptionID, Constants.AppConfigArguments)); } // SourceDCName if (!parameters.Keys.Contains(Constants.Parameters.SourceDCName)) { throw new ValidationException(string.Format(StringResources.MissingRequiredParameter, Constants.Parameters.SourceDCName, Constants.AppConfigArguments)); } #endregion #region Check for null or empty values // PublishSettingsFilePath if ((parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourcePublishSettingsFilePath])) || (parameters.ContainsKey(Constants.Parameters.SourceCertificateThumbprint) && string.IsNullOrEmpty(parameters[Constants.Parameters.SourceCertificateThumbprint]))) { throw new ValidationException(string.Format(StringResources.MissingCredentialsFile, StringResources.Source, Constants.AppConfigArguments)); } // ExportMetadataFolderPath if (string.IsNullOrEmpty(parameters[Constants.Parameters.ExportMetadataFolderPath])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.ExportMetadataFolderPath)); } // SourceSubscriptionID if (string.IsNullOrEmpty(parameters[Constants.Parameters.SourceSubscriptionID])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.SourceSubscriptionID)); } // SourceDCName if (string.IsNullOrEmpty(parameters[Constants.Parameters.SourceDCName])) { throw new ValidationException(string.Format(StringResources.EmptyOrNullParameter, Constants.Parameters.SourceDCName)); } #endregion #region Validate parameter's value // Validate PublishSettingsFilePath if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath) && !File.Exists(parameters[Constants.Parameters.SourcePublishSettingsFilePath])) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.SourcePublishSettingsFilePath), new FileNotFoundException(StringResources.PublishSettingsFilePathParamException)); } // Validate ExportMetadataFolderPath string folderPath = parameters[Constants.Parameters.ExportMetadataFolderPath]; if (!Directory.Exists(parameters[Constants.Parameters.ExportMetadataFolderPath])) { throw new ValidationException(string.Format(StringResources.InvalidParameterValue, Constants.Parameters.ExportMetadataFolderPath), new DirectoryNotFoundException(StringResources.ExportMetadataFolderPathParamException)); } int retryCount; Double minBackOff; Double maxBackOff; Double deltaBackOff; bool generateMapperXmlValue; if (!parameters.Keys.Contains(Constants.Parameters.RetryCount)) { retryCount = Int32.Parse(Constants.RetryCountDefault); } else { Int32.TryParse(parameters[Constants.Parameters.RetryCount], out retryCount); } if (!parameters.Keys.Contains(Constants.Parameters.MinBackoff)) { minBackOff = Double.Parse(Constants.MinBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.MinBackoff], out minBackOff); } if (!parameters.Keys.Contains(Constants.Parameters.MaxBackoff)) { maxBackOff = Double.Parse(Constants.MaxBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.MaxBackoff], out maxBackOff); } if (!parameters.Keys.Contains(Constants.Parameters.DeltaBackoff)) { deltaBackOff = Double.Parse(Constants.DeltaBackoffDefault); } else { Double.TryParse(parameters[Constants.Parameters.DeltaBackoff], out deltaBackOff); } if (!parameters.Keys.Contains(Constants.Parameters.GenerateMapperXml)) { generateMapperXmlValue = false; } else { bool.TryParse(parameters[Constants.Parameters.GenerateMapperXml], out generateMapperXmlValue); } // Validate SourceSubscriptionID PublishSettings publishSettingsFile = null; PublishSetting subscription = null; if (parameters.ContainsKey(Constants.Parameters.SourcePublishSettingsFilePath)) { try { var fileContents = File.ReadAllText(parameters[Constants.Parameters.SourcePublishSettingsFilePath]); publishSettingsFile = new PublishSettings(fileContents); } catch (Exception xmlEx) { throw new ValidationException(string.Format(StringResources.XMLParsingException + " =>" + xmlEx.Message, parameters[Constants.Parameters.SourcePublishSettingsFilePath])); } // Check whether subscriptionId exists in publish settings file subscription = publishSettingsFile.Subscriptions.FirstOrDefault(a => string.Compare(a.Id, parameters[Constants.Parameters.SourceSubscriptionID], StringComparison.InvariantCultureIgnoreCase) == 0); if (subscription == null) { throw new ValidationException(string.Format(StringResources.SubscriptionIdParamException, parameters[Constants.Parameters.SourceSubscriptionID], parameters[Constants.Parameters.SourcePublishSettingsFilePath])); } } else { string thumbprint = parameters[Constants.Parameters.SourceCertificateThumbprint]; X509Certificate2 certificate = GetStoreCertificate(thumbprint); if (!certificate.HasPrivateKey) { throw new ValidationException(string.Format( StringResources.MissingPrivateKeyInCertificate, StringResources.Source, thumbprint)); } var sourceCredentials = new CertificateCloudCredentials(parameters[Constants.Parameters.SourceSubscriptionID], certificate); string sourceSubscriptionName = null; using (var client = new ManagementClient(sourceCredentials)) { BaseParameters baseParams = new BaseParameters() { RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff) }; SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), baseParams, ResourceType.None); sourceSubscriptionName = subscriptionResponse.SubscriptionName; } subscription = new PublishSetting() { Id = parameters[Constants.Parameters.SourceSubscriptionID], Name = sourceSubscriptionName, ServiceUrl = new Uri(Constants.ServiceManagementUrlValue), Credentials = sourceCredentials }; } List<string> locations = ExportDataCenterLocations(subscription.Credentials, retryCount, minBackOff, maxBackOff, deltaBackOff); // Check whether SourceDc name exists in subscription bool sourceLocationNamePresent = locations.Any((l => string.Compare(l, parameters[Constants.Parameters.SourceDCName], StringComparison.CurrentCultureIgnoreCase) == 0)); if (!sourceLocationNamePresent) { throw new ValidationException(string.Format(StringResources.DCParamException, parameters[Constants.Parameters.SourceDCName])); } Logger.Info(methodName, ProgressResources.ParametersValidationCompleted); #endregion // Stores validated parameters in class. ExportParameters exportParams = new ExportParameters() { SourceDCName = parameters[Constants.Parameters.SourceDCName], ExportMetadataFolderPath = Path.Combine(parameters[Constants.Parameters.ExportMetadataFolderPath], string.Format(Constants.MetadataFileName, parameters[Constants.Parameters.SourceDCName], DateTime.Now.ToString(Constants.ExportMetadataFileNameFormat))), SourceSubscriptionSettings = subscription, RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff), GenerateMapperXml = generateMapperXmlValue, DestinationPrefixName = parameters.Keys.Contains(Constants.Parameters.DestinationPrefixName) ? parameters[Constants.Parameters.DestinationPrefixName].ToLower() : Constants.DestinationPrefixValue, }; return exportParams; }
private static void AssociateReservedIP(ManagementClient managementClient, string usWestLocStr, string location, StorageManagementClient storageClient, string storageAccountName, ref bool storageAccountCreated, ComputeManagementClient computeClient, string serviceName, string deploymentName, string reserveIpName, NetworkTestBase _testFixture, ref bool hostedServiceCreated, ref bool reserveIpCreated) { if (managementClient.Locations.List().Any( c => string.Equals(c.Name, usWestLocStr, StringComparison.OrdinalIgnoreCase))) { location = usWestLocStr; } CreateStorageAccount(location, storageClient, storageAccountName, out storageAccountCreated); CreateHostedService(location, computeClient, serviceName, out hostedServiceCreated); CreatePaaSDeployment(storageAccountName, computeClient, serviceName, deploymentName); NetworkReservedIPCreateParameters reservedIpCreatePars = new NetworkReservedIPCreateParameters { Name = reserveIpName, Location = "uswest", Label = "SampleReserveIPLabel" }; OperationStatusResponse reserveIpCreate = _testFixture.NetworkClient.ReservedIPs.Create(reservedIpCreatePars); Assert.True(reserveIpCreate.StatusCode == HttpStatusCode.OK); reserveIpCreated = true; NetworkReservedIPGetResponse reserveIpCreationResponse = _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName); Assert.True(reserveIpCreationResponse.StatusCode == HttpStatusCode.OK); NetworkReservedIPMobilityParameters pars = new NetworkReservedIPMobilityParameters { ServiceName = serviceName, DeploymentName = deploymentName }; OperationStatusResponse responseAssociateRip = _testFixture.NetworkClient.ReservedIPs.Associate(reserveIpName, pars); Assert.True(responseAssociateRip.StatusCode == HttpStatusCode.OK); NetworkReservedIPGetResponse receivedReservedIpFromRdfe = _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName); Assert.True(receivedReservedIpFromRdfe.StatusCode == HttpStatusCode.OK); Assert.True(serviceName == receivedReservedIpFromRdfe.ServiceName); Assert.True(receivedReservedIpFromRdfe.InUse == true); Assert.True(deploymentName == receivedReservedIpFromRdfe.DeploymentName); }
public StoreClient( AzureSubscription subscription, ComputeManagementClient compute, StoreManagementClient store, MarketplaceClient marketplace, ManagementClient management) { this.subscriptionId = subscription.Id.ToString(); computeClient = compute; storeClient = store; MarketplaceClient = marketplace; managementClient = management; }
/// <summary> /// Checks if destination subscription has capacity to deploy resources. /// </summary> private void ValidateSubscriptionCapacity() { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); var dataCenter = destSubscriptionMetadata.DataCenters.FirstOrDefault(); using (var client = new ManagementClient(importParameters.DestinationSubscriptionSettings.Credentials)) { SubscriptionGetResponse subscriptionResponse = Retry.RetryOperation(() => client.Subscriptions.Get(), (BaseParameters)importParameters, ResourceType.None); // Checks capacity for services. if ((subscriptionResponse.MaximumHostedServices - subscriptionResponse.CurrentHostedServices) < dataCenter.CloudServices.Where(service => service.IsImported != true).Count()) { throw (new ValidationException(StringResources.InsufficientCloudServices)); } // Checks capacity for storage accounts. if ((subscriptionResponse.MaximumStorageAccounts - subscriptionResponse.CurrentStorageAccounts) < dataCenter.StorageAccounts.Where(storage => storage.IsImported != true).Count()) { throw (new ValidationException(StringResources.InsufficientStorage)); } if (dataCenter.NetworkConfiguration != null && dataCenter.NetworkConfiguration.IsImported == false && dataCenter.NetworkConfiguration.VirtualNetworkConfiguration != null) { // Checks capacity for VirtualNetworkSites. if (dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.VirtualNetworkSites != null && (subscriptionResponse.MaximumVirtualNetworkSites - subscriptionResponse.CurrentVirtualNetworkSites) < dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.VirtualNetworkSites.Count()) { throw (new ValidationException(StringResources.InsufficientVirtualNetwork)); } // Checks capacity for Dns. if (dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.Dns != null && dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.Dns.DnsServers != null && (subscriptionResponse.MaximumDnsServers - subscriptionResponse.CurrentDnsServers) < dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.Dns.DnsServers.Count()) { throw (new ValidationException(StringResources.InsufficientDnsServers)); } // Checks capacity for LocalNetworkSites. if (dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.LocalNetworkSites != null && (subscriptionResponse.MaximumLocalNetworkSites - subscriptionResponse.CurrentLocalNetworkSites) < dataCenter.NetworkConfiguration.VirtualNetworkConfiguration.LocalNetworkSites.Count()) { throw (new ValidationException(StringResources.InsufficientLocalNetwork)); } } List<string> roleSizes = (from service in dataCenter.CloudServices where service.DeploymentDetails != null from virtualMachine in service.DeploymentDetails.VirtualMachines where virtualMachine.IsImported != true select virtualMachine.VirtualMachineDetails.RoleSize).ToList(); Dictionary<string, string> roleSizeMaster = GetRoleSizes(importParameters.DestinationSubscriptionSettings.Id, importParameters.DestinationSubscriptionSettings.Credentials.ManagementCertificate); int totalCoreCount = 0; foreach (string rolesize in roleSizes) { string cores; if (!roleSizeMaster.TryGetValue(rolesize, out cores)) { cores = "0"; } totalCoreCount += Convert.ToInt32(cores); } // Checks capacity for Vm cores. if ((subscriptionResponse.MaximumCoreCount - subscriptionResponse.CurrentCoreCount) < totalCoreCount) { throw (new ValidationException(StringResources.InsufficientCores)); } } Logger.Info(methodName, ProgressResources.ExecutionCompleted); }