public NetworkTestClient() { undoContext = UndoContext.Current; undoContext.Start(4); networkClient = TestBase.GetServiceClient<NetworkManagementClient>(); testOperations = new List<TestOperation>(); }
//这里返回VSUndo是为了使用using调用结束的时候,自动调用dispose方法来关闭undocontext public static VSUndo StartUndo() { undoContext = ApplicationObject.UndoContext; undoContext.Open(Guid.NewGuid().ToString()); return new VSUndo(); }
public void DatabaseActivationTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); // Management Clients var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler); var resClient = Sql2ScenarioHelper.GetResourceClient(handler); // Variables for server creation. string serverName = TestUtilities.GenerateName("csm-sql-activation"); string resGroupName = TestUtilities.GenerateName("csm-rg-activation"); string serverLocation = "Southeast Asia"; string adminLogin = "******"; string adminPass = "******"; string version = "12.0"; // Constants for database creation. var defaultDatabaseSize = 250L * 1024L * 1024L * 1024L; // 250 GB Guid dwSlo = new Guid("4E63CB0E-91B9-46FD-B05C-51FDD2367618 "); // DW100 var defaultCollation = "SQL_Latin1_General_CP1_CI_AS"; var databaseName = TestUtilities.GenerateName("csm-sql-activation-db"); string databaseEdition = "DataWarehouse"; // Create the resource group. resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup() { Location = serverLocation, }); try { ////////////////////////////////////////////////////////////////////// // Create server for test. var createResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLogin = adminLogin, AdministratorLoginPassword = adminPass, Version = version, } }); // Verify the the response from the service contains the right information TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.Created); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass, version, createResponse.Server); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Create database test. // Create only required var createDbResponse = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { MaxSizeBytes = defaultDatabaseSize, Edition = databaseEdition, RequestedServiceObjectiveId = dwSlo, }, }); TestUtilities.ValidateOperationResponse(createDbResponse, HttpStatusCode.Created); VerifyDatabaseInformation(createDbResponse.Database, serverLocation, defaultCollation, databaseEdition, defaultDatabaseSize, dwSlo, dwSlo); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Pause database. var pauseResponse = sqlClient.DatabaseActivation.Pause(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(pauseResponse, HttpStatusCode.OK); VerifyDatabaseInformation(pauseResponse.Database, serverLocation, defaultCollation, databaseEdition, defaultDatabaseSize, dwSlo, dwSlo, "Paused"); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Resume database. var resumeResponse = sqlClient.DatabaseActivation.Resume(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(resumeResponse, HttpStatusCode.OK); VerifyDatabaseInformation(resumeResponse.Database, serverLocation, defaultCollation, databaseEdition, defaultDatabaseSize, dwSlo, dwSlo, "Online"); /////////////////////////////////////////////////////////////////////// } finally { // Clean up the resource group. resClient.ResourceGroups.Delete(resGroupName); } } }
public void ElasticPoolCrud() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); string resPoolName = TestUtilities.GenerateName("csm-sql-respoolcrud"); string resPool2Name = TestUtilities.GenerateName("csm-sql-respoolcrud"); Sql2ScenarioHelper.RunServerTestInEnvironment( handler, "12.0", (sqlClient, resGroupName, server) => { ////////////////////////////////////////////////////////////////////// // Create Elastic Pool Test with all values specified (Default values) var pool1Properties = new ElasticPoolCreateOrUpdateProperties() { Edition = "Standard", Dtu = 200, DatabaseDtuMax = 100, DatabaseDtuMin = 10, StorageMB = 204800 }; var pool1 = sqlClient.ElasticPools.CreateOrUpdate(resGroupName, server.Name, resPoolName, new ElasticPoolCreateOrUpdateParameters() { Location = server.Location, Properties = pool1Properties }); TestUtilities.ValidateOperationResponse(pool1, HttpStatusCode.Created); ValidateElasticPool( pool1.ElasticPool, resPoolName, pool1Properties.Edition, pool1Properties.DatabaseDtuMax, pool1Properties.DatabaseDtuMin, pool1Properties.Dtu, pool1Properties.StorageMB); var pool2Properties = new ElasticPoolCreateOrUpdateProperties() { Edition = "Standard", }; var pool2 = sqlClient.ElasticPools.CreateOrUpdate(resGroupName, server.Name, resPool2Name, new ElasticPoolCreateOrUpdateParameters() { Location = server.Location, Properties = pool2Properties }); TestUtilities.ValidateOperationResponse(pool2, HttpStatusCode.Created); ValidateElasticPool( pool2.ElasticPool, resPool2Name, pool1Properties.Edition, 100, 0, 200, 204800); ////////////////////////////////////////////////////////////////////// // Update Elastic Pool Test pool1Properties.Dtu = 200; pool1Properties.DatabaseDtuMax = 50; pool1Properties.DatabaseDtuMin = 0; var pool3 = sqlClient.ElasticPools.CreateOrUpdate(resGroupName, server.Name, resPoolName, new ElasticPoolCreateOrUpdateParameters() { Location = server.Location, Properties = pool1Properties }); TestUtilities.ValidateOperationResponse(pool3, HttpStatusCode.OK); ValidateElasticPool( pool3.ElasticPool, resPoolName, pool1Properties.Edition, pool1Properties.DatabaseDtuMax, pool1Properties.DatabaseDtuMin, pool1Properties.Dtu, pool1Properties.StorageMB); ////////////////////////////////////////////////////////////////////// // Get Elastic Pool Test. var pool4 = sqlClient.ElasticPools.Get(resGroupName, server.Name, resPoolName); TestUtilities.ValidateOperationResponse(pool4, HttpStatusCode.OK); ValidateElasticPool( pool4.ElasticPool, resPoolName, pool3.ElasticPool.Properties.Edition, pool3.ElasticPool.Properties.DatabaseDtuMax, pool3.ElasticPool.Properties.DatabaseDtuMin, pool3.ElasticPool.Properties.Dtu, pool3.ElasticPool.Properties.StorageMB); ////////////////////////////////////////////////////////////////////// // Get Elastic Pool Test. var pools = sqlClient.ElasticPools.List(resGroupName, server.Name); TestUtilities.ValidateOperationResponse(pools, HttpStatusCode.OK); Assert.Equal(2, pools.ElasticPools.Count); ////////////////////////////////////////////////////////////////////// // Get Elastic Pool Activity Test. var activity = sqlClient.ElasticPools.ListActivity(resGroupName, server.Name, resPoolName); TestUtilities.ValidateOperationResponse(activity, HttpStatusCode.OK); Assert.True(activity.ElasticPoolActivities.Count > 0); ////////////////////////////////////////////////////////////////////// // Delete Elastic Pool Test. var resp = sqlClient.ElasticPools.Delete(resGroupName, server.Name, pool1.ElasticPool.Name); TestUtilities.ValidateOperationResponse(resp, HttpStatusCode.OK); resp = sqlClient.ElasticPools.Delete(resGroupName, server.Name, pool2.ElasticPool.Name); TestUtilities.ValidateOperationResponse(resp, HttpStatusCode.OK); }); } }
public void TransparentDataEncryptionCRUDTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); // Management Clients var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler); var resClient = Sql2ScenarioHelper.GetResourceClient(handler); // Variables for server create string serverName = TestUtilities.GenerateName("csm-sql-transparentdataencryptioncrud"); string resGroupName = TestUtilities.GenerateName("csm-rg-transparentdataencryptioncrud"); string serverLocation = "Japan East"; string adminLogin = "******"; string adminPass = "******"; string version = "12.0"; var defaultDatabaseSize = 1L * 1024L * 1024L * 1024L; // 1 GB Guid dbSloS0 = new Guid("f1173c43-91bd-4aaa-973c-54e79e15235b "); // S0 var defaultCollation = "SQL_Latin1_General_CP1_CI_AS"; var databaseName = TestUtilities.GenerateName("csm-sql-tde-db"); string databaseEdition = "Standard"; // Create the resource group. resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup() { Location = serverLocation, }); try { ////////////////////////////////////////////////////////////////////// // Create server for test. var createResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLogin = adminLogin, AdministratorLoginPassword = adminPass, Version = version, } }); // Verify the the response from the service contains the right information TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.Created); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass, version, createResponse.Server); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Create database test. // Create only required var createDbResponse = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { MaxSizeBytes = defaultDatabaseSize, }, }); TestUtilities.ValidateOperationResponse(createDbResponse, HttpStatusCode.Created); VerifyDatabaseInformation(serverLocation, defaultCollation, databaseEdition, defaultDatabaseSize, dbSloS0, dbSloS0, createDbResponse.Database); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Get transparent data encryption Test // Get single transparent data encryption var getTde = sqlClient.TransparentDataEncryption.Get(resGroupName, serverName, databaseName); // Verify that the Get request contains the right information. TestUtilities.ValidateOperationResponse(getTde, HttpStatusCode.OK); VerifyTransparentDataEncryptionInformation(TransparentDataEncryptionStates.Disabled, getTde.TransparentDataEncryption); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Update Transparent Data Encryption Test var updateResponse = sqlClient.TransparentDataEncryption.CreateOrUpdate(resGroupName, serverName, databaseName, new TransparentDataEncryptionCreateOrUpdateParameters { Properties = new TransparentDataEncryptionCreateOrUpdateProperties() { State = TransparentDataEncryptionStates.Enabled, }, }); /////////////////////////////////////////////////////////////////////// // Get Transparent Data Encryption Activity Test var activities = sqlClient.TransparentDataEncryption.ListActivity(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(activities, HttpStatusCode.OK); Assert.True(activities.TransparentDataEncryptionActivities.Count > 0); var transparentDataEncryptionActivity = activities.TransparentDataEncryptionActivities[0]; VerifyTransparentDataEncryptionActivityInformation(TransparentDataEncryptionActivityStates.Encrypting, transparentDataEncryptionActivity); // Get single transparent data encryption getTde = sqlClient.TransparentDataEncryption.Get(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(updateResponse, HttpStatusCode.OK); VerifyTransparentDataEncryptionInformation(TransparentDataEncryptionStates.Enabled, getTde.TransparentDataEncryption); /////////////////////////////////////////////////////////////////////// } finally { // Clean up the resource group. resClient.ResourceGroups.Delete(resGroupName); } } }
public void DisableProtectionForVMwareVM() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var fabrics = client.Fabrics.List(RequestHeaders); Fabric selectedFabric = null; ProtectionContainer selectedContainer = null; foreach (var fabric in fabrics.Fabrics) { if (fabric.Properties.CustomDetails.InstanceType.Contains("VMware")) { selectedFabric = fabric; } } var containers = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders); foreach (var container in containers.ProtectionContainers) { if (container.Properties.ProtectedItemCount > 0 && container.Properties.Role.Equals("Primary")) { selectedContainer = container; break; } } if (selectedContainer != null) { var protectedItem = client.ReplicationProtectedItem.List( selectedFabric.Name, selectedContainer.Name, RequestHeaders).ReplicationProtectedItems[0]; var response = client.ReplicationProtectedItem.DisableProtection( selectedFabric.Name, selectedContainer.Name, protectedItem.Name, new DisableProtectionInput() { Properties = new DisableProtectionInputProperties() { ProviderSettings = new DisableProtectionProviderSpecificInput() { } } }, RequestHeaders); Assert.NotNull(response); Assert.Equal(OperationStatus.Succeeded, response.Status); } else { throw new System.Exception("No protected item found"); } } }
public void EnableProtectionForVMwareVM() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = this.GetSiteRecoveryClient(this.CustomHttpHandler); string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab"; string vmAccount = "vm"; var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails; Assert.NotNull(vmWareDetails); var runAsAccount = vmWareDetails.RunAsAccounts.First( account => account.AccountName.Equals( vmAccount, StringComparison.InvariantCultureIgnoreCase)); Assert.NotNull(runAsAccount); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectableItemsResponse = client.ProtectableItem.Get( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, vmId, RequestHeaders); Assert.NotNull(protectableItemsResponse); Assert.NotNull(protectableItemsResponse.ProtectableItem); var hikewalrProtectableItem = protectableItemsResponse.ProtectableItem; var vmWareAzureV2Details = hikewalrProtectableItem.Properties.CustomDetails as VMwareVirtualMachineDetails; Assert.NotNull(vmWareAzureV2Details); var policyResponse = client.Policies.List(RequestHeaders); Assert.NotNull(policyResponse); Assert.NotEmpty(policyResponse.Policies); var policy = policyResponse.Policies.First( p => p.Properties.ProviderSpecificDetails.InstanceType == "InMageAzureV2"); Assert.NotNull(policy); Random random = new Random(100); string storageAccountSubscriptionId = "c183865e-6077-46f2-a3b1-deb0f4f4650a"; string storageAccountId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/Default-Storage-WestUS/providers/Microsoft.ClassicStorage/storageAccounts/hikewalrstoragewestus"; var response = client.ReplicationProtectedItem.EnableProtection( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, hikewalrProtectableItem.Name + "-Protected", new EnableProtectionInput { Properties = new EnableProtectionInputProperties { PolicyId = policy.Id, ProtectableItemId = hikewalrProtectableItem.Id, ProviderSpecificDetails = new InMageAzureV2EnableProtectionInput { MultiVmGroupId = Guid.NewGuid().ToString(), MultiVmGroupName = policy.Name + random.Next().ToString(), ProcessServerId = vmWareDetails.ProcessServers[0].Id, RunAsAccountId = runAsAccount.AccountId, StorageAccountId = storageAccountId, StorageSubscriptionId = storageAccountSubscriptionId, MasterTargetId = vmWareDetails.MasterTargetServers[0].Id } } }, RequestHeaders); Assert.NotNull(response); Assert.Equal(OperationStatus.Succeeded, response.Status); var enableResponse = response as ReplicationProtectedItemOperationResponse; Assert.NotNull(enableResponse); Assert.NotNull(enableResponse.ReplicationProtectedItem); Assert.NotNull(enableResponse.ReplicationProtectedItem.Properties); Assert.Equal(enableResponse.ReplicationProtectedItem.Name, hikewalrProtectableItem.Name + "-Protected"); } }
public void ServerAdministratorCRUDTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); Sql2ScenarioHelper.RunServerTestInEnvironment( handler, "12.0", "North Europe", (sqlClient, resGroupName, server) => { string AdministratorDefaultType = "activeDirectory"; string ActiveDirectoryDefaultName = "activeDirectory"; string activeDirectoryServerAdminLogin = "******"; Guid activeDirectoryServerAdminSid = new Guid("4dc34af5-6a71-4838-a983-14cdf8852ff9"); Guid activeDirectoryTenantId = new Guid("A0C03064-E4CB-4AB8-AF32-12203273FF1D"); /////////////////////////////////////////////////////////////////////// // Update Azure SQL Server Active Directory Administrator var createResponse = sqlClient.ServerAdministrators.CreateOrUpdate(resGroupName, server.Name, ActiveDirectoryDefaultName, new ServerAdministratorCreateOrUpdateParameters() { Properties = new ServerAdministratorCreateOrUpdateProperties() { Login = activeDirectoryServerAdminLogin, Sid = activeDirectoryServerAdminSid, AdministratorType = AdministratorDefaultType, TenantId = activeDirectoryTenantId, }, }); TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.OK); VerifyServerAdministratorInformation(activeDirectoryServerAdminLogin, activeDirectoryServerAdminSid, activeDirectoryTenantId, createResponse.ServerAdministrator); // Get single server active directory administrator var getAdminResponse = sqlClient.ServerAdministrators.Get(resGroupName, server.Name, ActiveDirectoryDefaultName); // Verify that the Get request contains the right information. TestUtilities.ValidateOperationResponse(getAdminResponse, HttpStatusCode.OK); VerifyServerAdministratorInformation(activeDirectoryServerAdminLogin, activeDirectoryServerAdminSid, activeDirectoryTenantId, getAdminResponse.Administrator); // Get list Azure SQL Server Active Directory Administrator var getAdminResponseList = sqlClient.ServerAdministrators.List(resGroupName, server.Name); //There should only be one Azure SQL Server Active Directory Administrator Assert.Equal(getAdminResponseList.Administrators.Count, 1); // Verify that the Get request contains the right information. TestUtilities.ValidateOperationResponse(getAdminResponseList, HttpStatusCode.OK); VerifyServerAdministratorInformation(activeDirectoryServerAdminLogin, activeDirectoryServerAdminSid, activeDirectoryTenantId, getAdminResponseList.Administrators[0]); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Delete Azure SQL Server Active Directory Administrator Test var deleteResponse = sqlClient.ServerAdministrators.Delete(resGroupName, server.Name, ActiveDirectoryDefaultName); // Verify that the delete operation works. TestUtilities.ValidateOperationResponse(deleteResponse, HttpStatusCode.NoContent); ///////////////////////////////////////////////////////////////////// // Verify that the Azure SQL Active Directory administrator is deleted. var getNoAdminResponse = sqlClient.ServerAdministrators.List(resGroupName, server.Name); TestUtilities.ValidateOperationResponse(getNoAdminResponse, HttpStatusCode.OK); // There should be no Azure SQL Server Active Directory Administrator after delete Assert.Empty(getNoAdminResponse.Administrators); }); } }
private void RunWebsiteTestScenario(WebsiteTestDelegate testAction, SkuOptions sku = SkuOptions.Shared) { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(4); WebSiteManagementClient webSitesClient = ResourceGroupHelper.GetWebSitesClient(handler); ResourceManagementClient resourcesClient = ResourceGroupHelper.GetResourcesClient(handler); string webSiteName = TestUtilities.GenerateName("csmws"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); string webHostingPlanName = TestUtilities.GenerateName("csmwhp"); string location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); webSitesClient.WebHostingPlans.CreateOrUpdate(resourceGroupName, new WebHostingPlanCreateOrUpdateParameters { WebHostingPlan = new WebHostingPlan { Name = webHostingPlanName, Location = location, Properties = new WebHostingPlanProperties() { Sku = sku } } }); var webSite = webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, webSiteName, null, new WebSiteCreateOrUpdateParameters { WebSite = new WebSiteBase { Name = webSiteName, Location = location, Tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "" } }, Properties = new WebSiteBaseProperties { ServerFarm = webHostingPlanName } } }); Assert.Equal(webSiteName, webSite.WebSite.Name); Assert.Equal(webSite.WebSite.Properties.ServerFarm, webHostingPlanName); Assert.Equal("value1", webSite.WebSite.Tags["tag1"]); Assert.Equal("", webSite.WebSite.Tags["tag2"]); testAction(webSiteName, resourceGroupName, webHostingPlanName, location, webSitesClient, resourcesClient); } }
public void ListBackupsAndScheduledBackupRoundTrip() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); var webSitesClient = GetWebSitesClient(handler); var resourcesClient = GetResourcesClient(handler); string farmName = TestUtilities.GenerateName("csmsf"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); string locationName = "West US"; string siteName = TestUtilities.GenerateName("csmws"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = locationName }); webSitesClient.WebHostingPlans.CreateOrUpdate(resourceGroupName, new WebHostingPlanCreateOrUpdateParameters { WebHostingPlan = new WebHostingPlan { Name = farmName, Location = locationName, Properties = new WebHostingPlanProperties { NumberOfWorkers = 1, WorkerSize = WorkerSizeOptions.Small } } }); webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, siteName, null, new WebSiteCreateOrUpdateParameters() { WebSite = new WebSiteBase() { Name = siteName, Location = locationName, Properties = new WebSiteBaseProperties() { ServerFarm = farmName } } }); var backupResponse = webSitesClient.WebSites.ListBackups(resourceGroupName, siteName, null); Assert.Equal(0, backupResponse.BackupList.Properties.Count); // , "Backup list should be empty" // the following URL just have a proper format, but it is not valid - for an API test it is not needed to be valid, // since we are just testing a roundtrip here string storageUrl = "https://nonexistingusername3567.blob.core.windows.net/backup/?sv=2012-02-12&st=2013-12-05T19%3A30%3A45Z&se=2017-12-04T19%3A30%3A45Z&sr=c&sp=rwdl&sig=3BY5sbzQ2NeKvdaelzxc8inxJgE1mGq2a%2BaqUeFGJYo%3D"; var sr = new BackupRequest() { Enabled = false, BackupSchedule = new BackupSchedule() { FrequencyInterval = 17, FrequencyUnit = FrequencyUnit.Day, KeepAtLeastOneBackup = true, RetentionPeriodInDays = 26, StartTime = DateTime.Now.AddDays(5) }, Name = "abc", StorageAccountUrl = storageUrl }; webSitesClient.WebSites.UpdateBackupConfiguration(resourceGroupName, siteName, null, new BackupRequestEnvelope() { Location = locationName, Request = sr }); var backupConfiguration = webSitesClient.WebSites.GetBackupConfiguration(resourceGroupName, siteName, null); Assert.Equal(sr.Enabled, backupConfiguration.BackupSchedule.Properties.Enabled); Assert.Equal(sr.BackupSchedule.FrequencyInterval, backupConfiguration.BackupSchedule.Properties.BackupSchedule.FrequencyInterval); Assert.Equal(sr.BackupSchedule.FrequencyUnit, backupConfiguration.BackupSchedule.Properties.BackupSchedule.FrequencyUnit); Assert.Equal(sr.BackupSchedule.KeepAtLeastOneBackup, backupConfiguration.BackupSchedule.Properties.BackupSchedule.KeepAtLeastOneBackup); Assert.Equal(sr.Name, backupConfiguration.BackupSchedule.Properties.Name); webSitesClient.WebSites.Delete(resourceGroupName, siteName, null, new WebSiteDeleteParameters() { DeleteAllSlots = true, DeleteMetrics = true }); webSitesClient.WebHostingPlans.Delete(resourceGroupName, farmName); var serverFarmResponse = webSitesClient.WebHostingPlans.List(resourceGroupName); Assert.Equal(0, serverFarmResponse.WebHostingPlans.Count); } }
public void CanCreateMediaServicesAccountSuccessfully() { using (UndoContext context = UndoContext.Current) { context.Start(); var mode = HttpMockServer.GetCurrentMode(); var managementClient = GetManagementClient(); var storageClient = GetStorageManagementClient(); var mediaClient = GetMediaServicesManagementClient(); var storageAccountName = TestUtilities.GenerateName(); var mediaAccountName = TestUtilities.GenerateName(); string location = ManagementTestUtilities.GetDefaultLocation(managementClient, "HighMemory"); Assert.DoesNotThrow(() => { try { storageClient.StorageAccounts.Create(new StorageAccountCreateParameters { Name = storageAccountName, AccountType = "Standard_LRS", Location = location, }); var storageResult = storageClient.StorageAccounts.Get(storageAccountName); var blobEndpoint = storageResult.StorageAccount.Properties.Endpoints.First(); var keyResult = storageClient.StorageAccounts.GetKeys(storageAccountName); StorageAccountGetResponse storageStatus = null; int tries = 0; do { TestUtilities.Wait(TimeSpan.FromSeconds(5)); storageStatus = storageClient.StorageAccounts.Get(storageAccountName); ++tries; } while (storageStatus.StorageAccount.Properties.Status != StorageAccountStatus.Created && tries < 10); mediaClient.Accounts.Create(new MediaServicesAccountCreateParameters { AccountName = mediaAccountName, BlobStorageEndpointUri = blobEndpoint, StorageAccountName = storageAccountName, StorageAccountKey = keyResult.PrimaryKey, Region = location }); var mediaGetResult = mediaClient.Accounts.Get(mediaAccountName); Assert.Equal(mediaGetResult.Account.AccountName, mediaAccountName); Assert.Equal(mediaGetResult.Account.AccountRegion, location); Assert.Equal(mediaGetResult.Account.StorageAccountName, storageAccountName); mediaClient.Accounts.RegenerateKey(mediaAccountName, MediaServicesKeyType.Primary); var mediaAccountList = mediaClient.Accounts.List(); var matchingMediaAccount = mediaAccountList.First( m => string.Equals(m.Name, mediaAccountName, StringComparison.Ordinal)); Assert.NotNull(matchingMediaAccount); } finally { TestUtilities.Wait(3000); TestUtilities.IgnoreExceptions(() => mediaClient.Accounts.Delete(mediaAccountName)); TestUtilities.IgnoreExceptions(() => storageClient.StorageAccounts.Delete(storageAccountName)); } }); } }
public void EnableProtectionForVMwareVM() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = this.GetSiteRecoveryClient(this.CustomHttpHandler); string vmId = "6d1a20c4-7e4c-11e5-bbda-0050569e3855"; string vmAccount = "vm"; var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails; Assert.NotNull(vmWareDetails); Assert.NotEmpty(vmWareDetails.VCenters); var runAsAccount = vmWareDetails.RunAsAccounts.First( account => account.AccountName.Equals( vmAccount, StringComparison.InvariantCultureIgnoreCase)); Assert.NotNull(runAsAccount); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectableItemsResponse = client.ProtectableItem.Get( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, vmId, RequestHeaders); Assert.NotNull(protectableItemsResponse); Assert.NotNull(protectableItemsResponse.ProtectableItem); var hikewalrProtectableItem = protectableItemsResponse.ProtectableItem; var vmWareAzureV2Details = hikewalrProtectableItem.Properties.CustomDetails as VMwareVirtualMachineDetails; Assert.NotNull(vmWareAzureV2Details); var policyResponse = client.Policies.List(RequestHeaders); Assert.NotNull(policyResponse); Assert.NotEmpty(policyResponse.Policies); var policy = policyResponse.Policies.First( p => p.Properties.ProviderSpecificDetails.InstanceType == "VMwareAzureV2"); Assert.NotNull(policy); Random random = new Random(100); //string storageAccountName = "bvtstoragev2"; string storageAccountSubscriptionId = "e7c9ee80-fa3b-4d71-a0db-e8e46e0e6e3b"; string storageAccountId = "/subscriptions/e7c9ee80-fa3b-4d71-a0db-e8e46e0e6e3b/resourceGroups/Default-Storage-SoutheastAsia/providers/Microsoft.Storage/storageAccounts/bvtstoragev2"; var response = client.ReplicationProtectedItem.EnableProtection( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, hikewalrProtectableItem.Name + "-Protected", new EnableProtectionInput { Properties = new EnableProtectionInputProperties { PolicyId = policy.Id, ProtectableItemId = hikewalrProtectableItem.Id, ProviderSpecificDetails = new VMwareAzureV2EnableProtectionInput { MultiVmGroupId = Guid.NewGuid().ToString(), MultiVmGroupName = policy.Name + random.Next().ToString(), ProcessServerId = vmWareDetails.ProcessServers[0].Id, RunAsAccountId = runAsAccount.AccountId, StorageAccountId = storageAccountId, StorageSubscriptionId = storageAccountSubscriptionId, MasterTargetId = vmWareDetails.MasterTargetServers[0].Id } } }, RequestHeaders); Assert.NotNull(response); Assert.Equal(OperationStatus.Succeeded, response.Status); } }
public void EnableProtectionTest() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var requestHeaders = RequestHeaders; requestHeaders.AgentAuthenticationHeader = GenerateAgentAuthenticationHeader(requestHeaders.ClientRequestId); var responsePC = client.ProtectionContainer.List(RequestHeaders); JobResponse response = new JobResponse(); bool desiredPEFound = false; foreach (var pc in responsePC.ProtectionContainers) { if (pc.Role == "Primary") { var responsePEs = client.ProtectionEntity.List(pc.ID, RequestHeaders); response = null; foreach (var pe in responsePEs.ProtectionEntities) { if (pe.Protected == false) { AzureVmDiskDetails diskDetails; DataContractUtils.Deserialize <AzureVmDiskDetails>( pe.ReplicationProviderSettings, out diskDetails); EnableProtectionInput input = new EnableProtectionInput(); int index = 0; input.ProtectionProfileId = pc.AvailableProtectionProfiles[index].ID; AzureEnableProtectionInput azureInput = new AzureEnableProtectionInput(); azureInput.HvHostVmId = pe.FabricObjectId; azureInput.VmName = pe.Name; azureInput.VHDId = diskDetails.VHDId; azureInput.OSType = diskDetails.OsType; if (string.IsNullOrWhiteSpace(azureInput.OSType)) { azureInput.OSType = "Windows"; } input.ReplicationProviderInput = DataContractUtils.Serialize <AzureEnableProtectionInput>(azureInput); response = client.ProtectionEntity.EnableProtection( pe.ProtectionContainerId, pe.ID, input, requestHeaders); desiredPEFound = true; break; } } if (desiredPEFound) { break; } } } Assert.NotNull(response.Job); Assert.NotNull(response.Job.ID); Assert.True(response.Job.Errors.Count < 1, "Errors found while doing Enable protection operation"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } }
public void CancelJobTest() { using (UndoContext context = UndoContext.Current) { context.Start(); string resourceNamespace = ConfigurationManager.AppSettings["ResourceNamespace"]; string resourceGroupName = ConfigurationManager.AppSettings["RsVaultRgNameRP"]; string resourceName = ConfigurationManager.AppSettings["RsVaultNameRP"]; string location = ConfigurationManager.AppSettings["vaultLocationRP"]; // TODO: Create VM instead of taking these parameters from config string containerUniqueName = ConfigurationManager.AppSettings["RsVaultIaasVMContainerUniqueNameRP"]; string itemUniqueName = ConfigurationManager.AppSettings["RsVaultIaasVMItemUniqueNameRP"]; string containeType = ConfigurationManager.AppSettings["IaaSVMContainerType"]; string itemType = ConfigurationManager.AppSettings["IaaSVMItemType"]; string containerUri = containeType + ";" + containerUniqueName; string itemUri = itemType + ";" + itemUniqueName; var client = GetServiceClient <RecoveryServicesBackupManagementClient>(resourceNamespace); // 1. Create vault VaultTestHelpers vaultTestHelper = new VaultTestHelpers(client); vaultTestHelper.CreateVault(resourceGroupName, resourceName, location); // 2. Get default policy PolicyTestHelpers policyTestHelper = new PolicyTestHelpers(client); string policyId = policyTestHelper.GetDefaultPolicyId(resourceGroupName, resourceName); // 3. Enable protection ProtectedItemTestHelpers protectedItemTestHelper = new ProtectedItemTestHelpers(client); DateTime protectionStartTime = DateTime.UtcNow; protectedItemTestHelper.EnableProtection(resourceGroupName, resourceName, policyId, containerUri, itemUri); DateTime protectionEndTime = DateTime.UtcNow; // 4. Trigger backup and get the job BackupTestHelpers backupTestHelper = new BackupTestHelpers(client); string jobId = backupTestHelper.BackupProtectedItem(resourceGroupName, resourceName, containerUri, itemUri); CommonJobQueryFilters commonFilters = new CommonJobQueryFilters(); commonFilters.Status = JobStatus.InProgress.ToString(); commonFilters.Operation = JobOperation.Backup.ToString(); JobTestHelpers helper = new JobTestHelpers(client); var job = helper.GetJob(resourceGroupName, resourceName, jobId); // ACTION: Cancel the job var cancelResponse = helper.CancelJob(resourceGroupName, resourceName, jobId); var opId = helper.GetOpId(cancelResponse.Location); var opStatus = helper.GetJobOperationStatus(resourceGroupName, resourceName, jobId, opId); TestUtilities.RetryActionWithTimeout( () => opStatus = helper.GetJobOperationStatus(resourceGroupName, resourceName, jobId, opId), () => opStatus.StatusCode != HttpStatusCode.Accepted, TimeSpan.FromMinutes(30), statusCode => { if (HttpMockServer.Mode == HttpRecorderMode.Record) { Thread.Sleep(15 * 1000); } return(true); }); } }
public void CreateAndVerifyGetOnAWebsiteSlot() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); var webSitesClient = ResourceGroupHelper.GetWebSitesClient(handler); var resourcesClient = ResourceGroupHelper.GetResourcesClient(handler); string webSiteName = TestUtilities.GenerateName("csmws"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); string whpName = TestUtilities.GenerateName("cswhp"); const string slotName = "staging"; string siteWithSlotName = string.Format("{0}({1})", webSiteName, slotName); var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); webSitesClient.WebHostingPlans.CreateOrUpdate(resourceGroupName, new WebHostingPlanCreateOrUpdateParameters { WebHostingPlan = new WebHostingPlan { Name = whpName, Location = location, Properties = new WebHostingPlanProperties { Sku = SkuOptions.Standard } } }); webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, webSiteName, null, new WebSiteCreateOrUpdateParameters { WebSite = new WebSiteBase { Name = webSiteName, Location = location, Tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "" } }, Properties = new WebSiteBaseProperties { ServerFarm = whpName } } }); webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, webSiteName, slotName, new WebSiteCreateOrUpdateParameters { WebSite = new WebSiteBase { Location = location, Properties = new WebSiteBaseProperties { ServerFarm = whpName } } }); // TODO: Replace with GetSite with slotName API once its CSM related issue is resolved. var webSiteSlotCollection = webSitesClient.WebSites.List(resourceGroupName, webSiteName, null); Assert.Equal(1, webSiteSlotCollection.WebSites.Count); Assert.Equal(siteWithSlotName, webSiteSlotCollection.WebSites[0].Name); } }
public void CreateAndDeleteWebSiteSlot() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); var webSitesClient = ResourceGroupHelper.GetWebSitesClient(handler); var resourcesClient = ResourceGroupHelper.GetResourcesClient(handler); string webSiteName = TestUtilities.GenerateName("csmws"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); string whpName = TestUtilities.GenerateName("csmwhp"); const string slotName = "staging"; string siteWithSlotName = string.Format("{0}({1})", webSiteName, slotName); var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); webSitesClient.WebHostingPlans.CreateOrUpdate(resourceGroupName, new WebHostingPlanCreateOrUpdateParameters { WebHostingPlan = new WebHostingPlan { Name = whpName, Location = location, Properties = new WebHostingPlanProperties() { Sku = SkuOptions.Standard } } }); webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, webSiteName, null, new WebSiteCreateOrUpdateParameters { WebSite = new WebSiteBase { Name = webSiteName, Location = location, Properties = new WebSiteBaseProperties { ServerFarm = whpName } } }); webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, webSiteName, slotName, new WebSiteCreateOrUpdateParameters { WebSite = new WebSiteBase { Location = location, Properties = new WebSiteBaseProperties { ServerFarm = whpName } } }); webSitesClient.WebSites.Delete(resourceGroupName, webSiteName, slotName, new WebSiteDeleteParameters { DeleteAllSlots = false }); var webSites = webSitesClient.WebSites.List(resourceGroupName, webSiteName, null); Assert.Equal(0, webSites.WebSites.Count); } }
public void RunPsTestWorkflow( Func <string[]> scriptBuilder, Action <CSMTestEnvironmentFactory> initialize, Action cleanup, string callingClassType, string mockName) { Dictionary <string, string> d = new Dictionary <string, string>(); d.Add("Microsoft.Authorization", null); HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(false, d); using (UndoContext context = UndoContext.Current) { context.Start(callingClassType, mockName); this.csmTestFactory = new CSMTestEnvironmentFactory(); if (initialize != null) { initialize(this.csmTestFactory); } SetupManagementClients(); helper.SetupEnvironment(AzureModule.AzureResourceManager); var callingClassName = callingClassType .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries) .Last(); helper.SetupModules(AzureModule.AzureResourceManager, "ScenarioTests\\Common.ps1", "ScenarioTests\\ComputeTestCommon.ps1", "ScenarioTests\\" + callingClassName + ".ps1", helper.RMProfileModule, helper.RMResourceModule, helper.RMStorageDataPlaneModule, helper.RMStorageModule, helper.GetRMModulePath("AzureRM.Compute.psd1"), helper.GetRMModulePath("AzureRM.Network.psd1")); try { if (scriptBuilder != null) { var psScripts = scriptBuilder(); if (psScripts != null) { helper.RunPowerShellTest(psScripts); } } } finally { if (cleanup != null) { cleanup(); } } } }
public void GetAndSetSiteLimits() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (UndoContext context = UndoContext.Current) { context.Start(); var webSitesClient = ResourceGroupHelper.GetWebSitesClient(handler); var resourcesClient = ResourceGroupHelper.GetResourcesClient(handler); string whpName = TestUtilities.GenerateName("cswhp"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); var locationName = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites"); string siteName = TestUtilities.GenerateName("csmws"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = locationName }); webSitesClient.WebHostingPlans.CreateOrUpdate(resourceGroupName, new WebHostingPlanCreateOrUpdateParameters { WebHostingPlan = new WebHostingPlan { Name = whpName, Location = locationName, Properties = new WebHostingPlanProperties { NumberOfWorkers = 1, WorkerSize = WorkerSizeOptions.Small } } }); var createResponse = webSitesClient.WebSites.CreateOrUpdate(resourceGroupName, siteName, null, new WebSiteCreateOrUpdateParameters() { WebSite = new WebSiteBase() { Name = siteName, Location = locationName, Properties = new WebSiteBaseProperties() { ServerFarm = whpName } } }); #region Get/Set Site limits var expectedSitelimits = new SiteLimits() { MaxDiskSizeInMb = 512, MaxMemoryInMb = 1024, MaxPercentageCpu = 70.5 }; var parameters = new WebSiteUpdateConfigurationParameters() { Location = locationName, Properties = new WebSiteUpdateConfigurationDetails() { Limits = expectedSitelimits } }; var siteUpdateConfigResponse = webSitesClient.WebSites.UpdateConfiguration( resourceGroupName, siteName, null, parameters); Assert.Equal(HttpStatusCode.OK, siteUpdateConfigResponse.StatusCode); var siteGetConfigResponse = webSitesClient.WebSites.GetConfiguration(resourceGroupName, siteName, null, null); Assert.NotNull(siteGetConfigResponse); Assert.NotNull(siteGetConfigResponse.Resource); Assert.NotNull(siteGetConfigResponse.Resource.Properties); var limits = siteGetConfigResponse.Resource.Properties.Limits; Assert.NotNull(limits); Assert.Equal(expectedSitelimits.MaxDiskSizeInMb, limits.MaxDiskSizeInMb); Assert.Equal(expectedSitelimits.MaxMemoryInMb, limits.MaxMemoryInMb); Assert.Equal(expectedSitelimits.MaxPercentageCpu, limits.MaxPercentageCpu); #endregion Get/Set Site limits webSitesClient.WebSites.Delete(resourceGroupName, siteName, null, new WebSiteDeleteParameters() { DeleteAllSlots = true, DeleteMetrics = true }); webSitesClient.WebHostingPlans.Delete(resourceGroupName, whpName); } }
public void UpdateProtectionOfInMageAzureV2ProtectedItem() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab"; var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectedItemResponse = client.ReplicationProtectedItem.Get( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, vmId + "-Protected", RequestHeaders); var replicationProtectedItem = protectedItemResponse.ReplicationProtectedItem; Assert.NotNull(replicationProtectedItem); var nics = new List <VMNicInputDetails>(); nics.Add( new VMNicInputDetails { NicId = "00:50:56:9E:3E:F2", RecoveryVMSubnetName = "TenantSubnet", SelectionType = "SelectedByUser", }); UpdateReplicationProtectedItemInputProperties inputProps = new UpdateReplicationProtectedItemInputProperties() { RecoveryAzureVMName = replicationProtectedItem.Properties.FriendlyName, VmNics = nics, SelectedRecoveryAzureNetworkId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/Default-Networking/providers/Microsoft.ClassicNetwork/virtualNetworks/ExpressRouteVNet-WUS-1" }; UpdateReplicationProtectedItemInput input = new UpdateReplicationProtectedItemInput() { Properties = inputProps }; var updateResponse = client.ReplicationProtectedItem.UpdateProtection( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, replicationProtectedItem.Name, input, RequestHeaders); Assert.NotNull(updateResponse); Assert.Equal(OperationStatus.Succeeded, updateResponse.Status); } }
public void ApplyRecoveryPoint() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var fabrics = client.Fabrics.List(RequestHeaders); Fabric selectedFabric = null; ProtectionContainer selectedContainer = null; foreach (var fabric in fabrics.Fabrics) { if (fabric.Properties.CustomDetails.InstanceType.Contains("VMM")) { selectedFabric = fabric; break; } } var containers = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders); foreach (var container in containers.ProtectionContainers) { if (container.Properties.ProtectedItemCount > 0 && container.Properties.Role.Equals("Primary")) { selectedContainer = container; break; } } string fabricId = selectedFabric.Name; string containerId = selectedContainer.Name; if (selectedContainer != null) { var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders); var rps = client.RecoveryPoint.List(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, RequestHeaders); ApplyRecoveryPointInputProperties applyRpProp = new ApplyRecoveryPointInputProperties() { RecoveryPointId = rps.RecoveryPoints[rps.RecoveryPoints.Count - 2].Id, ProviderSpecificDetails = new HyperVReplicaAzureApplyRecoveryPointInput() { VaultLocation = "SoutheastAsia" } }; ApplyRecoveryPointInput applyRpInput = new ApplyRecoveryPointInput() { Properties = applyRpProp }; var applyRpResp = client.ReplicationProtectedItem.ApplyRecoveryPoint( fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, applyRpInput, RequestHeaders); } else { throw new System.Exception("Container not found."); } } }
public void EnableProtectionForVMwareVMUsingInMageProvider() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = this.GetSiteRecoveryClient(this.CustomHttpHandler); string vmId = "1faecbb8-b47d-11e5-af2b-0050569e66ab"; string vmAccount = "vm"; var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails; Assert.NotNull(vmWareDetails); var runAsAccount = vmWareDetails.RunAsAccounts.First( account => account.AccountName.Equals( vmAccount, StringComparison.InvariantCultureIgnoreCase)); Assert.NotNull(runAsAccount); var processServer = vmWareDetails.ProcessServers.FirstOrDefault( ps => ps.FriendlyName.Equals("hikewalr-psjan6")); Assert.NotNull(processServer); var masterTargetServer = vmWareDetails.MasterTargetServers.FirstOrDefault(); Assert.NotNull(masterTargetServer); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectableItemsResponse = client.ProtectableItem.Get( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, vmId, RequestHeaders); Assert.NotNull(protectableItemsResponse); Assert.NotNull(protectableItemsResponse.ProtectableItem); var hikewalrProtectableItem = protectableItemsResponse.ProtectableItem; var vmWareAzureV2Details = hikewalrProtectableItem.Properties.CustomDetails as VMwareVirtualMachineDetails; Assert.NotNull(vmWareAzureV2Details); var policyResponse = client.Policies.List(RequestHeaders); Assert.NotNull(policyResponse); Assert.NotEmpty(policyResponse.Policies); var policy = policyResponse.Policies.First( p => p.Properties.ProviderSpecificDetails.InstanceType == "InMage"); Assert.NotNull(policy); Random random = new Random(100); string dataStoreName = "datastore-local (1)"; var response = client.ReplicationProtectedItem.EnableProtection( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, hikewalrProtectableItem.Name + "-Protected", new EnableProtectionInput { Properties = new EnableProtectionInputProperties { PolicyId = policy.Id, ProtectableItemId = hikewalrProtectableItem.Id, ProviderSpecificDetails = new InMageEnableProtectionInput { DatastoreName = dataStoreName, DiskExclusionInput = new InMageDiskExclusionInput(), MasterTargetId = masterTargetServer.Id, MultiVmGroupId = Guid.NewGuid().ToString(), MultiVmGroupName = policy.Name + random.Next().ToString(), ProcessServerId = processServer.Id, RetentionDrive = masterTargetServer.RetentionVolumes[0].VolumeName, RunAsAccountId = runAsAccount.AccountId, VmFriendlyName = hikewalrProtectableItem.Properties.FriendlyName } } }, RequestHeaders); Assert.NotNull(response); Assert.Equal(OperationStatus.Succeeded, response.Status); var enableResponse = response as ReplicationProtectedItemOperationResponse; Assert.NotNull(enableResponse); Assert.NotNull(enableResponse.ReplicationProtectedItem); Assert.NotNull(enableResponse.ReplicationProtectedItem.Properties); Assert.Equal(enableResponse.ReplicationProtectedItem.Name, hikewalrProtectableItem.Name + "-Protected"); } }
public void VMwareAzureV2UnplannedFailover() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectedItemsResponse = client.ReplicationProtectedItem.List( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, RequestHeaders); Assert.NotNull(protectedItemsResponse); Assert.NotEmpty(protectedItemsResponse.ReplicationProtectedItems); var protectedItem = protectedItemsResponse.ReplicationProtectedItems[0]; Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails); var vmWareAzureV2Details = protectedItem.Properties.ProviderSpecificDetails as VMwareAzureV2ProviderSpecificSettings; Assert.NotNull(vmWareAzureV2Details); UnplannedFailoverInput ufoInput = new UnplannedFailoverInput() { Properties = new UnplannedFailoverInputProperties() { FailoverDirection = "PrimaryToRecovery", ProviderSpecificDetails = new VMWareAzureV2FailoverProviderInput { RecoveryPointId = "", VaultLocation = "Southeast Asia" }, SourceSiteOperations = "" } }; var failoverExecution = client.ReplicationProtectedItem.UnplannedFailover( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, protectedItem.Name, ufoInput, RequestHeaders); } }
public void FirewallCRUDTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); // Management Clients var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler); var resClient = Sql2ScenarioHelper.GetResourceClient(handler); // Variables for server create string serverName = TestUtilities.GenerateName("csm-sql-firewallcrud"); string resGroupName = TestUtilities.GenerateName("csm-rg-firewallcrud"); string serverLocation = "West US"; string adminLogin = "******"; string adminPass = "******"; string version = "12.0"; // Create the resource group. resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup() { Location = serverLocation, }); try { ////////////////////////////////////////////////////////////////////// // Create server for test. var createResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLogin = adminLogin, AdministratorLoginPassword = adminPass, Version = version, } }); // Verify the the response from the service contains the right information TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.Created); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass, version, createResponse.Server); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Create firewall test. string firewallRuleName = TestUtilities.GenerateName("sql-fwrule"); string startIp1 = "1.2.3.4"; string endIp1 = "2.3.4.5"; string startIp2 = "10.20.30.40"; string endIp2 = "20.30.40.50"; // Create standard firewall rule. var firewallCreate = sqlClient.FirewallRules.CreateOrUpdate(resGroupName, serverName, firewallRuleName, new FirewallRuleCreateOrUpdateParameters() { Properties = new FirewallRuleCreateOrUpdateProperties() { StartIpAddress = startIp1, EndIpAddress = endIp1, } }); TestUtilities.ValidateOperationResponse(firewallCreate, HttpStatusCode.Created); FirewallRule rule = firewallCreate.FirewallRule; VerifyFirewallRuleInformation(firewallRuleName, startIp1, endIp1, rule); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Get firewall Test // Get single firewall rule var getFirewall = sqlClient.FirewallRules.Get(resGroupName, serverName, firewallRuleName); // Verify that the Get request contains the right information. TestUtilities.ValidateOperationResponse(getFirewall, HttpStatusCode.OK); VerifyFirewallRuleInformation(firewallRuleName, startIp1, endIp1, getFirewall.FirewallRule); // List all firewall rules var listResponse = sqlClient.FirewallRules.List(resGroupName, serverName); TestUtilities.ValidateOperationResponse(listResponse); Assert.Equal(1, listResponse.FirewallRules.Count); VerifyFirewallRuleInformation(firewallRuleName, startIp1, endIp1, listResponse.FirewallRules[0]); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Update firewall Test var updateResponse = sqlClient.FirewallRules.CreateOrUpdate(resGroupName, serverName, firewallRuleName, new FirewallRuleCreateOrUpdateParameters() { Properties = new FirewallRuleCreateOrUpdateProperties() { StartIpAddress = startIp2, EndIpAddress = endIp2, }, }); TestUtilities.ValidateOperationResponse(updateResponse, HttpStatusCode.OK); VerifyFirewallRuleInformation(firewallRuleName, startIp2, endIp2, updateResponse.FirewallRule); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Delete firewall Test var deleteResponse = sqlClient.FirewallRules.Delete(resGroupName, serverName, firewallRuleName); // Verify that the delete operation works. TestUtilities.ValidateOperationResponse(deleteResponse, HttpStatusCode.OK); ///////////////////////////////////////////////////////////////////// } finally { // Clean up the resource group. resClient.ResourceGroups.Delete(resGroupName); } } }
/// <summary>实现 IDTCommandTarget 接口的 Exec 方法。此方法在调用该命令时调用。</summary> /// <param term='commandName'>要执行的命令的名称。</param> /// <param term='executeOption'>描述该命令应如何运行。</param> /// <param term='varIn'>从调用方传递到命令处理程序的参数。</param> /// <param term='varOut'>从命令处理程序传递到调用方的参数。</param> /// <param term='handled'>通知调用方此命令是否已被处理。</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName == "MyCodeAddin.Connect.MyCodeAddin") { //此处添加自己的逻辑代码 #region //Point pos = new Point(); //var aa = GetCaretPos(ref pos); #endregion //TextPoint pt; //var ab = pt.CodeElement[vsCMElement //获取被选中文件路径及文件名 string fileFullPath = GetSelecteditempath(); //获取被选中文件路径(不包含文件名) string filePath = GetSelectedProjectPath(); //获取被选中的工程 Project project = GetSelectedProject(); SelectedItem item = GetProjectItemSel(); //文档 Document doc = _applicationObject.ActiveDocument; TextDocument textDoc = (TextDocument)_applicationObject.ActiveDocument.Object(""); TextSelection texSel = (TextSelection)_applicationObject.ActiveDocument.Selection; EditPoint Start = texSel.AnchorPoint.CreateEditPoint(); TextPoint endpt = texSel.BottomPoint; UndoContext undoObj = _applicationObject.UndoContext; undoObj.Open("Comment Region"); #region Business Methods //<# foreach(var item in Items) //{ // #> //public <#= item.Type #> <#= item.Name #> //{ // get ; // set ; //} //<#}#> #endregion //Do While (Start.LessThan(endpt)) Start.Insert("public {get;set;}"); Start.LineDown(); Start.StartOfLine(); //Loop undoObj.Close(); string actDocName = doc.Name; //var er=textPT.get_CodeElement(vsCMElement.vsCMElementClass); //var pt = textPT.CodeElement[vsCMElement.vsCMElementClass]; //MainForm mainF = new MainForm(); //mainF.applicationObject = _applicationObject; //mainF.project = project; //mainF.fileFullPath = fileFullPath; //mainF.filePath = filePath; //mainF.Show(); //handled = true; //return; //Form1 mainF = new Form1(); //mainF.applicationObject = _applicationObject; //mainF.project = project; //mainF.projectSel = item; //mainF.fileFullPath = fileFullPath; //mainF.filePath = filePath; //mainF.doc = doc; //mainF.textDoc = textDoc; //mainF.texSel = texSel; //mainF.start = Start; //mainF.undoObj = undoObj; //mainF.Show(); handled = true; return; //if (!GetSelecteditempath().ToLower().EndsWith(".cs")) //{ // return; //} ////读取选中类文件 //FileStream fs = new FileStream(GetSelecteditempath(), FileMode.Open, FileAccess.Read); //StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312")); ////将文件内容编译生成对象 //string conString = sr.ReadToEnd(); //object classobject = DynamicCompiling.Compo(conString); //string aa = classobject.GetType().Namespace; //if (classobject is string) //{ // MessageBox.Show("动态编译失败:" + "\r\n" + classobject, "类文件编译错误!"); // sr.Close(); // fs.Close(); // handled = true; // return; //} ////创建代码文件,并添加到项目中 //Createcode(classobject, GetSelectedProject(), GetSelectedProjectPath()); //sr.Close(); //fs.Close(); //handled = true; } } }
public void ElasticPoolDatabaseOperations() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); string resPoolName = TestUtilities.GenerateName("csm-sql-respoolcrud"); Sql2ScenarioHelper.RunServerTestInEnvironment( handler, "12.0", (sqlClient, resGroupName, server) => { ////////////////////////////////////////////////////////////////////// // Create Elastic Pool Test with all values specified (Default values) var pool1Properties = new ElasticPoolCreateOrUpdateProperties() { Edition = "Standard", Dtu = 200, DatabaseDtuMax = 100, DatabaseDtuMin = 10, StorageMB = 204800 }; var pool1 = sqlClient.ElasticPools.CreateOrUpdate(resGroupName, server.Name, resPoolName, new ElasticPoolCreateOrUpdateParameters() { Location = server.Location, Properties = pool1Properties }); TestUtilities.ValidateOperationResponse(pool1, HttpStatusCode.Created); //////////////////////////////////////////////////////////////////// // Create database in Elastic Pool var databaseName = TestUtilities.GenerateName("csm-sql-respoolcrud"); var db1 = sqlClient.Databases.CreateOrUpdate(resGroupName, server.Name, databaseName, new DatabaseCreateOrUpdateParameters() { Location = server.Location, Properties = new DatabaseCreateOrUpdateProperties() { ElasticPoolName = pool1.ElasticPool.Name, } }); TestUtilities.ValidateOperationResponse(db1, HttpStatusCode.Created); ////////////////////////////////////////////////////////////////////// // Move database into Elastic Pool var database2Name = TestUtilities.GenerateName("csm-sql-respoolcrud"); var db2 = sqlClient.Databases.CreateOrUpdate(resGroupName, server.Name, database2Name, new DatabaseCreateOrUpdateParameters() { Location = server.Location, Properties = new DatabaseCreateOrUpdateProperties() { Edition = "Basic" } }); TestUtilities.ValidateOperationResponse(db2, HttpStatusCode.Created); var moveResult = sqlClient.Databases.CreateOrUpdate(resGroupName, server.Name, database2Name, new DatabaseCreateOrUpdateParameters() { Location = server.Location, Properties = new DatabaseCreateOrUpdateProperties() { ElasticPoolName = pool1.ElasticPool.Name, } }); TestUtilities.ValidateOperationResponse(moveResult, HttpStatusCode.OK); ////////////////////////////////////////////////////////////////////// // Get database acitivity var activity = sqlClient.ElasticPools.ListDatabaseActivity(resGroupName, server.Name, resPoolName); TestUtilities.ValidateOperationResponse(moveResult, HttpStatusCode.OK); Assert.True(activity.ElasticPoolDatabaseActivities.Count > 0); }); } }
public void UpdateMobilityService() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var responseServers = client.Fabrics.List(RequestHeaders); Assert.True( responseServers.Fabrics.Count > 0, "Servers count can't be less than 1"); var vmWareFabric = responseServers.Fabrics.First( fabric => fabric.Properties.CustomDetails.InstanceType == "VMware"); Assert.NotNull(vmWareFabric); var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails; Assert.NotNull(vmWareDetails); var runAsAccount = vmWareDetails.RunAsAccounts.First( account => account.AccountName.Equals( this.runAsAccountName, StringComparison.InvariantCultureIgnoreCase)); Assert.NotNull(runAsAccount); var containersResponse = client.ProtectionContainer.List( vmWareFabric.Name, RequestHeaders); Assert.NotNull(containersResponse); Assert.True( containersResponse.ProtectionContainers.Count > 0, "Containers count can't be less than 1."); var protectedItemsResponse = client.ReplicationProtectedItem.List( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, RequestHeaders); Assert.NotNull(protectedItemsResponse); var protectedItem = protectedItemsResponse.ReplicationProtectedItems[0]; Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails); var vmWareAzureV2Details = protectedItem.Properties.ProviderSpecificDetails as VMwareAzureV2ProviderSpecificSettings; Assert.NotNull(vmWareAzureV2Details); var response = client.ReplicationProtectedItem.UpdateMobilityService( vmWareFabric.Name, containersResponse.ProtectionContainers[0].Name, vmWareAzureV2Details.InfrastructureVmId, new UpdateMobilityServiceRequest { Properties = new UpdateMobilityServiceRequestProperties { RunAsAccountId = runAsAccount.AccountId } }, RequestHeaders); Assert.Equal(OperationStatus.Succeeded, response.Status); } }
public void DatabaseCRUDTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); // Management Clients var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler); var resClient = Sql2ScenarioHelper.GetResourceClient(handler); // Variables for server create string serverName = TestUtilities.GenerateName("csm-sql-dbcrud-server"); string resGroupName = TestUtilities.GenerateName("csm-rg-dbcrud"); string serverLocation = "Japan East"; string adminLogin = "******"; string adminPass = "******"; string version = "12.0"; // Default values var defaultCollation = "SQL_Latin1_General_CP1_CI_AS"; var defaultEdition = "Standard"; var defaultDatabaseSize = 1L * 1024L * 1024L * 1024L; // 1 GB var defaultGuid = new Guid("dd6d99bb-f193-4ec1-86f2-43d3bccbc49c"); // Variables for database create string databaseName = TestUtilities.GenerateName("csm-sql-dbcrud-db"); string databaseCollation = "Japanese_Bushu_Kakusu_100_CS_AS_KS_WS"; string databaseEdition = "Standard"; long databaseMaxSize = 5L * 1024L * 1024L * 1024L; // 5 GB Guid dbSloShared = new Guid("910b4fcb-8a29-4c3e-958f-f7ba794388b2"); // Web / Business Guid dbSloBasic = new Guid("dd6d99bb-f193-4ec1-86f2-43d3bccbc49c"); // Basic Guid dbSloS0 = new Guid("f1173c43-91bd-4aaa-973c-54e79e15235b "); // S0 Guid dbSloS1 = new Guid("1b1ebd4d-d903-4baa-97f9-4ea675f5e928"); // S1 Guid dbSloS2 = new Guid("455330e1-00cd-488b-b5fa-177c226f28b7"); // S2 var databaseName2 = TestUtilities.GenerateName("csm-sql-dbcrud-db"); var databaseMaxSize2 = defaultDatabaseSize / 2L; var dbEditionBasic = "Basic"; // Create the resource group. resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup() { Location = serverLocation, }); try { ////////////////////////////////////////////////////////////////////// // Create server for test. var createServerResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLogin = adminLogin, AdministratorLoginPassword = adminPass, Version = version, } }); // Verify the the response from the service contains the right information TestUtilities.ValidateOperationResponse(createServerResponse, HttpStatusCode.Created); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass, version, createServerResponse.Server); ////////////////////////////////////////////////////////////////////// // Get Service objectives // var serviceObjectivesResponse = sqlClient.ServiceObjectives.List(resGroupName, serverName); // TestUtilities.ValidateOperationResponse(serviceObjectivesResponse, HttpStatusCode.OK); ////////////////////////////////////////////////////////////////////// // Create database test. // Create all options. var createDbResponse1 = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { Collation = databaseCollation, Edition = databaseEdition, MaxSizeBytes = databaseMaxSize, RequestedServiceObjectiveId = dbSloS1 }, }); TestUtilities.ValidateOperationResponse(createDbResponse1, HttpStatusCode.Created); VerifyDatabaseInformation(createDbResponse1.Database, serverLocation, databaseCollation, databaseEdition, databaseMaxSize, dbSloS1, dbSloS1); // Create only required var createDbResponse2 = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName2, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { MaxSizeBytes = defaultDatabaseSize, }, }); TestUtilities.ValidateOperationResponse(createDbResponse2, HttpStatusCode.Created); VerifyDatabaseInformation(createDbResponse2.Database, serverLocation, defaultCollation, databaseEdition, defaultDatabaseSize, dbSloS0, dbSloS0); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Get database test. // Get first database var getDatabase1 = sqlClient.Databases.Get(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(getDatabase1); VerifyDatabaseInformation(getDatabase1.Database, serverLocation, databaseCollation, databaseEdition, databaseMaxSize, dbSloS1, dbSloS1); // Get second database var getDatabase2 = sqlClient.Databases.Get(resGroupName, serverName, databaseName2); TestUtilities.ValidateOperationResponse(getDatabase2); VerifyDatabaseInformation(getDatabase2.Database, serverLocation, defaultCollation, defaultEdition, defaultDatabaseSize, dbSloS0, dbSloS0); // Get all databases var listDatabase1 = sqlClient.Databases.List(resGroupName, serverName); TestUtilities.ValidateOperationResponse(listDatabase1); Assert.Equal(3, listDatabase1.Databases.Count); //Get database by ID var getById = sqlClient.Databases.GetById(resGroupName, serverName, getDatabase1.Database.Properties.DatabaseId); TestUtilities.ValidateOperationResponse(getById); Assert.Equal(1, getById.Databases.Count); VerifyDatabaseInformation(getById.Databases[0], serverLocation, databaseCollation, databaseEdition, databaseMaxSize, dbSloS1, dbSloS1); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Update database test. // Update SLO var updateDb1 = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { RequestedServiceObjectiveId = dbSloS2 }, }); TestUtilities.ValidateOperationResponse(updateDb1); VerifyDatabaseInformation(updateDb1.Database, serverLocation, databaseCollation, databaseEdition, databaseMaxSize, dbSloS2, dbSloS2); //Update Size var updateDb2 = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { MaxSizeBytes = defaultDatabaseSize, }, }); TestUtilities.ValidateOperationResponse(updateDb2); VerifyDatabaseInformation(updateDb2.Database, serverLocation, databaseCollation, databaseEdition, defaultDatabaseSize, dbSloS2, dbSloS2); //Update Edition + SLO var updateDb3 = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName2, new DatabaseCreateOrUpdateParameters() { Location = serverLocation, Properties = new DatabaseCreateOrUpdateProperties() { Edition = dbEditionBasic, RequestedServiceObjectiveId = dbSloBasic, }, }); TestUtilities.ValidateOperationResponse(updateDb3); VerifyDatabaseInformation(updateDb3.Database, serverLocation, defaultCollation, "Basic", defaultDatabaseSize, dbSloBasic, dbSloBasic); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Delete database test. var deleteDb1 = sqlClient.Databases.Delete(resGroupName, serverName, databaseName); TestUtilities.ValidateOperationResponse(deleteDb1, HttpStatusCode.OK); var deleteDb2 = sqlClient.Databases.Delete(resGroupName, serverName, databaseName2); TestUtilities.ValidateOperationResponse(deleteDb2, HttpStatusCode.OK); ////////////////////////////////////////////////////////////////////// } finally { // Clean up the resource group. resClient.ResourceGroups.Delete(resGroupName); } } }
public void RunPsTestWorkflow( Func <string[]> scriptBuilder, Action <CSMTestEnvironmentFactory> initialize, Action cleanup, string callingClassType, string mockName) { Dictionary <string, string> d = new Dictionary <string, string>(); d.Add("Microsoft.Resources", null); d.Add("Microsoft.Features", null); d.Add("Microsoft.Authorization", null); var providersToIgnore = new Dictionary <string, string>(); providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01"); HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore); HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords"); using (UndoContext context = UndoContext.Current) { context.Start(callingClassType, mockName); this.csmTestFactory = new CSMTestEnvironmentFactory(); if (initialize != null) { initialize(this.csmTestFactory); } SetupManagementClients(); helper.SetupEnvironment(); var callingClassName = callingClassType .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries) .Last(); helper.SetupModules(AzureModule.AzureResourceManager, "ScenarioTests\\Common.ps1", "ScenarioTests\\" + callingClassName + ".ps1", helper.RMProfileModule, helper.RMResourceModule, helper.GetRMModulePath("AzureRM.KeyVault.psd1")); try { if (scriptBuilder != null) { var psScripts = scriptBuilder(); if (psScripts != null) { helper.RunPowerShellTest(psScripts); } } } finally { if (cleanup != null) { cleanup(); } } } }
public void ServerCRUDTest() { var handler = new BasicDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); // Management Clients var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler); var resClient = Sql2ScenarioHelper.GetResourceClient(handler); // Variables for server create string serverName = TestUtilities.GenerateName("csm-sql-servercrud"); string resGroupName = TestUtilities.GenerateName("csm-rg-servercrud"); string serverLocation = "West US"; string adminLogin = "******"; string adminPass = "******"; string adminPass2 = "S3c0ndP455"; string version = "12.0"; // Create the resource group. resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup() { Location = serverLocation, }); try { ////////////////////////////////////////////////////////////////////// // Create server Test. var createResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLogin = adminLogin, AdministratorLoginPassword = adminPass, Version = version, } }); // Verify the the response from the service contains the right information TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.Created); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass, version, createResponse.Server); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Get Server Test // Get single server var getResponse = sqlClient.Servers.Get(resGroupName, serverName); // Verify that the Get request contains the right information. TestUtilities.ValidateOperationResponse(getResponse, HttpStatusCode.OK); VerifyServerInformation(serverName, serverLocation, adminLogin, null, version, getResponse.Server); // List all servers var listResponse = sqlClient.Servers.List(resGroupName); TestUtilities.ValidateOperationResponse(listResponse); Assert.Equal(1, listResponse.Servers.Count); VerifyServerInformation(serverName, serverLocation, adminLogin, null, version, listResponse.Servers[0]); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Update Server Test var updateResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters() { Location = serverLocation, Properties = new ServerCreateOrUpdateProperties() { AdministratorLoginPassword = adminPass2, }, }); TestUtilities.ValidateOperationResponse(updateResponse, HttpStatusCode.OK); VerifyServerInformation(serverName, serverLocation, adminLogin, adminPass2, version, updateResponse.Server); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Delete Server Test var deleteResponse = sqlClient.Servers.Delete(resGroupName, serverName); // Verify that the delete operation works. TestUtilities.ValidateOperationResponse(deleteResponse, HttpStatusCode.NoContent); ///////////////////////////////////////////////////////////////////// } finally { // Clean up the resource group. resClient.ResourceGroups.Delete(resGroupName); } } }
public void PairClouds() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); string priCld = string.Empty; string recCldGuid = string.Empty; string recCld = string.Empty; string policyName = "Hydra" + (new Random()).Next(); Fabric selectedFabric = null; Policy currentPolicy = null; var fabrics = client.Fabrics.List(RequestHeaders); foreach (var fabric in fabrics.Fabrics) { if (fabric.Properties.CustomDetails.InstanceType.Contains("VMM")) { selectedFabric = fabric; } } var containers = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders); foreach (var container in containers.ProtectionContainers) { if (client.ProtectionContainerMapping.List(selectedFabric.Name, container.Name, RequestHeaders).ProtectionContainerMappings.Count == 0) { if (string.IsNullOrEmpty(priCld)) { priCld = container.Name; } else if (string.IsNullOrEmpty(recCld)) { recCld = container.Id; recCldGuid = container.Name; } } } HyperVReplica2012R2PolicyInput hvrProfileInput = new HyperVReplica2012R2PolicyInput() { ApplicationConsistentSnapshotFrequencyInHours = 0, AllowedAuthenticationType = 1, Compression = "Enable", InitialReplicationMethod = "OverNetwork", OnlineReplicationStartTime = null, RecoveryPoints = 0, ReplicaDeletion = "Required" }; CreatePolicyInputProperties policyCreationProp = new CreatePolicyInputProperties() { ProviderSpecificInput = hvrProfileInput }; CreatePolicyInput policyCreationInput = new CreatePolicyInput() { Properties = policyCreationProp }; var policyCreateResp = client.Policies.Create(policyName, policyCreationInput, RequestHeaders); currentPolicy = client.Policies.Get(policyName, RequestHeaders).Policy; CreateProtectionContainerMappingInputProperties pairingProps = new CreateProtectionContainerMappingInputProperties() { PolicyId = currentPolicy.Id, ProviderSpecificInput = new ReplicationProviderContainerMappingInput(), TargetProtectionContainerId = recCld }; CreateProtectionContainerMappingInput pairingInput = new CreateProtectionContainerMappingInput() { Properties = pairingProps }; var pairingResp = client.ProtectionContainerMapping.ConfigureProtection(selectedFabric.Name, priCld, "Mapping01", pairingInput, RequestHeaders); } }
private void AddPageMethod() { try { // Reset to the default name of the page method string name = _signature.DeclaringType.Name; // Ensure we don't have a ServicePath set PropertyDescriptor pagePathProperty = TypeDescriptor.GetProperties(Component)[_attribute.ServicePathProperty]; if (pagePathProperty != null) { string servicePath = pagePathProperty.GetValue(Component) as string; if (!string.IsNullOrEmpty(servicePath)) { ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because the extender is using web service \"{1}\" instead!", name, servicePath)); return; } } // Optionally set UseContextKey to true if (_attribute.IncludeContextParameter) { PropertyDescriptor useContextKeyProperty = TypeDescriptor.GetProperties(Component)[_attribute.UseContextKeyProperty]; if (useContextKeyProperty != null) { useContextKeyProperty.SetValue(Component, true); } } // Open the code for the page IEventBindingService bindingService; if (!EnsureService(out bindingService)) { return; } bindingService.ShowCode(); // Load the automation service object _dte = GetService(ReferencedAssemblies.EnvDTE.GetType("EnvDTE._DTE")); if (_dte == null) { ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because {1} could not be acquired!", _signature.DeclaringType.Name, "EnvDTE._DTE")); return; } DTE2 automation = new DTE2(_dte); try { // Get the CodeModel for the file FileCodeModel2 fileCodeModel = LoadFileCodeModel(automation.ActiveDocument.ProjectItem); if (fileCodeModel == null || fileCodeModel.Reference == null) { ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because no CodeBehind or CodeFile file was found!", name)); return; } // Get the class for the page IDesignerHost host; if (!EnsureService(out host)) { return; } CodeClass2 classModel = FindClass(fileCodeModel, host.RootComponentClassName); if (classModel == null || classModel.Reference == null) { ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because no CodeBehind or CodeFile file was found!", name)); return; } // Either set the ServiceMethod to the default name, or use an existing value to look it up PropertyDescriptor pageMethodProperty = TypeDescriptor.GetProperties(Component)[_attribute.ServiceMethodProperty]; if (pageMethodProperty != null) { string value = pageMethodProperty.GetValue(Component) as string; if (!string.IsNullOrEmpty(value)) { // Use the existing value as the name name = value; } else { // Ensure we get a unique name when use the default value string defaultName = name; int i = 2; while (FindMethod(classModel, name, _signature) != null) { name = defaultName + i++; } // Set the value to the default name pageMethodProperty.SetValue(Component, name); } } // Get the UndoContext for the currently open document // (since creating a DesignerTransaction will refer to the aspx page, // not the code behind that we opened) UndoContext undo = automation.UndoContext; if (undo != null && undo.Reference != null && undo.IsOpen) { undo = null; } try { CodeFunction2 method = FindMethod(classModel, name, _signature); if (method != null && method.Reference != null) { if (PageMethodNeedsRepair(method) && (ShowMessage(string.Format(CultureInfo.CurrentCulture, "Would you like to repair the existing page method \"{0}\"?", name), MessageBoxButtons.YesNo) == DialogResult.Yes)) { // Repair an existing page method if (undo != null) { undo.Open(string.Format(CultureInfo.CurrentCulture, "Repair \"{0}\" page method", name), false); } RepairPageMethod(method); } } else { // Create a new page method if (undo != null) { undo.Open(string.Format(CultureInfo.CurrentCulture, "Add \"{0}\" page method", name), false); } CreatePageMethod(classModel, name); } } finally { if (undo != null && undo.IsOpen) { undo.Close(); } } } finally { UnloadWebProjectItem(automation.ActiveDocument.ProjectItem); } } catch (Exception ex) { ShowMessage(string.Format(CultureInfo.CurrentCulture, "Unexpected error ({0}): {1}{2}{3}", ex.GetType().Name, ex.Message, Environment.NewLine, ex.StackTrace)); } }
public void CrudEndpointsFullCycle() { using (UndoContext context = UndoContext.Current) { context.Start(); TrafficManagerManagementClient trafficManagerClient = TrafficManagerHelper.GetTrafficManagerClient(); string profileName = TestUtilities.GenerateName("hydratestwatmv2profile"); string endpointName = TestUtilities.GenerateName("hydratestwatmv2endpoint"); ResourceGroupExtended resourceGroup = TrafficManagerHelper.CreateResourceGroup(); Profile profile = TrafficManagerHelper.GenerateDefaultProfile(profileName); profile.Properties.Endpoints = null; // Create profile without endpoints trafficManagerClient.Profiles.CreateOrUpdate( resourceGroup.Name, profileName, new ProfileCreateOrUpdateParameters { Profile = profile }); // Create the endpoint EndpointCreateOrUpdateResponse createEndpoint = trafficManagerClient.Endpoints.CreateOrUpdate( resourceGroup.Name, profileName, "ExternalEndpoints", endpointName, new EndpointCreateOrUpdateParameters { Endpoint = TrafficManagerHelper.GenerateDefaultEndpoint(endpointName) }); Assert.Equal(HttpStatusCode.Created, createEndpoint.StatusCode); EndpointGetResponse getEndpoint = trafficManagerClient.Endpoints.Get( resourceGroup.Name, profileName, "ExternalEndpoints", endpointName); Assert.Equal(HttpStatusCode.OK, getEndpoint.StatusCode); Endpoint endpointToUpdate = getEndpoint.Endpoint; string oldTarget = endpointToUpdate.Properties.Target; string newTarget = "another." + oldTarget; endpointToUpdate.Properties.Target = newTarget; // Update the endpoint EndpointUpdateResponse updateEndpoint = trafficManagerClient.Endpoints.Update( resourceGroup.Name, profileName, "ExternalEndpoints", endpointName, new EndpointUpdateParameters { Endpoint = endpointToUpdate }); Assert.Equal(HttpStatusCode.OK, updateEndpoint.StatusCode); Assert.Equal(newTarget, updateEndpoint.Endpoint.Properties.Target); AzureOperationResponse deleteResponse = trafficManagerClient.Endpoints.Delete( resourceGroup.Name, profileName, "ExternalEndpoints", endpointName); Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode); } }