public LogAnalyticsConnection(Instance instance) { _instance = instance ?? throw new ArgumentNullException(nameof(instance)); _config = _instance.Config; _arm = new AzureResourceManager(_config); _laArm = new AzureResourceManager(_config); }
protected async Task GetSubscriptionAsync( CancellationToken cancellationToken = default ) { // Initialization of MicrosoftGraphServiceClient var microsoftGraphTokenCredentials = _authenticationManager .GetMicrosoftGraphDelegatingTokenCredentials(); _applicationsManager = new ApplicationsManager( _authConf.TenantId, microsoftGraphTokenCredentials, cancellationToken ); await SetOwnerAsync(cancellationToken); // Initialization of AzureResourceManager var azureCredentials = _authenticationManager .GetDelegatingAzureCredentials(); _azureResourceManager = new AzureResourceManager(azureCredentials); // Select subscription to use. var subscriptionsList = _azureResourceManager.GetSubscriptions(); _subscription = _configurationProvider.GetSubscription(subscriptionsList); _azureResourceManager.Init(_subscription); }
public async Task LoginHandler() { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Login") .SetMessage("Please wait while logging in...") .SetCancelable(false); AlertDialog dialog = null; RunOnUiThread(() => { dialog = alertBuilder.Show(); }); try { azureResourceManager = await AuthenticationManager.Authenticate(platformParam); } catch (Exception e) { } finally { if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (alertBuilder != null) { alertBuilder.Dispose(); } } }
public void AzureClientCertificateLocalFile() { TestUtilities utils = DefaultUtilities(); ConfigurationOptions config = utils.ConfigurationOptions; utils.ConfigurationOptions.Validate(); DeleteTokenCache(); ProcessOutput results = utils.ExecuteTest((config) => { AzureResourceManager arm = new AzureResourceManager(config); string certFile = $"{TestUtilities.TempDir}\\{config.AzureClientSecret}.pfx"; new CertificateUtilities().SaveCertificateToFile(_appCertificate, certFile); //config.AzureClientId = ""; config.AzureClientCertificate = certFile; config.AzureKeyVault = ""; config.AzureClientSecret = ""; Assert.IsTrue(config.IsClientIdConfigured(), "test configuration invalid"); return(config.ValidateAad()); }, utils.Collector.Config); Assert.IsTrue(results.ExitBool); Assert.IsTrue(!results.HasErrors(), results.ToString()); }
public async Task TestStuckGenericResourcesCheckExistence() { AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(@"FILL THIS"); var subscriptionId = "FILL THIS"; AzureResourceManager rm = new AzureResourceManager(credentials, subscriptionId); var resourceGroupName = "temp1234"; await rm.StartDeploymentAsync(resourceGroupName, "West US", "tempDeploy", "azuredeploy.json", String.Empty); await rm.WaitForComputeResourceDeploymentAsync(resourceGroupName, "SimpleWinVM", "virtualMachines"); }
private async Task <ServiceResponse <DatabaseInstanceInfo> > GetDatabasesForServerFromService( IAzureResourceManagementSession session, IAzureSqlServerResource azureSqlServer, string serverName, CancellationToken cancellationToken, CancellationToken internalCancellationToken) { try { if (cancellationToken.IsCancellationRequested) { return(new ServiceResponse <DatabaseInstanceInfo>()); } ServerInstanceInfo serverInstanceInfo = new ServerInstanceInfo(ServerDefinition) { Name = azureSqlServer.Name, FullyQualifiedDomainName = azureSqlServer.FullyQualifiedDomainName, AdministratorLogin = azureSqlServer.AdministratorLogin }; OnDatabaseFound(new DatabaseInstanceInfo(serverInstanceInfo)); IEnumerable <IAzureResource> databases = await AzureResourceManager.GetAzureDatabasesAsync( session, azureSqlServer.ResourceGroupName, azureSqlServer.Name); if (cancellationToken.IsCancellationRequested) { return(new ServiceResponse <DatabaseInstanceInfo>()); } else { IEnumerable <DatabaseInstanceInfo> data = databases.Select(x => ConvertToModel(serverInstanceInfo, x)); ServiceResponse <DatabaseInstanceInfo> result = new ServiceResponse <DatabaseInstanceInfo>(data); foreach (var databaseInstance in result.Data) { if (cancellationToken.IsCancellationRequested) { break; } OnDatabaseFound(databaseInstance); } return(result); } } catch (Exception ex) { return(new ServiceResponse <DatabaseInstanceInfo>(ex)); } }
public void AzureMsalDeviceAuthTest() { ProcessOutput results = DefaultUtilities().ExecuteTest(() => { AzureResourceManager arm = new AzureResourceManager(); AzureResourceManager.MsalMessage += AzureResourceManager_MsalMessage; AzureResourceManager.MsalDeviceCode += AzureResourceManager_MsalDeviceCode; bool result = arm.CreatePublicClient(true, true); AzureResourceManager.MsalMessage -= AzureResourceManager_MsalMessage; AzureResourceManager.MsalDeviceCode -= AzureResourceManager_MsalDeviceCode; return(result); }); Assert.IsFalse(results.HasErrors(), results.ToString()); }
public async Task <ServiceResponse <ServerInstanceInfo> > GetServerInstancesAsync() { ServiceResponse <ServerInstanceInfo> result = new ServiceResponse <ServerInstanceInfo>(); List <ServerInstanceInfo> serverInstances = new List <ServerInstanceInfo>(); if (AccountManager != null && AzureAccountManager != null && AzureResourceManager != null) { try { IEnumerable <IAzureUserAccountSubscriptionContext> subscriptions = await AzureAccountManager.GetSelectedSubscriptionsAsync(); if (subscriptions != null) { foreach (IAzureUserAccountSubscriptionContext subscription in subscriptions) { using (IAzureResourceManagementSession session = await AzureResourceManager.CreateSessionAsync(subscription)) { IEnumerable <IAzureSqlServerResource> azureResources = await AzureResourceManager.GetSqlServerAzureResourcesAsync(session); serverInstances.AddRange( azureResources.Select(x => new ServerInstanceInfo(ServerDefinition) { Name = x.Name, FullyQualifiedDomainName = x.FullyQualifiedDomainName, AdministratorLogin = x.AdministratorLogin })); } } } result = new ServiceResponse <ServerInstanceInfo>(serverInstances); } catch (Exception ex) { result = new ServiceResponse <ServerInstanceInfo>(serverInstances, new List <Exception>() { ex }); } } return(result); }
private TestUtilities DefaultUtilities() { TestUtilities utils = new TestUtilities(); CertificateUtilities certificateUtilities = new CertificateUtilities(); ConfigurationOptions config = utils.Collector.Config; // verify test credentials work AzureResourceManager arm = new AzureResourceManager(config); _appCertificate = certificateUtilities.GetClientCertificate(TestUtilities.TestProperties.AzureClientCertificate); //_appCertificate = new X509Certificate2(Convert.FromBase64String(TestUtilities.TestProperties.AzureClientCertificate), // TestUtilities.TestProperties.adminPassword, // X509KeyStorageFlags.Exportable); Assert.IsNotNull(_appCertificate); _clientCertificate = certificateUtilities.GetClientCertificate(TestUtilities.TestProperties.testAzClientCertificate); //_clientCertificate = new X509Certificate2(Convert.FromBase64String(TestUtilities.TestProperties.testAzClientCertificate), // TestUtilities.TestProperties.adminPassword, // X509KeyStorageFlags.Exportable); Assert.IsNotNull(_clientCertificate); config.AzureResourceGroup = TestUtilities.TestProperties.AzureResourceGroup; config.AzureResourceGroupLocation = TestUtilities.TestProperties.AzureResourceGroupLocation; config.AzureSubscriptionId = TestUtilities.TestProperties.AzureSubscriptionId; config.AzureTenantId = TestUtilities.TestProperties.AzureTenantId; // config.AzureClientSecret = TestUtilities.TestProperties.AzureClientSecret; config.AzureClientId = TestUtilities.TestProperties.testAzClientId; config.AzureClientCertificate = TestUtilities.TestProperties.testAzClientCertificate; arm.Authenticate(true); config.SasKey = TestUtilities.TestProperties.SasKey; config.CacheLocation = TestUtilities.TempDir; config.StartTimeStamp = DateTime.MinValue.ToString("o"); config.EndTimeStamp = DateTime.Now.ToString("o"); config.AzureClientId = TestUtilities.TestProperties.AzureClientId; config.AzureClientCertificate = TestUtilities.TestProperties.AzureClientCertificate; config.AzureClientSecret = TestUtilities.TestProperties.AzureClientSecret; config.AzureKeyVault = TestUtilities.TestProperties.AzureKeyVault; config.List = true; config.GatherType = FileTypesEnum.trace.ToString(); return(utils); }
public void AzureClientCertificateKeyVaultUserManagedIdentity() { TestUtilities utils = DefaultUtilities(); ConfigurationOptions config = utils.ConfigurationOptions; utils.ConfigurationOptions.Validate(); DeleteTokenCache(); ProcessOutput results = utils.ExecuteTest((config) => { //config.AzureClientId = ""; Assert.IsTrue(config.IsClientIdConfigured(), "test configuration invalid"); AzureResourceManager arm = new AzureResourceManager(config); Assert.IsTrue(arm.ClientIdentity.IsUserManagedIdentity, "arm.IsUserManagedIdentity not detected. test from azure vm with user managed identity enabled."); return(config.ValidateAad()); }, utils.Collector.Config); Assert.IsTrue(results.ExitBool); Assert.IsTrue(!results.HasErrors(), results.ToString()); }
/// <summary> /// Returns a list of Azure sql databases for given subscription /// </summary> private async Task <ServiceResponse <DatabaseInstanceInfo> > GetDatabaseForSubscriptionFromServiceAsync( IAzureUserAccountSubscriptionContext input, string serverName, CancellationToken cancellationToken, CancellationToken internalCancellationToken) { ServiceResponse <DatabaseInstanceInfo> result = null; try { if (!cancellationToken.IsCancellationRequested && !internalCancellationToken.IsCancellationRequested) { using (IAzureResourceManagementSession session = await AzureResourceManager.CreateSessionAsync(input)) { //find the server matches with the given servername which should be only one bool shouldFilter = !string.IsNullOrEmpty(serverName); IEnumerable <IAzureSqlServerResource> sqlAzureServers = await AzureResourceManager.GetSqlServerAzureResourcesAsync(session); IEnumerable <IAzureSqlServerResource> filteredServers = !shouldFilter ? sqlAzureServers : sqlAzureServers.Where(x => x.FullyQualifiedDomainName != null && x.FullyQualifiedDomainName.Equals(serverName, StringComparison.OrdinalIgnoreCase)); IList <IAzureSqlServerResource> filteredServersList = filteredServers.ToList(); result = await GetDatabasesForSubscriptionServersAsync(session, filteredServersList.ToList(), cancellationToken); //Set response Found to true to notify the other tasks to cancel if (shouldFilter && filteredServersList.Any()) { result.Found = true; } } } } catch (Exception ex) { result = new ServiceResponse <DatabaseInstanceInfo>(ex); } return(result ?? new ServiceResponse <DatabaseInstanceInfo>()); }
public KustoEndpoint(ConfigurationOptions config) { _config = config ?? throw new ArgumentNullException(nameof(config)); _arm = new AzureResourceManager(_config); if (!_config.IsKustoConfigured()) { string errMessage = "kusto not configured"; Log.Error(errMessage); throw new ArgumentNullException(errMessage); } DeleteSourceOnSuccess = !_config.KustoUseBlobAsSource; if (Regex.IsMatch(_config.KustoCluster, Constants.KustoUrlPattern)) { Match matches = Regex.Match(_config.KustoCluster, Constants.KustoUrlPattern); string domainName = matches.Groups["domainName"].Value; DatabaseName = matches.Groups["databaseName"].Value; TableName = _config.KustoTable; string ingestPrefix = matches.Groups["ingest"].Value; ClusterName = matches.Groups["clusterName"].Value; string location = matches.Groups["location"].Value; HostName = $"{ClusterName}.{location}.{domainName}"; ManagementUrl = $"https://{HostName}"; ClusterIngestUrl = $"https://{ingestPrefix}{ClusterName}.{location}.{domainName}"; RestMgmtUri = $"{ClusterIngestUrl}/v1/rest/mgmt"; RestQueryUri = $"{ManagementUrl}/v1/rest/query"; } else { string errMessage = $"invalid kusto url."; Log.Error(errMessage); throw new ArgumentException(errMessage); } }
static void DoMain(string[] args) { bool showHelp = false, verbose = false; string subscriptionId = null, resourceGroupName = null, vmIPAddress = null, vmSize = "Standard_F1S"; ushort localPort = 50000, remotePort = 3389; var p = new OptionSet { { "s|subscriptionId=", "Subscription id, in which the VM is located.", v => { subscriptionId = v; } }, { "r|resgroup=", "Resource Group name or id, where the VM is located.", v => { resourceGroupName = v; } }, { "i|vmip=", "Virtual Machine IP address.", v => { vmIPAddress = v; } }, { "l|localport=", "Port number of the local machine used by the SSH tunnel (default 50000).", v => { localPort = ushort.Parse(v); } }, { "p|remoteport=", "Port number of the remote machine (default 3389 - RDP).", v => { remotePort = ushort.Parse(v); } }, { "vmsize=", "The size of the Virtual Machine to be created (default Standard_F1S)", v => { vmSize = v; } }, { "v|verbose", "Outputs all requests to Azure.", v => verbose = v != null }, { "h|help", "Show this message and exit", v => showHelp = v != null }, { "?", "Show this message and exit", v => showHelp = v != null } }; try { p.Parse(args); } catch (OptionException ex) { Console.Error.Write("ERROR: invalid argument"); Console.Error.WriteLine(ex.Message); Console.Error.WriteLine(); showHelp = true; } catch (FormatException) { Console.Error.WriteLine("ERROR: invalid number in one of the constraints"); Console.Error.WriteLine(); showHelp = true; } catch (OverflowException) { Console.Error.WriteLine("ERROR: invalid port number"); Console.Error.WriteLine(); showHelp = true; } Guid g; if (!showHelp && !Guid.TryParseExact(subscriptionId, "d", out g)) { Console.Error.WriteLine("ERROR: subscription id was not provided or is invalid"); Console.Error.WriteLine(); showHelp = true; } if (showHelp) { ShowHelp(p); return; } SetConsoleCtrlCHook(); try { var resourceManager = new AzureResourceManager(subscriptionId, verbose); resourceManager.AuthenticateWithPrompt().Wait(); var targetVM = new AzureVMLocalizer(resourceManager); Console.WriteLine("---------------------------------------------"); Console.WriteLine(" Gathering information about the target VM"); Console.WriteLine("---------------------------------------------"); Console.WriteLine(); targetVM.LocalizeVMAsync(resourceGroupName, vmIPAddress, appCancellationToken).Wait(); Trace.TraceInformation($"The target VM IP: {targetVM.TargetIPAddress}, Vnet: {Path.GetFileName(targetVM.VirtualNetworkId)}, " + $"Subnet: {Path.GetFileName(targetVM.SubnetId)}, RG: {targetVM.ResourceGroupName}"); using (var azureJumpHost = new AzureJumpHost(resourceManager, targetVM)) { using (var openSSHWrapper = new OpenSSHWrapper(SupportFiles.SupportFileDir, RootUsername)) { if (!openSSHWrapper.IsKeyFileLoaded) { openSSHWrapper.GenerateKeyFileInUserProfile(); } Console.WriteLine("-------------------------------------------"); Console.WriteLine(" Provisioning VM with Public IP in Azure"); Console.WriteLine("-------------------------------------------"); Console.WriteLine(); azureJumpHost.DeployAndStartAsync(RootUsername, openSSHWrapper.GetPublicKey(), vmSize, appCancellationToken).Wait(); var jumpHostPublicIPAddress = azureJumpHost.GetPublicIPAddressAsync(appCancellationToken).Result; openSSHWrapper.StartOpenSSHSession(new OpenSSHWrapper.SSHSessionInfo { LocalPort = localPort, TargetPort = remotePort, TargetVMIPAddress = targetVM.TargetIPAddress, JumpHostPublicIPAddress = jumpHostPublicIPAddress }); Console.WriteLine(); Console.WriteLine("---------------------------------------"); Console.WriteLine(" SSH tunnel to the target VM is open"); Console.WriteLine("---------------------------------------"); Console.WriteLine(); Console.WriteLine(" Local endpoint : localhost:{0}", localPort); Console.WriteLine(" Target VM endpoint : {0}:{1}", targetVM.TargetIPAddress, remotePort); Console.WriteLine("SSH jump host address : {0}", jumpHostPublicIPAddress); Console.WriteLine(); Console.WriteLine("Press Ctrl+C to end the session and remove all the resources."); if (remotePort == 3389) // for RDP we will start mstsc { Process.Start("mstsc", $"/v:localhost:{localPort}"); } while (!appCancellationToken.IsCancellationRequested) { if (!openSSHWrapper.IsSSHSessionActive) { Console.WriteLine("ERROR: SSH session ended unexpectedly. Use -v option to enable SSH process output."); break; } Thread.Sleep(TimeSpan.FromSeconds(5)); } } } } catch (AggregateException ex) { Trace.TraceError(ex.ToString()); Console.Write("ERROR: "); ex = ex.Flatten(); if (ex.InnerExceptions.Count == 1) { Console.WriteLine($"[{ex.InnerException.GetType().Name}] {ex.InnerException.Message}"); } else { Console.WriteLine(); foreach (var inex in ex.InnerExceptions) { Console.WriteLine($"- [{inex.GetType().Name}] {inex.Message}"); } } } catch (AzureException ex) { Trace.TraceError(ex.ToString()); Console.WriteLine($"ERROR: error while performing action in Azure. Details: {ex.Message}."); Console.WriteLine("If the error persists, you may turn detailed logging with -v switch to learn more."); } catch (Exception ex) { Trace.TraceError(ex.ToString()); Console.WriteLine($"ERROR: [{ex.GetType().Name}] {ex.Message}."); } }
public async Task InitializeResourceGroupSelectionAsync( CancellationToken cancellationToken = default ) { _azureResourceManager = new AzureResourceManager(_azureCredentials); // Select subscription to use. var subscriptionsList = _azureResourceManager.GetSubscriptions(); _subscription = _configurationProvider.SelectSubscription(subscriptionsList); _azureResourceManager.Init(_subscription); // Select existing ResourceGroup or create a new one. var useExisting = _configurationProvider.CheckIfUseExistingResourceGroup(); if (useExisting) { var resourceGroups = _azureResourceManager.GetResourceGroups(); _resourceGroup = _configurationProvider.SelectExistingResourceGroup(resourceGroups); } else { var region = _configurationProvider .SelectResourceGroupRegion( AzureResourceManager.FunctionalRegions ); bool checkIfResourceGroupExists(string _resourceGroupName) { var _resourceGroupExists = _azureResourceManager .CheckIfResourceGroupExistsAsync( _resourceGroupName, cancellationToken ) .Result; return(_resourceGroupExists); } string defaultResourceGroupName = null; if (!checkIfResourceGroupExists(_applicationName)) { defaultResourceGroupName = _applicationName; } var newResourceGroupName = _configurationProvider .SelectResourceGroupName( checkIfResourceGroupExists, defaultResourceGroupName ); _resourceGroup = await _azureResourceManager .CreateResourceGroupAsync( region, newResourceGroupName, _defaultTagsDict, cancellationToken ); } }
/// <summary> /// Creates a virtual machine in Azure. /// Creates all the required resources before creating VM. /// </summary> /// <param name="subscriptionId">Subscription Id</param> /// <param name="credentialName">Internet name/address used to identify entry in Credential Manager</param> /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param> /// <param name="customerTenantId">Id or Domain of the customer Azure tenant</param> private static void CreateAzureVirtualMachine(string appId, string credentialName, string customerTenantId, string subscriptionId) { // Get Azure Authentication Token string azureToken = Reseller.GetAzureAuthTokenForCustomerTenant(appId, credentialName, customerTenantId); // Correlation Id to be used for this scenaario var correlationId = Guid.NewGuid().ToString(); var resourceGroupName = Guid.NewGuid().ToString(); // Appending suffix to resource group name to build names of other resources // Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. // So removing hyphen and truncating. var storageAccountName = String.Format("{0}sa", resourceGroupName.Replace("-", "").Remove(20)); var networkSecurityGroupName = String.Format("{0}_nsg", resourceGroupName); var networkSecurityGroupId = String.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/networkSecurityGroups/{2}", subscriptionId, resourceGroupName, networkSecurityGroupName); var virtualNetworkName = String.Format("{0}_vn", resourceGroupName); var subnetName = String.Format("{0}_sn", resourceGroupName); var subNetId = String.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/microsoft.network/virtualNetworks/{2}/subnets/{3}", subscriptionId, resourceGroupName, virtualNetworkName, subnetName); var publicIpName = String.Format("{0}_pip", resourceGroupName); var publicIpId = String.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/publicIPAddresses/{2}", subscriptionId, resourceGroupName, publicIpName); var networkInterfaceName = String.Format("{0}_nic", resourceGroupName); var networkInterfaceId = String.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/networkInterfaces/{2}", subscriptionId, resourceGroupName, networkInterfaceName); var ipName = String.Format("{0}_ip", resourceGroupName); var vitualMachineName = String.Format("{0}_vm", resourceGroupName); // Waiting Time (in seconds) For Resource to be Provisioned var retryAfter = 5; // Retry attempts for resource provisioning errors var retryAttempts = 5; var attempts = 0; // The following resources are to be created in order before creating a virtual machine. // #1 Create Resource Group do { var createResourceGroupResponse = AzureResourceManager.CreateResourceGroup(subscriptionId, resourceGroupName, azureToken, correlationId); if (createResourceGroupResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the resource group to be created, if the request is just Accepted and the creation is still pending. if ((int)(createResourceGroupResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForResourceGroupProvisioning(subscriptionId, resourceGroupName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #2 Create Storage Account // Register the subscription with Storage Resource Provider, for creating Storage Account // Storage Resource Provider const string storageProviderName = "Microsoft.Storage"; AzureResourceManager.RegisterProvider(subscriptionId, storageProviderName, azureToken, correlationId); attempts = 0; do { var storageAccountResponse = AzureResourceManager.CreateStorageAccount(subscriptionId, resourceGroupName, storageAccountName, azureToken, correlationId); if (storageAccountResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the storage account to be created, if the request is just Accepted and the creation is still pending. if ((int)(storageAccountResponse.StatusCode) == (int)HttpStatusCode.Accepted) { var location = storageAccountResponse.Headers.Get("Location"); retryAfter = Int32.Parse(storageAccountResponse.Headers.Get("Retry-After")); AzureResourceManager.WaitForStorageAccountProvisioning(location, resourceGroupName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // Register the subscription with Network Resource Provider for creating Network Resources - Netowrk Securtiy Group, Virtual Network, Subnet, Public IP and Network Interface // Network Resource Provider const string networkProviderName = "Microsoft.Network"; AzureResourceManager.RegisterProvider(subscriptionId, networkProviderName, azureToken, correlationId); // #3 Create Network Security Group attempts = 0; do { var networkSecurityGroupResponse = AzureResourceManager.CreateNetworkSecurityGroup(subscriptionId, resourceGroupName, networkSecurityGroupName, azureToken, correlationId); if (networkSecurityGroupResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the network security group to be created, if the request is just Accepted and the creation is still pending. if ((int)(networkSecurityGroupResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForNetworkSecurityGroupProvisioning(subscriptionId, resourceGroupName, networkSecurityGroupName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #4 Create Virtual Network attempts = 0; do { var virtualNetworkResponse = AzureResourceManager.CreateVirtualNetwork(subscriptionId, resourceGroupName, virtualNetworkName, azureToken, correlationId); if (virtualNetworkResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the virtual network to be created, if the request is just Accepted and the creation is still pending. if ((int)(virtualNetworkResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForVirtualNetworkProvisioning(subscriptionId, resourceGroupName, virtualNetworkName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #5 Create Subnet attempts = 0; do { var subNetResponse = AzureResourceManager.CreateSubNet(subscriptionId, resourceGroupName, virtualNetworkName, networkSecurityGroupId, subnetName, azureToken, correlationId); if (subNetResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the subnet to be created, if the request is just Accepted and the creation is still pending. if ((int)(subNetResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForSubNetProvisioning(subscriptionId, resourceGroupName, virtualNetworkName, subnetName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #6 Create Public IP Address attempts = 0; do { var publicIpResponse = AzureResourceManager.CreatePublicIpAddress(subscriptionId, resourceGroupName, publicIpName, azureToken, correlationId); if (publicIpResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the public IP to be created, if the request is just Accepted and the creation is still pending. if ((int)(publicIpResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForPublicIpProvisioning(subscriptionId, resourceGroupName, publicIpName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #7 Create Network Interface attempts = 0; do { var networkInterfaceResponse = AzureResourceManager.CreateNetworkInterface(subscriptionId, resourceGroupName, networkInterfaceName, networkSecurityGroupId, ipName, publicIpId, subNetId, azureToken, correlationId); if (networkInterfaceResponse == null) { attempts++; } else { attempts = retryAttempts + 1; // Waiting for the network interface to be created, if the request is just Accepted and the creation is still pending. if ((int)(networkInterfaceResponse.StatusCode) == (int)HttpStatusCode.Accepted) { AzureResourceManager.WaitForNetworkInterfaceProvisioning(subscriptionId, resourceGroupName, networkInterfaceName, retryAfter, azureToken, correlationId); } } } while (attempts < retryAttempts); // #8 Create Azure Virtual Machine // Compute Resource Provider const string computeProviderName = "Microsoft.Compute"; AzureResourceManager.RegisterProvider(subscriptionId, computeProviderName, azureToken, correlationId); var virtualMachineResponse = AzureResourceManager.CreateVirtualMachine(subscriptionId, resourceGroupName, networkInterfaceId, storageAccountName, vitualMachineName, azureToken, correlationId); if (virtualMachineResponse == null) { return; } // #9 Create a New User var newUserInfo = User.PopulateUserFromConsole(); var newUser = AzureResourceManager.CreateUser(newUserInfo.displayName, newUserInfo.mailNickname, newUserInfo.userPrincipalName, newUserInfo.password, azureToken, correlationId); // #10 Add user to Owner role // Register the subscription with Authorization Provider const string authorizationProviderName = "Microsoft.Authorization"; var registrationResult = AzureResourceManager.RegisterProvider(subscriptionId, authorizationProviderName, azureToken, correlationId); // Role Id for Role 'Owner' const string roleIdForOwner = "8e3af657-a8ff-443c-a75c-2fe8c4bcb635"; var scope = String.Format("/subscriptions/{0}", subscriptionId); // Assigning 'Owner' role to the new user var roleAssignment = AzureResourceManager.CreateRoleAssignment(azureToken, scope, newUser.objectId, roleIdForOwner, correlationId); }