public async Task <IDeployment> BeginCreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (creatableResourceGroup != null) { await creatableResourceGroup.CreateAsync(cancellationToken); } SetInner(await Manager.Inner.Deployments.BeginCreateOrUpdateAsync(resourceGroupName, Name, createUpdateParamter, cancellationToken)); return(this); }
///GENMHASH:637F0A3522F2C635C23E54FAAD79CBEA:FE111B80F10F1D62FBC7A570DF172CC4 public async Task <Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseImportExportResponse> ExecuteWorkAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (this.storageAccountCreatable != null) { this.storageAccount = await storageAccountCreatable.CreateAsync(cancellationToken) ?? throw new Exception("Failed to create Storage Account"); } if (this.storageAccount != null) { var storageKeys = (await storageAccount.GetKeysAsync(cancellationToken)); if (storageKeys == null || storageKeys.Count == 0) { throw new Exception("Failed to retrieve Storage Account Keys"); } var storageAccountKey = storageKeys[0].Value; this.Inner.StorageUri = $"{this.storageAccount.EndPoints.Primary.Blob}{this.containerName}/{this.fileName}"; this.Inner.StorageKeyType = StorageKeyType.StorageAccessKey; this.Inner.StorageKey = storageAccountKey; // Create the storage account container if one does not exist var sas = $"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={storageAccountKey};EndpointSuffix=core.Windows.Net"; var cloudBlobClient = CloudStorageAccount.Parse(sas).CreateCloudBlobClient(); await cloudBlobClient.GetContainerReference(containerName).CreateIfNotExistsAsync(); } var importExportResponseInner = await this.sqlServerManager.Inner.Databases .ExportAsync(this.sqlDatabase.ResourceGroupName(), this.sqlDatabase.SqlServerName(), this.sqlDatabase.Name(), this.Inner, cancellationToken); return(new SqlDatabaseImportExportResponseImpl(importExportResponseInner)); }
///GENMHASH:359B78C1848B4A526D723F29D8C8C558:149EB760CEBAD953681C8A653E657563 protected async override Task <Models.VirtualNetworkGatewayInner> CreateInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { var tasks = new List <Task>(); VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = EnsureDefaultIPConfig(); if (defaultIPConfig != null && defaultIPConfig.PublicIPAddressId() == null) { // If public ip not specified, then create a default PIP Task pipTask = Task.Run(async() => { var publicIP = await EnsureDefaultPipDefinition().CreateAsync(cancellationToken); defaultIPConfig.WithExistingPublicIPAddress(publicIP); }); tasks.Add(pipTask); } // Determine if default VNet should be created if (defaultIPConfig.SubnetName() == null) { // But if default IP config does not have a subnet specified, then create a VNet Task networkTask = Task.Run(async() => { var network = await creatableNetwork.CreateAsync(cancellationToken); //... and assign the created VNet to the default IP config defaultIPConfig.WithExistingSubnet(network, GATEWAY_SUBNET); }); tasks.Add(networkTask); } await Task.WhenAll(tasks.ToArray()); return(await Manager.Inner.VirtualNetworkGateways.CreateOrUpdateAsync(ResourceGroupName, Name, Inner, cancellationToken)); }
public async new Task <IDeployment> CreateAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true) { if (creatableResourceGroup != null) { await creatableResourceGroup.CreateAsync(cancellationToken); } return(await CreateResourceAsync(cancellationToken)); }
public async Task <IDeployment> BeginCreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (creatableResourceGroup != null) { await creatableResourceGroup.CreateAsync(cancellationToken); } Models.Deployment inner = new Models.Deployment() { Properties = new DeploymentPropertiesInner { Mode = Mode.Value, Template = Template, TemplateLink = TemplateLink, Parameters = Parameters, ParametersLink = ParametersLink } }; SetInner(await Manager.Inner.Deployments.BeginCreateOrUpdateAsync(resourceGroupName, Name, inner.Properties, cancellationToken)); return(this); }
///GENMHASH:7EC7263977FF1ECADB7B046E165FF424:183CE50E3A3AA226A74F1F233B5BE50D internal CaptureSettings WithNewStorageAccountForCapturedData(ICreatable <Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatableStorageAccount, string containerName) { this.EnsureSettings().Destination.StorageAccountResourceId = "temp-id"; this.EnsureSettings().Destination.BlobContainer = containerName; works.Add(async(CancellationToken token) => { var storageAccount = await creatableStorageAccount.CreateAsync(token); this.EnsureSettings().Destination.StorageAccountResourceId = storageAccount.Id; await CreateContainerIfNotExistsAsync(storageAccount, containerName, token); }); return(this); }
/// <summary> /// Invokes CreateAsync(..) on the given creatable. /// </summary> /// <typeparam name="FluentT">type of fluent resource that creatable creates</typeparam> /// <param name="creatable">the creatable</param> /// <param name="progressReport">to report status of the create operation</param> /// <param name="cancellation">the ask cancellation token</param> /// <returns>task representing the CreateAsync invocation</returns> private async Task InvokeCreateIngoreErrorAsync <FluentT>(ICreatable <FluentT> creatable, ResourceCreateProgressReport progressReport, CancellationToken cancellation = default(CancellationToken)) { try { await creatable.CreateAsync(progressReport, cancellation); } catch (Exception ex) { // Ok to catch since any error will be reported to client via progressReport // Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
public void CanCRUDLocks() { using (var context = FluentMockContext.Start(GetType().FullName)) { IAuthorizationManager authorizationManager = TestHelper.CreateAuthorizationManager(); IComputeManager computeManager = TestHelper.CreateComputeManager(); IResourceManager managerResources = computeManager.ResourceManager; INetworkManager networkManager = TestHelper.CreateNetworkManager(); IStorageManager storageManager = TestHelper.CreateStorageManager(); // Prepare a VM string password = SdkContext.RandomResourceName("P@s", 14); string rgName = SdkContext.RandomResourceName("rg", 15); string vmName = SdkContext.RandomResourceName("vm", 15); string storageName = SdkContext.RandomResourceName("st", 15); string diskName = SdkContext.RandomResourceName("dsk", 15); string netName = SdkContext.RandomResourceName("net", 15); Region region = Region.USEast; IResourceGroup resourceGroup = null; IManagementLock lockGroup = null, lockVM = null, lockStorage = null, lockDiskRO = null, lockDiskDel = null, lockSubnet = null; try { resourceGroup = managerResources.ResourceGroups.Define(rgName) .WithRegion(region) .Create(); Assert.NotNull(resourceGroup); ICreatable <INetwork> netDefinition = networkManager.Networks.Define(netName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28"); // Define a VM for testing VM locks ICreatable <IVirtualMachine> vmDefinition = computeManager.VirtualMachines.Define(vmName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithNewPrimaryNetwork(netDefinition) .WithPrimaryPrivateIPAddressDynamic() .WithoutPrimaryPublicIPAddress() .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter) .WithAdminUsername("tester") .WithAdminPassword(password) .WithSize(VirtualMachineSizeTypes.BasicA1); // Define a managed disk for testing locks on that ICreatable <IDisk> diskDefinition = computeManager.Disks.Define(diskName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithData() .WithSizeInGB(100); // Define a storage account for testing locks on that ICreatable <IStorageAccount> storageDefinition = storageManager.StorageAccounts.Define(storageName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup); // Create resources in parallel to save time and money Extensions.Synchronize(() => Task.WhenAll( storageDefinition.CreateAsync(), vmDefinition.CreateAsync(), diskDefinition.CreateAsync())); IVirtualMachine vm = (IVirtualMachine)vmDefinition; IStorageAccount storage = (IStorageAccount)storageDefinition; IDisk disk = (IDisk)diskDefinition; INetwork network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork(); ISubnet subnet = network.Subnets.Values.FirstOrDefault(); // Lock subnet ICreatable <IManagementLock> lockSubnetDef = authorizationManager.ManagementLocks.Define("subnetLock") .WithLockedResource(subnet.Inner.Id) .WithLevel(LockLevel.ReadOnly); // Lock VM ICreatable <IManagementLock> lockVMDef = authorizationManager.ManagementLocks.Define("vmlock") .WithLockedResource(vm) .WithLevel(LockLevel.ReadOnly) .WithNotes("vm readonly lock"); // Lock resource group ICreatable <IManagementLock> lockGroupDef = authorizationManager.ManagementLocks.Define("rglock") .WithLockedResource(resourceGroup.Id) .WithLevel(LockLevel.CanNotDelete); // Lock storage ICreatable <IManagementLock> lockStorageDef = authorizationManager.ManagementLocks.Define("stLock") .WithLockedResource(storage) .WithLevel(LockLevel.CanNotDelete); // Create locks in parallel ICreatedResources <IManagementLock> created = authorizationManager.ManagementLocks.Create(lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef); lockVM = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key)); lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key)); lockGroup = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key)); lockSubnet = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key)); // Lock disk synchronously lockDiskRO = authorizationManager.ManagementLocks.Define("diskLockRO") .WithLockedResource(disk) .WithLevel(LockLevel.ReadOnly) .Create(); lockDiskDel = authorizationManager.ManagementLocks.Define("diskLockDel") .WithLockedResource(disk) .WithLevel(LockLevel.CanNotDelete) .Create(); // Verify VM lock Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(vm.Id).Count()); Assert.NotNull(lockVM); lockVM = authorizationManager.ManagementLocks.GetById(lockVM.Id); Assert.NotNull(lockVM); Assert.Equal(LockLevel.ReadOnly, lockVM.Level); Assert.Equal(vm.Id, lockVM.LockedResourceId, true); // Verify resource group lock Assert.NotNull(lockGroup); lockGroup = authorizationManager.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock"); Assert.NotNull(lockGroup); Assert.Equal(LockLevel.CanNotDelete, lockGroup.Level); Assert.Equal(resourceGroup.Id, lockGroup.LockedResourceId, true); // Verify storage account lock Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(storage.Id).Count()); Assert.NotNull(lockStorage); lockStorage = authorizationManager.ManagementLocks.GetById(lockStorage.Id); Assert.NotNull(lockStorage); Assert.Equal(LockLevel.CanNotDelete, lockStorage.Level); Assert.Equal(storage.Id, lockStorage.LockedResourceId, true); // Verify disk lock Assert.Equal(3, authorizationManager.ManagementLocks.ListForResource(disk.Id).Count()); Assert.NotNull(lockDiskRO); lockDiskRO = authorizationManager.ManagementLocks.GetById(lockDiskRO.Id); Assert.NotNull(lockDiskRO); Assert.Equal(LockLevel.ReadOnly, lockDiskRO.Level); Assert.Equal(disk.Id, lockDiskRO.LockedResourceId, true); Assert.NotNull(lockDiskDel); lockDiskDel = authorizationManager.ManagementLocks.GetById(lockDiskDel.Id); Assert.NotNull(lockDiskDel); Assert.Equal(LockLevel.CanNotDelete, lockDiskDel.Level); Assert.Equal(disk.Id, lockDiskDel.LockedResourceId, true); // Verify subnet lock Assert.Equal(2, authorizationManager.ManagementLocks.ListForResource(network.Id).Count()); lockSubnet = authorizationManager.ManagementLocks.GetById(lockSubnet.Id); Assert.NotNull(lockSubnet); Assert.Equal(LockLevel.ReadOnly, lockSubnet.Level); Assert.Equal(subnet.Inner.Id, lockSubnet.LockedResourceId, true); // Verify lock collection var locksSubscription = authorizationManager.ManagementLocks.List(); var locksGroup = authorizationManager.ManagementLocks.ListByResourceGroup(vm.ResourceGroupName); Assert.NotNull(locksSubscription); Assert.NotNull(locksGroup); int locksAllCount = locksSubscription.Count(); Assert.True(6 <= locksAllCount); int locksGroupCount = locksGroup.Count(); Assert.Equal(6, locksGroup.Count()); } finally { try { if (resourceGroup != null) { if (lockGroup != null) { authorizationManager.ManagementLocks.DeleteById(lockGroup.Id); } if (lockVM != null) { authorizationManager.ManagementLocks.DeleteById(lockVM.Id); } if (lockDiskRO != null) { authorizationManager.ManagementLocks.DeleteById(lockDiskRO.Id); } if (lockDiskDel != null) { authorizationManager.ManagementLocks.DeleteById(lockDiskDel.Id); } if (lockStorage != null) { authorizationManager.ManagementLocks.DeleteById(lockStorage.Id); } if (lockSubnet != null) { authorizationManager.ManagementLocks.DeleteById(lockSubnet.Id); } managerResources.ResourceGroups.BeginDeleteByName(rgName); } } catch { } } } }
/** * Azure sample for applying locks to resources * * Summary ... * * This sample shows examples of management locks usage on various resources. * * Details ... * * 1. Create a number of various resources to apply locks to... * 2. Apply various locks to the resources * 3. Retrieve and show lock information * 4. Remove the locks and clean up */ public static void RunSample(IAzure azure) { string password = SdkContext.RandomResourceName("P@s", 14); string rgName = SdkContext.RandomResourceName("rg", 15); string vmName = SdkContext.RandomResourceName("vm", 15); string storageName = SdkContext.RandomResourceName("st", 15); string diskName = SdkContext.RandomResourceName("dsk", 15); string netName = SdkContext.RandomResourceName("net", 15); Region region = Region.USEast; IResourceGroup resourceGroup = null; IManagementLock lockGroup = null, lockVM = null, lockStorage = null, lockDiskRO = null, lockDiskDel = null, lockSubnet = null; try { //============================================================= // Create a shared resource group for all the resources so they can all be deleted together // resourceGroup = azure.ResourceGroups.Define(rgName) .WithRegion(region) .Create(); Utilities.Log("Created a new resource group - " + resourceGroup.Id); //============================================================ // Create various resources for demonstrating locks // // Define a network to apply a lock to ICreatable <INetwork> netDefinition = azure.Networks.Define(netName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28"); // Define a managed disk for testing locks on that ICreatable <IDisk> diskDefinition = azure.Disks.Define(diskName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithData() .WithSizeInGB(100); // Define a VM to apply a lock to ICreatable <IVirtualMachine> vmDefinition = azure.VirtualMachines.Define(vmName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithNewPrimaryNetwork(netDefinition) .WithPrimaryPrivateIPAddressDynamic() .WithoutPrimaryPublicIPAddress() .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter) .WithAdminUsername("tester") .WithAdminPassword(password) .WithNewDataDisk(diskDefinition, 1, CachingTypes.None) .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4")); // Define a storage account to apply a lock to ICreatable <IStorageAccount> storageDefinition = azure.StorageAccounts.Define(storageName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup); // Create resources in parallel to save time Utilities.Log("Creating the needed resources..."); Task.WaitAll( storageDefinition.CreateAsync(), vmDefinition.CreateAsync()); Utilities.Log("Resources created."); IVirtualMachine vm = (IVirtualMachine)vmDefinition; IStorageAccount storage = (IStorageAccount)storageDefinition; IDisk disk = (IDisk)diskDefinition; INetwork network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork(); ISubnet subnet = network.Subnets.Values.FirstOrDefault(); //============================================================ // Create various locks for the created resources // // Locks can be created serially, and multiple can be applied to the same resource: Utilities.Log("Creating locks sequentially..."); // Apply a ReadOnly lock to the disk lockDiskRO = azure.ManagementLocks.Define("diskLockRO") .WithLockedResource(disk) .WithLevel(LockLevel.ReadOnly) .Create(); // Apply a lock preventing the disk from being deleted lockDiskDel = azure.ManagementLocks.Define("diskLockDel") .WithLockedResource(disk) .WithLevel(LockLevel.CanNotDelete) .Create(); // Locks can also be created in parallel, for better overall performance: Utilities.Log("Creating locks in parallel..."); // Define a subnet lock ICreatable <IManagementLock> lockSubnetDef = azure.ManagementLocks.Define("subnetLock") .WithLockedResource(subnet.Inner.Id) .WithLevel(LockLevel.ReadOnly); // Define a VM lock ICreatable <IManagementLock> lockVMDef = azure.ManagementLocks.Define("vmlock") .WithLockedResource(vm) .WithLevel(LockLevel.ReadOnly) .WithNotes("vm readonly lock"); // Define a resource group lock ICreatable <IManagementLock> lockGroupDef = azure.ManagementLocks.Define("rglock") .WithLockedResource(resourceGroup.Id) .WithLevel(LockLevel.CanNotDelete); // Define a storage lock ICreatable <IManagementLock> lockStorageDef = azure.ManagementLocks.Define("stLock") .WithLockedResource(storage) .WithLevel(LockLevel.CanNotDelete); var created = azure.ManagementLocks.Create( lockVMDef, lockGroupDef, lockStorageDef, lockSubnetDef); lockVM = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key, StringComparison.OrdinalIgnoreCase)); lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key, StringComparison.OrdinalIgnoreCase)); lockGroup = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key, StringComparison.OrdinalIgnoreCase)); lockSubnet = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key, StringComparison.OrdinalIgnoreCase)); Utilities.Log("Locks created."); //============================================================ // Retrieve and show lock information // // Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources) int lockCount = azure.ManagementLocks.ListForResource(vm.Id).Count(); Utilities.Log("Number of locks applied to the virtual machine: " + lockCount); lockCount = azure.ManagementLocks.ListByResourceGroup(resourceGroup.Name).Count(); Utilities.Log("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount); lockCount = azure.ManagementLocks.ListForResource(storage.Id).Count(); Utilities.Log("Number of locks applied to the storage account: " + lockCount); lockCount = azure.ManagementLocks.ListForResource(disk.Id).Count(); Utilities.Log("Number of locks applied to the managed disk: " + lockCount); lockCount = azure.ManagementLocks.ListForResource(network.Id).Count(); Utilities.Log("Number of locks applied to the network (including its subnets): " + lockCount); // Locks can be retrieved using their ID lockVM = azure.ManagementLocks.GetById(lockVM.Id); lockGroup = azure.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock"); lockStorage = azure.ManagementLocks.GetById(lockStorage.Id); lockDiskRO = azure.ManagementLocks.GetById(lockDiskRO.Id); lockDiskDel = azure.ManagementLocks.GetById(lockDiskDel.Id); lockSubnet = azure.ManagementLocks.GetById(lockSubnet.Id); // Show the locks Utilities.Print(lockGroup); Utilities.Print(lockVM); Utilities.Print(lockDiskDel); Utilities.Print(lockDiskRO); Utilities.Print(lockStorage); Utilities.Print(lockSubnet); // List all locks within a subscription var locksSubscription = azure.ManagementLocks.List(); Utilities.Log("Total number of locks within this subscription: " + locksSubscription.Count()); } finally { try { // Clean up (remember to unlock resources before deleting the resource group) azure.ManagementLocks.DeleteByIds( lockGroup.Id, lockVM.Id, lockDiskRO.Id, lockDiskDel.Id, lockStorage.Id, lockSubnet.Id); Utilities.Log("Starting the deletion of the resource group: " + rgName); azure.ResourceGroups.BeginDeleteByName(rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }