public GetAzureRmLogProfileTests(ITestOutputHelper output) { //XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); insightsLogProfileOperationsMock = new Mock<ILogProfilesOperations>(); insightsClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new GetAzureRmLogProfileCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsClientMock.Object }; response = Test.Utilities.InitializeLogProfileResponse(); insightsLogProfileOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse<LogProfileResource>>(response)) .Callback((string pfn, Dictionary<string, List<string>> headers, CancellationToken t) => { logProfileName = pfn; }); responseList = new AzureOperationResponse<IEnumerable<LogProfileResource>>() { Body = new List<LogProfileResource>() {response.Body} }; insightsLogProfileOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse<IEnumerable<LogProfileResource>>>(responseList)) .Callback((Dictionary<string, List<string>> headers, CancellationToken t) => {}); insightsClientMock.SetupGet(f => f.LogProfiles).Returns(this.insightsLogProfileOperationsMock.Object); }
public void GetIntuneAndroidMAMPolicyGroupCmdlet_ReturnsValidItem_Test() { // Set up the expected App string expectedAppResBody = "{\"value\":[{\"id\":\"/providers/Microsoft.Intune/locations/fef.bmsua01/androidPolicies/24bdd9a9-45e6-464c-a5be-82146fbe9646/groups/046e0be0-5828-47e2-8876-b6a2e33f0ccf\",\"name\":\"046e0be0-5828-47e2-8876-b6a2e33f0ccf\",\"type\":\"Microsoft.Intune/locations/androidPolicies/groups\",\"properties\":{\"friendlyName\":\"SG7\"}}]}"; var expectedRespose = new AzureOperationResponse<IPage<GroupItem>>(); var expectedResultPage = new Page<GroupItem>(); expectedResultPage = JsonConvert.DeserializeObject<Page<GroupItem>>(expectedAppResBody, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.Android.GetGroupsForMAMPolicyWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), // policy It.IsAny<Dictionary<string, List<string>>>(), // dict It.IsAny<CancellationToken>())) // cancelationToken .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.Android.GetGroupsForMAMPolicyNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void GetIntuneMAMStatus_ReturnsValidItem_Test() { // Set up the expected Policy string mamStatus = "{\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/statuses/default\",\r\n \"name\": \"default\",\r\n \"type\": \"Microsoft.Intune/locations/statuses\",\r\n \"properties\": {\r\n \"deployedPolicies\": 0,\r\n \"status\": \"complete\",\r\n \"flaggedUsers\": 0,\r\n \"policyAppliedUsers\": 0,\r\n \"enrolledUsers\": 0,\r\n \"wipePendingApps\": 0,\r\n \"wipeFailedApps\": 0,\r\n \"wipeSucceededApps\": 0,\r\n \"lastModifiedTime\": \"2015-11-24T21:32:05.4576414\"\r\n }\r\n}"; AzureOperationResponse<StatusesDefault> expectedRespose = new AzureOperationResponse<StatusesDefault>(); StatusesDefault expectedResult = JsonConvert.DeserializeObject<StatusesDefault>(mamStatus, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResult; // Set up the mock methods intuneClientMock.Setup(f => f.GetMAMStatusesWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResult), Times.Once()); }
public void GetIntuneMAMUserDeviceWipe_ReturnsValidItem_Test() { // Set up the expected Policy string deviceWipeResponse = "{\r\n \"name\": \"8693b393-a69c-4d12-a9c8-a1a415884fd2\",\r\n \"type\": \"Microsoft.Intune/locations/users/devices\",\r\n \"properties\": {\r\n \"value\": \"/operationResults/8693b393-a69c-4d12-a9c8-a1a415884fd2?$filter=category eq '8693b393-a69c-4d12-a9c8-a1a415884fd2'\"\r\n }\r\n}"; AzureOperationResponse<WipeDeviceOperationResult> expectedRespose = new AzureOperationResponse<WipeDeviceOperationResult>(); var expectedResult = JsonConvert.DeserializeObject<WipeDeviceOperationResult>(deviceWipeResponse, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResult; WipeDeviceOperationResult wipeDeviceOpResult = new WipeDeviceOperationResult(); // Set up the mock methods intuneClientMock.Setup(f => f.WipeMAMUserDeviceWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.Force = true; this.cmdlet.Name = "UserName1"; this.cmdlet.DeviceName = "MyDevice1"; this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResult), Times.Once()); }
public AddAzureRmWebtestAlertRuleTests() { insightsAlertRuleOperationsMock = new Mock<IAlertOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new AddAzureRmWebtestAlertRuleCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, }; insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateRuleAsync(It.IsAny<string>(), It.IsAny<RuleCreateOrUpdateParameters>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse>(response)) .Callback((string resourceGrp, RuleCreateOrUpdateParameters createOrUpdateParams, CancellationToken t) => { resourceGroup = resourceGrp; createOrUpdatePrms = createOrUpdateParams; }); insightsManagementClientMock.SetupGet(f => f.AlertOperations).Returns(this.insightsAlertRuleOperationsMock.Object); }
public RemoveAzureRmAutoscaleSettingTests() { insightsAutoscaleOperationsMock = new Mock<IAutoscaleOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new RemoveAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, }; insightsAutoscaleOperationsMock.Setup(f => f.DeleteSettingAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse>(response)) .Callback((string resourceGrp, string settingNm, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleOperations).Returns(this.insightsAutoscaleOperationsMock.Object); }
public RemoveAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); insightsAutoscaleOperationsMock = new Mock<IAutoscaleOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new RemoveAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, }; insightsAutoscaleOperationsMock.Setup(f => f.DeleteSettingAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse>(response)) .Callback((string resourceGrp, string settingNm, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleOperations).Returns(this.insightsAutoscaleOperationsMock.Object); }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ProcessRecordInternal() { WriteWarning("The output of this cmdlet will change. The cmdlet will not return anything in future releases."); var result = this.InsightsManagementClient.AutoscaleSettings.DeleteWithHttpMessagesAsync(resourceGroupName: this.ResourceGroup, autoscaleSettingName: this.Name).Result; // Keep this response for backwards compatibility. // Note: Delete operations return nothing in the new specification. var response = new AzureOperationResponse { // There is no data about the request Id in the new SDK .Net. RequestId = result.RequestId, StatusCode = HttpStatusCode.OK }; WriteObject(response); }
public void GetAndroidPolicies_ReturnsValidItem_Test() { // Set up the expected Policy var expectedRespose = new AzureOperationResponse<IPage<IOSMAMPolicy>>(); string expectedPolicyResBody = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/05207a60-6afd-4fd0-a8a8-e4e54bc11aa5\",\r\n \"name\": \"05207a60-6afd-4fd0-a8a8-e4e54bc11aa5\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy4872\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T20:29:48.0885169\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/0f85f3de-172b-4867-9c8c-61dcf8798515\",\r\n \"name\": \"0f85f3de-172b-4867-9c8c-61dcf8798515\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy542\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T20:30:56.7433738\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/1e5326cd-1d14-45df-a2b6-217e89a51b84\",\r\n \"name\": \"1e5326cd-1d14-45df-a2b6-217e89a51b84\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy2587\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T20:29:50.5728801\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/485cacb6-4c14-4530-b9eb-319f380201de\",\r\n \"name\": \"485cacb6-4c14-4530-b9eb-319f380201de\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy3818\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T20:31:02.853748\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/ab511ef4-fae7-4b88-8de1-ebfe8b89775c\",\r\n \"name\": \"ab511ef4-fae7-4b88-8de1-ebfe8b89775c\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy3156\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T20:11:28.8676537\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/b4a51113-0c80-48f8-a1ec-f18ebff0a4b0\",\r\n \"name\": \"b4a51113-0c80-48f8-a1ec-f18ebff0a4b0\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy8044\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T23:53:00.7365543\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.dmsua01/androidPolicies/e3059837-8d02-4dbd-a166-4c620950db3a\",\r\n \"name\": \"e3059837-8d02-4dbd-a166-4c620950db3a\",\r\n \"type\": \"Microsoft.Intune/locations/androidPolicies\",\r\n \"properties\": {\r\n \"screenCapture\": \"allow\",\r\n \"fileEncryption\": \"required\",\r\n \"friendlyName\": \"IntuneAndroidPolicy67\",\r\n \"description\": \"New Ios Policy\",\r\n \"accessRecheckOfflineTimeout\": \"P0DT12H00M\",\r\n \"accessRecheckOnlineTimeout\": \"P0DT00H30M\",\r\n \"appSharingFromLevel\": \"none\",\r\n \"appSharingToLevel\": \"none\",\r\n \"authentication\": \"required\",\r\n \"clipboardSharingLevel\": \"blocked\",\r\n \"dataBackup\": \"allow\",\r\n \"deviceCompliance\": \"enable\",\r\n \"managedBrowser\": \"required\",\r\n \"fileSharingSaveAs\": \"allow\",\r\n \"offlineWipeTimeout\": \"P1D\",\r\n \"pin\": \"required\",\r\n \"pinNumRetry\": 15,\r\n \"numOfApps\": 0,\r\n \"groupStatus\": \"notTargeted\",\r\n \"lastModifiedTime\": \"2015-11-12T23:53:01.1428402\"\r\n }\r\n }\r\n ]\r\n}"; var expectedResultPage = new Page<IOSMAMPolicy>(); expectedResultPage = JsonConvert.DeserializeObject<Page<IOSMAMPolicy>>(expectedPolicyResBody, intuneClientMock.Object.DeserializationSettings); // Set expected Policy object var expectedMAMPolicy = new IOSMAMPolicy() { FriendlyName = "expectedPolicyFriendlyName", PinNumRetry = IntuneConstants.DefaultPinNumRetry, AccessRecheckOfflineTimeout = TimeSpan.FromMinutes(IntuneConstants.DefaultAccessRecheckOfflineTimeout), AccessRecheckOnlineTimeout = TimeSpan.FromMinutes(IntuneConstants.DefaultAccessRecheckOnlineTimeout), OfflineWipeTimeout = TimeSpan.FromDays(IntuneConstants.DefaultOfflineWipeTimeout), }; expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.Ios.GetMAMPoliciesWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.Ios.GetMAMPoliciesNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void RemoveBatchAccountTest() { string accountName = "account01"; string resourceGroup = "resourceGroup"; AzureOperationResponse deleteResponse = new AzureOperationResponse(); batchClientMock.Setup(b => b.DeleteAccount(resourceGroup, accountName)).Returns(deleteResponse); cmdlet.AccountName = accountName; cmdlet.ResourceGroupName = resourceGroup; cmdlet.Force = true; commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true); cmdlet.ExecuteCmdlet(); batchClientMock.Verify(b => b.DeleteAccount(resourceGroup, accountName), Times.Once()); }
/// <summary> /// C'tor for AddIntuneAndroidMAMPolicyAppCmdletTests class. /// </summary> public AddIntuneAndroidMAMPolicyAppCmdletTests() { commandRuntimeMock = new Mock<ICommandRuntime>(); intuneClientMock = new Mock<IIntuneResourceManagementClient>(); cmdlet = new AddIntuneAndroidMAMPolicyAppCmdlet(); this.cmdlet.CommandRuntime = commandRuntimeMock.Object; this.cmdlet.IntuneClient = intuneClientMock.Object; // Set-up mock Location and mock the underlying service API method AzureOperationResponse<Location> resLocation = new AzureOperationResponse<Location>(); expectedLocation = new Location("mockHostName"); resLocation.Body = expectedLocation; intuneClientMock.Setup(f => f.GetLocationByHostNameWithHttpMessagesAsync(It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(resLocation)); }
/// <summary> /// C'tor for GetIntuneApplicationCmdletTests class. /// </summary> public GetIntuneiOSMAMAppCmdletTests(ITestOutputHelper output) { XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); commandRuntimeMock = new Mock<ICommandRuntime>(); intuneClientMock = new Mock<IIntuneResourceManagementClient>(); cmdlet = new GetIntuneiOSMAMAppCmdlet(); this.cmdlet.CommandRuntime = commandRuntimeMock.Object; this.cmdlet.IntuneClient = intuneClientMock.Object; // Set-up mock Location and mock the underlying service API method AzureOperationResponse<Location> resLocation = new AzureOperationResponse<Location>(); expectedLocation = new Location("mockHostName"); resLocation.Body = expectedLocation; intuneClientMock.Setup(f => f.GetLocationByHostNameWithHttpMessagesAsync(It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(resLocation)); }
public void NewIntuneiOSMAMPolicy_WithDefaultArgs_Test() { AzureOperationResponse<IOSMAMPolicy> resIosPolicy = new AzureOperationResponse<IOSMAMPolicy>(); // Set expected Policy object var expectedMAMPolicy = new IOSMAMPolicy() { FriendlyName = "expectedPolicyFriendlyName", PinNumRetry = IntuneConstants.DefaultPinNumRetry, AccessRecheckOfflineTimeout = TimeSpan.FromMinutes(IntuneConstants.DefaultAccessRecheckOfflineTimeout), AccessRecheckOnlineTimeout = TimeSpan.FromMinutes(IntuneConstants.DefaultAccessRecheckOnlineTimeout), OfflineWipeTimeout = TimeSpan.FromDays(IntuneConstants.DefaultOfflineWipeTimeout), }; resIosPolicy.Body = expectedMAMPolicy; IOSMAMPolicy actualPolicyObj = new IOSMAMPolicy(); // Mock the Underlying Service API method intuneClientMock.Setup(f => f.Ios.CreateOrUpdateMAMPolicyWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IOSMAMPolicy>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(resIosPolicy)).Callback((string hostName, string s, IOSMAMPolicy pObj, Dictionary<string, List<string>> dict, CancellationToken cTkn) => { actualPolicyObj = pObj; }); // Mock the PowerShell RunTime method commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set the cmdline args and execute the cmdlet this.cmdlet.FriendlyName = expectedMAMPolicy.FriendlyName; this.cmdlet.ExecuteCmdlet(); // Verify the params which are set with Default values Assert.Equal(expectedMAMPolicy.FriendlyName, actualPolicyObj.FriendlyName); Assert.Equal(expectedMAMPolicy.Name, actualPolicyObj.Id); Assert.Equal(expectedMAMPolicy.Id, actualPolicyObj.Name); Assert.Equal(expectedMAMPolicy.PinNumRetry, actualPolicyObj.PinNumRetry); Assert.Equal(expectedMAMPolicy.OfflineWipeTimeout, actualPolicyObj.OfflineWipeTimeout); Assert.Equal(expectedMAMPolicy.AccessRecheckOfflineTimeout, actualPolicyObj.AccessRecheckOfflineTimeout); Assert.Equal(expectedMAMPolicy.AccessRecheckOnlineTimeout, actualPolicyObj.AccessRecheckOnlineTimeout); commandRuntimeMock.Verify(f => f.WriteObject(expectedMAMPolicy), Times.Once()); }
public void SetIntuneAndroidMAMPolicyCmdlet_WithValidArgs_Test() { // Set up the expected Policy var resPolicy = new AzureOperationResponse<AndroidMAMPolicy>(); var expectedMAMPolicy = new AndroidMAMPolicy() { FriendlyName = "expectedPolicyFriendlyName", OfflineWipeTimeout = TimeSpan.FromDays(100), AccessRecheckOfflineTimeout = TimeSpan.FromMinutes(2), AccessRecheckOnlineTimeout = TimeSpan.FromMinutes(3), }; resPolicy.Body = expectedMAMPolicy; AndroidMAMPolicy actualPolicyObj = new AndroidMAMPolicy(); // Set up the mock methods intuneClientMock.Setup(f => f.Android.PatchMAMPolicyWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<AndroidMAMPolicy>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(resPolicy)).Callback((string hostName, string s, AndroidMAMPolicy pObj, Dictionary<string, List<string>> dict, CancellationToken cTkn) => { actualPolicyObj = pObj; }); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and Execute the cmdlet this.cmdlet.Force = true; this.cmdlet.FriendlyName = expectedMAMPolicy.FriendlyName; this.cmdlet.AccessRecheckOfflineTimeout = expectedMAMPolicy.AccessRecheckOfflineTimeout.Value.Minutes; this.cmdlet.AccessRecheckOnlineTimeout = expectedMAMPolicy.AccessRecheckOnlineTimeout.Value.Minutes; this.cmdlet.OfflineWipeTimeout = expectedMAMPolicy.OfflineWipeTimeout.Value.Days; this.cmdlet.ExecuteCmdlet(); // Verify the result Assert.Equal(expectedMAMPolicy.FriendlyName, actualPolicyObj.FriendlyName); Assert.Equal(expectedMAMPolicy.OfflineWipeTimeout, actualPolicyObj.OfflineWipeTimeout); Assert.Equal(expectedMAMPolicy.AccessRecheckOfflineTimeout, actualPolicyObj.AccessRecheckOfflineTimeout); Assert.Equal(expectedMAMPolicy.AccessRecheckOnlineTimeout, actualPolicyObj.AccessRecheckOnlineTimeout); commandRuntimeMock.Verify(f => f.WriteObject(expectedMAMPolicy), Times.Once()); }
public void GetIntuneAndroidMAMPolicyAppCmdlet_ReturnsValidItem_Test() { // Set up the expected App string expectedAppResBody = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/apps/com.microsoft.skydrive.Android\",\r\n \"name\": \"com.microsoft.skydrive.Android\",\r\n \"type\": \"Microsoft.Intune/locations/apps\",\r\n \"properties\": {\r\n \"friendlyName\": \"OneDrive\",\r\n \"platform\": \"android\",\r\n \"appId\": \"b26aadf8-566f-4478-926f-589f601d9c74\"\r\n }\r\n }\r\n ]\r\n}"; var expectedRespose = new AzureOperationResponse<IPage<Application>>(); var expectedResultPage = new Page<Application>(); expectedResultPage = JsonConvert.DeserializeObject<Page<Application>>(expectedAppResBody, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.Android.GetAppForMAMPolicyWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), // policy It.IsAny<string>(), // filter It.IsAny<int?>(), // top It.IsAny<string>(), // select It.IsAny<Dictionary<string, List<string>>>(), // dict It.IsAny<CancellationToken>())) // cancelationToken .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.Android.GetAppForMAMPolicyNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void GetIntuneMAMFlaggedEnrolledApps_ReturnsValidItem_Test() { // Set up the expected Policy string flaggedEnrolledApps = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/flaggedUsers/f4058390-f6d0-459b-9c36-3cf9d88e87f5/flaggedEnrolledApps/04045141-9ec3-4ecd-a302-3efca2b0be54\",\r\n \"name\": \"04045141-9ec3-4ecd-a302-3efca2b0be54\",\r\n \"type\": \"Microsoft.Intune/locations/flaggedUsers/flaggedEnrolledApps\",\r\n \"properties\": {\r\n \"friendlyName\": \"OneDrive\",\r\n \"deviceType\": \"TestIpad\",\r\n \"platform\": \"ios\",\r\n \"errors\": [\r\n {\r\n \"severity\": \"warning\",\r\n \"errorCode\": \"err_rootedDevice\"\r\n }\r\n ],\r\n \"lastModifiedTime\": \"2015-11-19T01:00:14.3952221\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/flaggedUsers/f4058390-f6d0-459b-9c36-3cf9d88e87f5/flaggedEnrolledApps/197103ab-43cf-46e9-87cc-a59a375a9f6c\",\r\n \"name\": \"197103ab-43cf-46e9-87cc-a59a375a9f6c\",\r\n \"type\": \"Microsoft.Intune/locations/flaggedUsers/flaggedEnrolledApps\",\r\n \"properties\": {\r\n \"friendlyName\": \"Excel\",\r\n \"deviceType\": \"TestIpad\",\r\n \"platform\": \"ios\",\r\n \"errors\": [\r\n {\r\n \"severity\": \"warning\",\r\n \"errorCode\": \"err_rootedDevice\"\r\n }\r\n ],\r\n \"lastModifiedTime\": \"2015-11-19T21:31:44.5201421\"\r\n }\r\n }\r\n ]\r\n}"; var expectedRespose = new AzureOperationResponse<IPage<FlaggedEnrolledApp>>(); IPage<FlaggedEnrolledApp> expectedResultPage = new Page<FlaggedEnrolledApp>(); expectedResultPage = JsonConvert.DeserializeObject<Page<FlaggedEnrolledApp>>(flaggedEnrolledApps, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.GetMAMUserFlaggedEnrolledAppsWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.GetMAMUserFlaggedEnrolledAppsNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void GetIntuneMAMUserDevices_ReturnsValidItem_Test() { // Set up the expected Policy string expectedUserDevices = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/users/f4058390-f6d0-459b-9c36-3cf9d88e87f5/devices/8693b393-a69c-4d12-a9c8-a1a415884fd2\",\r\n \"name\": \"8693b393-a69c-4d12-a9c8-a1a415884fd2\",\r\n \"type\": \"Microsoft.Intune/locations/users/devices\",\r\n \"properties\": {\r\n \"userId\": \"f4058390-f6d0-459b-9c36-3cf9d88e87f5\",\r\n \"friendlyName\": \"TestIpad\",\r\n \"platform\": \"IOS\",\r\n \"platformVersion\": \"9.0\",\r\n \"deviceType\": \"TestIpad\"\r\n }\r\n },\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/users/f4058390-f6d0-459b-9c36-3cf9d88e87f5/devices/38BBFA62-371F-4AA8-BFDB-846EBD47A86A\",\r\n \"name\": \"38BBFA62-371F-4AA8-BFDB-846EBD47A86A\",\r\n \"type\": \"Microsoft.Intune/locations/users/devices\",\r\n \"properties\": {\r\n \"userId\": \"f4058390-f6d0-459b-9c36-3cf9d88e87f5\",\r\n \"friendlyName\": \"iPad\",\r\n \"platform\": \"IOS\",\r\n \"platformVersion\": \"8.1\",\r\n \"deviceType\": \"iPad\"\r\n }\r\n }\r\n ]\r\n}"; var expectedRespose = new AzureOperationResponse<IPage<Device>>(); IPage<Device> expectedResultPage = new Page<Device>(); expectedResultPage = JsonConvert.DeserializeObject<Page<Device>>(expectedUserDevices, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.GetMAMUserDevicesWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.GetMAMUserDevicesNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void GetIntuneMAMFlaggedUsers_ReturnsValidItem_Test() { // Set up the expected Policy string expectedFlaggedUsers = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.bmsua01/flaggedUsers/f4058390-f6d0-459b-9c36-3cf9d88e87f5\",\r\n \"name\": \"f4058390-f6d0-459b-9c36-3cf9d88e87f5\",\r\n \"type\": \"Microsoft.Intune/locations/flaggedUsers\",\r\n \"properties\": {\r\n \"friendlyName\": \"(?)??? ???????????? ????????\",\r\n \"errorCount\": 1\r\n }\r\n }\r\n ]\r\n}"; var expectedRespose = new AzureOperationResponse<IPage<FlaggedUser>>(); IPage<FlaggedUser> expectedResultPage = new Page<FlaggedUser>(); expectedResultPage = JsonConvert.DeserializeObject<Page<FlaggedUser>>(expectedFlaggedUsers, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.GetMAMFlaggedUsersWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.GetMAMFlaggedUsersNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public void GetIntuneOperationResults_ReturnsValidItem_Test() { // Set up the expected App string expectedOperationResultsBody = "{\r\n \"value\": [\r\n {\r\n \"id\": \"/providers/Microsoft.Intune/locations/fef.msua06/operationResults/b2a254ae-ca91-4086-b6cd-575e5dbc6698\",\r\n \"name\": \"b2a254ae-ca91-4086-b6cd-575e5dbc6698\",\r\n \"type\": \"Microsoft.Intune/locations/operationResults\",\r\n \"properties\": {\r\n \"friendlyName\": \"Wipe\",\r\n \"category\": \"ApplicationManagement\",\r\n \"lastModifiedTime\": \"2015-12-03T00:15:48.4394665\",\r\n \"state\": \"pending\",\r\n \"operationMetadata\": [\r\n {\r\n \"name\": \"app\",\r\n \"value\": \"Word\"\r\n },\r\n {\r\n \"name\": \"userId\",\r\n \"value\": \"d8aeb100-6e17-4cf7-bbda-169000d03c1e\"\r\n },\r\n {\r\n \"name\": \"userName\",\r\n \"value\": \"Joe Admin\"\r\n },\r\n {\r\n \"name\": \"deviceType\",\r\n \"value\": \"iPad\"\r\n }\r\n ]\r\n }\r\n }\r\n ]\r\n}"; var expectedRespose = new AzureOperationResponse<IPage<OperationResult>>(); var expectedResultPage = new Page<OperationResult>(); expectedResultPage = JsonConvert.DeserializeObject<Page<OperationResult>>(expectedOperationResultsBody, intuneClientMock.Object.DeserializationSettings); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.GetOperationResultsWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.GetOperationResultsNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
public GetAzureRmAlertHistoryTests(ITestOutputHelper output) { //XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); insightsEventOperationsMock = new Mock<IEventsOperations>(); insightsClientMock = new Mock<InsightsClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new GetAzureRmAlertHistoryCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsClient = insightsClientMock.Object }; response = Test.Utilities.InitializeResponse(); insightsEventOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<ODataQuery<EventData>>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse<IPage<EventData>>>(response)) .Callback((ODataQuery<EventData> f, string s, Dictionary<string, List<string>> headers, CancellationToken t) => { filter = f; selected = s; }); insightsClientMock.SetupGet(f => f.Events).Returns(this.insightsEventOperationsMock.Object); }
public static void VerifyContinuationToken(AzureOperationResponse<IPage<EventData>> response, Mock<IEventsOperations> insinsightsEventOperationsMockightsClientMock, EventCmdletBase cmdlet) { // Make sure calls to Next work also string nextToken = ContinuationToken; insinsightsEventOperationsMockightsClientMock.Setup(f => f.ListNextWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AzureOperationResponse<IPage<EventData>>>(response)) .Callback((string n, Dictionary<string, List<string>> h, CancellationToken t) => nextToken = n); // Calling without optional parameters cmdlet.ExecuteCmdlet(); Assert.Equal(Utilities.ContinuationToken, nextToken, ignoreCase:true, ignoreLineEndingDifferences:true,ignoreWhiteSpaceDifferences:true); }
public void GetPoolTestNonNullProperties() { DateTime currentDateTime = DateTime.UtcNow; DateTime dateTimeMinusAnHour = currentDateTime.AddHours(-1); using (BatchClient client = ClientUnitTestCommon.CreateDummyClient()) { Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(baseRequest => { var request = (Protocol.BatchRequest <Models.PoolGetOptions, AzureOperationResponse <Models.CloudPool, Models.PoolGetHeaders> >)baseRequest; request.ServiceRequestFunc = async(token) => { var response = new AzureOperationResponse <Models.CloudPool, Models.PoolGetHeaders> { Body = new Models.CloudPool { AllocationState = Models.AllocationState.Steady, AllocationStateTransitionTime = dateTimeMinusAnHour, AutoScaleFormula = string.Empty, AutoScaleRun = new Models.AutoScaleRun(), DisplayName = "batch-test", CertificateReferences = new[] { new Models.CertificateReference { StoreLocation = Models.CertificateStoreLocation.CurrentUser, StoreName = "My", Thumbprint = string.Empty, ThumbprintAlgorithm = "sha1", Visibility = new List <Models.CertificateVisibility>() { Models.CertificateVisibility.RemoteUser, Models.CertificateVisibility.StartTask, Models.CertificateVisibility.Task } } }, CreationTime = dateTimeMinusAnHour, CloudServiceConfiguration = new Models.CloudServiceConfiguration(osFamily: "4", osVersion: "*"), CurrentDedicatedNodes = 3, ETag = "eTag=0x8D250D98B5D78AA", EnableAutoScale = false, LastModified = currentDateTime, TaskSlotsPerNode = 4, ResizeTimeout = new TimeSpan(), State = Models.PoolState.Active, StateTransitionTime = currentDateTime, TargetDedicatedNodes = 3, Url = "testbatch://batch-test.windows-int.net/pools/batch-test", TaskSchedulingPolicy = new Microsoft.Azure.Batch.Protocol.Models.TaskSchedulingPolicy { NodeFillType = Models.ComputeNodeFillType.Pack } } }; var task = Task.FromResult(response); return(await task); }; }); var pool = client.PoolOperations.GetPool("batch-test", additionalBehaviors: new List <BatchClientBehavior> { interceptor }); Assert.Equal("batch-test", pool.DisplayName); Assert.Equal(AllocationState.Steady, pool.AllocationState); Assert.Equal(dateTimeMinusAnHour, pool.AllocationStateTransitionTime); Assert.Equal(dateTimeMinusAnHour, pool.CreationTime); Assert.Equal("*", pool.CloudServiceConfiguration.OSVersion); Assert.Equal(3, pool.CurrentDedicatedComputeNodes); Assert.Equal(false, pool.AutoScaleEnabled); Assert.Equal(currentDateTime, pool.LastModified); Assert.Equal(4, pool.TaskSlotsPerNode); Assert.Equal("4", pool.CloudServiceConfiguration.OSFamily); Assert.Equal(PoolState.Active, pool.State); Assert.Equal(currentDateTime, pool.StateTransitionTime); Assert.Equal(ComputeNodeFillType.Pack, pool.TaskSchedulingPolicy.ComputeNodeFillType); Assert.Equal(3, pool.TargetDedicatedComputeNodes); Assert.Equal("testbatch://batch-test.windows-int.net/pools/batch-test", pool.Url); var certs = pool.CertificateReferences; Assert.Equal(CertStoreLocation.CurrentUser, certs[0].StoreLocation); Assert.Equal("My", certs[0].StoreName); Assert.Equal(string.Empty, certs[0].Thumbprint); Assert.Equal("sha1", certs[0].ThumbprintAlgorithm); } }
/// <summary> /// The Get publicIpAddress operation retreives information about the /// specified pubicIpAddress /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <PublicIPAddress> GetAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse <PublicIPAddress> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, expand, null, cancellationToken).ConfigureAwait(false); return(result.Body); }
/// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationResponse <IList <VirtualMachineImageResource> > > ListSkusWithHttpMessagesAsync(string location, string publisherName, string offer, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (offer == null) { throw new ValidationException(ValidationRules.CannotBeNull, "offer"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("offer", offer); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListSkus", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{offer}", Uri.EscapeDataString(offer)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse <IList <VirtualMachineImageResource> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject <IList <VirtualMachineImageResource> >(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public SetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output) { //ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); insightsDiagnosticsOperationsMock = new Mock<IServiceDiagnosticSettingsOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new SetAzureRmDiagnosticSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; request = new ServiceDiagnosticSettingsResource { StorageAccountId = storageAccountId, Logs = new List<LogSettings> { new LogSettings { Category = "TestCategory1", Enabled = true }, new LogSettings { Category = "TestCategory2", Enabled = false } }, Metrics = new List<MetricSettings> { new MetricSettings { TimeGrain = TimeSpan.FromMinutes(1), Enabled = false }, new MetricSettings { TimeGrain = TimeSpan.FromHours(1), Enabled = true } } }; insightsDiagnosticsOperationsMock.Setup(f => f.GetAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<ServiceDiagnosticSettingsResource>(request)) .Callback((string resourceId) => { this.calledResourceId = resourceId; }); Rest.Azure.AzureOperationResponse<ServiceDiagnosticSettingsResource> response = new AzureOperationResponse<ServiceDiagnosticSettingsResource> { Body = request }; insightsDiagnosticsOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<ServiceDiagnosticSettingsCreateOrUpdateParameters>(), It.IsAny<Dictionary<string,List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Rest.Azure.AzureOperationResponse<ServiceDiagnosticSettingsResource>>(response)) .Callback((string resourceId, ServiceDiagnosticSettingsCreateOrUpdateParameters putParameters, Dictionary<string,List<string>> headers) => { this.calledResourceId = resourceId; this.calledPutParameters = putParameters; }); insightsManagementClientMock.SetupGet(f => f.ServiceDiagnosticSettings).Returns(this.insightsDiagnosticsOperationsMock.Object); }
/// <summary> /// The List publicIpAddress opertion retrieves all the publicIpAddresses in a /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <IPage <PublicIPAddress> > ListNextAsync(this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse <IPage <PublicIPAddress> > result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return(result.Body); }
public override void ExecuteCmdlet() { ExecutionBlock(() => { base.ExecuteCmdlet(); ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId); string vaultName = resourceIdentifier.ResourceName; string resourceGroupName = resourceIdentifier.ResourceGroupName; WriteDebug(string.Format("Input params - Policy: {0}" + "RetentionPolicy:{1}, SchedulePolicy:{2}", Policy == null ? "NULL" : Policy.ToString(), RetentionPolicy == null ? "NULL" : RetentionPolicy.ToString(), SchedulePolicy == null ? "NULL" : SchedulePolicy.ToString())); // Validate policy name PolicyCmdletHelpers.ValidateProtectionPolicyName(Policy.Name); // Validate if policy already exists ProtectionPolicyResource servicePolicy = PolicyCmdletHelpers.GetProtectionPolicyByName( Policy.Name, ServiceClientAdapter, vaultName: vaultName, resourceGroupName: resourceGroupName); if (servicePolicy == null) { throw new ArgumentException(string.Format(Resources.PolicyNotFoundException, Policy.Name)); } PsBackupProviderManager providerManager = new PsBackupProviderManager( new Dictionary <System.Enum, object>() { { VaultParams.VaultName, vaultName }, { VaultParams.ResourceGroupName, resourceGroupName }, { PolicyParams.ProtectionPolicy, Policy }, { PolicyParams.RetentionPolicy, RetentionPolicy }, { PolicyParams.SchedulePolicy, SchedulePolicy }, }, ServiceClientAdapter); IPsBackupProvider psBackupProvider = providerManager.GetProviderInstance( Policy.WorkloadType, Policy.BackupManagementType); AzureOperationResponse <ProtectionPolicyResource> policyResponse = psBackupProvider.ModifyPolicy(); WriteDebug("ModifyPolicy http response from service: " + policyResponse.Response.StatusCode.ToString()); if (policyResponse.Response.StatusCode == System.Net.HttpStatusCode.Accepted) { // Track OperationStatus URL for operation completion string policyName = Policy.Name; ServiceClientModel.OperationStatus operationStatus = TrackingHelpers.GetOperationStatus( policyResponse, operationId => ServiceClientAdapter.GetProtectionPolicyOperationStatus( policyName, operationId, vaultName: vaultName, resourceGroupName: resourceGroupName)); WriteDebug("Final operation status: " + operationStatus.Status); if (operationStatus.Properties != null && ((OperationStatusJobsExtendedInfo)operationStatus.Properties) .JobIds != null) { // get list of jobIds and return jobResponses WriteObject(GetJobObject( ((OperationStatusJobsExtendedInfo)operationStatus.Properties).JobIds, vaultName: vaultName, resourceGroupName: resourceGroupName)); } if (operationStatus.Status == OperationStatusValues.Failed) { // if operation failed, then trace error and throw exception if (operationStatus.Error != null) { WriteDebug(string.Format( "OperationStatus Error: {0} " + "OperationStatus Code: {1}", operationStatus.Error.Message, operationStatus.Error.Code)); } } } else { // ServiceClient will return OK if NO datasources are associated with this policy WriteDebug("No datasources are associated with Policy, http response code: " + policyResponse.Response.StatusCode.ToString()); } }, ShouldProcess(Policy.Name, VerbsCommon.Set)); }
public void GetBatchTaskTest() { // Setup cmdlet to get a task by id BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = "task1"; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a Get CloudTask call AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(cmdlet.Id); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskGetOptions, AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the task returned from the OM to the pipeline Assert.Equal(1, pipeline.Count); Assert.Equal(cmdlet.Id, pipeline[0].Id); }
public void GetsResourceProviderTests() { //setup return values const string RegisteredProviderNamespace = "Providers.Test1"; const string UnregisteredProviderNamespace = "Providers.Test2"; const string ResourceTypeName = "TestResource1"; var unregisteredProvider = new Provider { NamespaceProperty = UnregisteredProviderNamespace, RegistrationState = "Unregistered", ResourceTypes = new[] { new ProviderResourceType { Locations = new[] {"West US", "East US", "South US"}, ResourceType = "TestResource2" } } }; var listResult = new List<Provider>() { new Provider { NamespaceProperty = RegisteredProviderNamespace, RegistrationState = ResourceManagerSdkClient.RegisteredStateName, ResourceTypes = new[] { new ProviderResourceType { Locations = new[] { "West US", "East US" }, //Name = ResourceTypeName, } } }, unregisteredProvider, }; var pagableResult = new Page<Provider>(); pagableResult.SetItemValue<Provider>(listResult); var result = new AzureOperationResponse<IPage<Provider>>() { Body = pagableResult }; this.providerOperationsMock .Setup(f => f.ListWithHttpMessagesAsync(null, null, null, It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(result)); var locationList = new List<Location> { new Location { Name = "southus", DisplayName = "South US", } }; var pagableLocations = new Page<Location>(); pagableLocations.SetItemValue<Location>(locationList); var locationsResult = new AzureOperationResponse<IEnumerable<Location>>() { Body = pagableLocations }; this.subscriptionsOperationsMock .Setup(f => f.ListLocationsWithHttpMessagesAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(locationsResult)); // 1. List only registered providers this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(1, providers.Length); var provider = providers.Single(); Assert.Equal(RegisteredProviderNamespace, provider.ProviderNamespace); Assert.Equal(ResourceManagerSdkClient.RegisteredStateName, provider.RegistrationState); Assert.Equal(1, provider.ResourceTypes.Length); var resourceType = provider.ResourceTypes.Single(); Assert.Equal(ResourceTypeName, resourceType.ResourceTypeName); Assert.Equal(2, resourceType.Locations.Length); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 2. List all providers this.cmdlet.ListAvailable = true; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(2, providers.Length); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 3. List a single provider by name this.cmdlet.ProviderNamespace = UnregisteredProviderNamespace; this.providerOperationsMock .Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), null, null, It.IsAny<CancellationToken>())) .Returns((Task.FromResult(new AzureOperationResponse<Provider>() { Body = unregisteredProvider }))); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(1, providers.Length); var provider = providers.Single(); Assert.Equal(UnregisteredProviderNamespace, provider.ProviderNamespace); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.IndividualProviderParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyGetCallPatternAndReset(); // 4. List only registered providers with location this.cmdlet.Location = "South US"; this.cmdlet.ListAvailable = false; this.cmdlet.ProviderNamespace = null; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(0, providers.Length); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 5. List all providers this.cmdlet.ListAvailable = true; this.cmdlet.Location = "South US"; this.cmdlet.ProviderNamespace = null; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { var providers = (PSResourceProvider[])obj; Assert.Equal(0, providers.Length); var provider = providers.Single(); Assert.Equal(UnregisteredProviderNamespace, provider.ProviderNamespace); Assert.Equal(1, provider.ResourceTypes.Length); var resourceType = provider.ResourceTypes.Single(); Assert.Equal(ResourceTypeName, resourceType.ResourceTypeName); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); }
public void ListTasksMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list tasks without filters and a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] idsOfConstructedTasks = new[] { "testTask1", "testTask2", "testTask3" }; // Build some CloudTasks instead of querying the service on a List CloudTasks call AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateCloudTaskListResponse(idsOfConstructedTasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())) .Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(idsOfConstructedTasks.Length, pipeline.Count); }
public void GetBatchTaskParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.Job = null; cmdlet.Filter = null; AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateGenericAzureOperationListResponse <ProxyModels.CloudTask, ProxyModels.TaskListHeaders>(); // Build a CloudTask instead of querying the service on a List CloudTask call RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobId = "job-1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); }
public void ListBatchTasksWithoutFiltersTest() { // Setup cmdlet to list tasks without filters. Use WorkItemName and JobName. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = null; cmdlet.Filter = null; string[] idsOfConstructedTasks = new[] { "testTask1", "testTask2", "testTask3" }; // Build some CloudTasks instead of querying the service on a List CloudTasks call AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateCloudTaskListResponse(idsOfConstructedTasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())) .Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed tasks to the pipeline Assert.Equal(3, pipeline.Count); int taskCount = 0; foreach (PSCloudTask t in pipeline) { Assert.True(idsOfConstructedTasks.Contains(t.Id)); taskCount++; } Assert.Equal(idsOfConstructedTasks.Length, taskCount); }
public void ListBatchTasksODataTest() { // Setup cmdlet to list tasks using an OData filter BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "testJob"; cmdlet.Id = null; cmdlet.Filter = "startswith(id,'test')"; cmdlet.Select = "id,state"; cmdlet.Expand = "stats"; string requestFilter = null; string requestSelect = null; string requestExpand = null; AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateGenericAzureOperationListResponse <ProxyModels.CloudTask, ProxyModels.TaskListHeaders>(); Action <BatchRequest <ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> > > extractTaskListAction = (request) => { ProxyModels.TaskListOptions options = request.Options; requestFilter = options.Filter; requestSelect = options.Select; requestExpand = options.Expand; }; RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor(responseToUse: response, requestAction: extractTaskListAction); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor }; cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor }; cmdlet.ExecuteCmdlet(); Assert.Equal(cmdlet.Filter, requestFilter); Assert.Equal(cmdlet.Select, requestSelect); Assert.Equal(cmdlet.Expand, requestExpand); }
public void GetBatchTaskODataTest() { // Setup cmdlet to get a single task BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "testJob"; cmdlet.Id = "testTask1"; cmdlet.Select = "id,state"; cmdlet.Expand = "stats"; string requestSelect = null; string requestExpand = null; // Fetch the OData clauses off the request. The OData clauses are applied after user provided RequestInterceptors, so a ResponseInterceptor is used. AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> getResponse = BatchTestHelpers.CreateCloudTaskGetResponse(cmdlet.Id); RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskGetOptions, AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(getResponse); ResponseInterceptor responseInterceptor = new ResponseInterceptor((response, request) => { ProxyModels.TaskGetOptions options = (ProxyModels.TaskGetOptions)request.Options; requestSelect = options.Select; requestExpand = options.Expand; return(Task.FromResult(response)); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor, responseInterceptor }; cmdlet.ExecuteCmdlet(); Assert.Equal(cmdlet.Select, requestSelect); Assert.Equal(cmdlet.Expand, requestExpand); }
// TO DO: Since we have to fetch the task, the interceptor needs to handle that case too. Once // the cmdlet can directly call the List Subtasks method by itself, update these test cases to // use the generic interceptor creation helper. private RequestInterceptor CreateFakeListSubtasksInterceptor( string taskId, AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> listSubtasksResponse) { RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { TaskListSubtasksBatchRequest listSubtaskRequest = baseRequest as TaskListSubtasksBatchRequest; if (listSubtaskRequest != null) { listSubtaskRequest.ServiceRequestFunc = (cancellationToken) => { Task<AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders>> task = Task.FromResult(listSubtasksResponse); return task; }; } else { TaskGetBatchRequest getTaskRequest = (TaskGetBatchRequest)baseRequest; getTaskRequest.ServiceRequestFunc = (cancellationToken) => { AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(taskId); Task<AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders>> task = Task.FromResult(response); return task; }; } }); return interceptor; }
/// <summary> /// Unregister the Scheduler resource provider with your subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task <AzureOperationResponse> UnregisterResourceProviderAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); TracingAdapter.Enter(invocationId, this, "UnregisterResourceProviderAsync", tracingParameters); } // Construct URL string url = (this.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Credentials.SubscriptionId)) + "/services?"; url = url + "service=scheduler.JobCollections"; url = url + "&action=unregister"; string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public void WhenGettingATaskFromTheService_ExitConditionsAreMapped() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = "task-1"; cmdlet.JobId = "job-1"; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a Get CloudTask call ProxyModels.ExitOptions none = new ProxyModels.ExitOptions { JobAction = ProxyModels.JobAction.None }; ProxyModels.ExitOptions terminate = new ProxyModels.ExitOptions { JobAction = ProxyModels.JobAction.Terminate }; ProxyModels.CloudTask cloudTask = new ProxyModels.CloudTask { Id = "task-1", ExitConditions = new ProxyModels.ExitConditions { ExitCodeRanges = new[] { new ProxyModels.ExitCodeRangeMapping(2, 5, none) }, ExitCodes = new[] { new ProxyModels.ExitCodeMapping(4, terminate) }, PreProcessingError = terminate, FileUploadError = none, DefaultProperty = none, } }; AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(cloudTask); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <ProxyModels.TaskGetOptions, AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later var pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the task returned from the OM to the pipeline Assert.Single(pipeline); Assert.Equal(cmdlet.Id, pipeline[0].Id); PSExitConditions psExitConditions = pipeline[0].ExitConditions; Assert.Equal(JobAction.None, psExitConditions.Default.JobAction); Assert.Equal(JobAction.None, psExitConditions.ExitCodeRanges.First().ExitOptions.JobAction); Assert.Equal(JobAction.Terminate, psExitConditions.PreProcessingError.JobAction); Assert.Equal(JobAction.None, psExitConditions.FileUploadError.JobAction); Assert.Equal(4, psExitConditions.ExitCodes.First().Code); Assert.Equal(JobAction.Terminate, psExitConditions.ExitCodes.First().ExitOptions.JobAction); Assert.Equal(2, psExitConditions.ExitCodeRanges.First().Start); Assert.Equal(5, psExitConditions.ExitCodeRanges.First().End); Assert.Equal(JobAction.None, psExitConditions.ExitCodeRanges.First().ExitOptions.JobAction); }
/// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update PublicIPAddress operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <PublicIPAddress> BeginCreateOrUpdateAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse <PublicIPAddress> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false); return(result.Body); }
public void GetProviderFeatureTests() { // setup return values const string Provider1Namespace = "Providers.Test1"; const string Feature1Name = "feature1"; const string Provider2Namespace = "Providers.Test2"; const string Feature2Name = "feature2"; var provider1RegisteredFeature = new FeatureResult { Id = "featureId1", Name = Provider1Namespace + "/" + Feature1Name, Properties = new FeatureProperties { State = ProviderFeatureClient.RegisteredStateName, }, Type = "Microsoft.Features/feature" }; var provider1UnregisteredFeature = new FeatureResult { Id = "featureId1", Name = Provider1Namespace + "/" + Feature2Name, Properties = new FeatureProperties { State = "Unregistered", }, Type = "Microsoft.Features/feature" }; var provider2UnregisteredFeature = new FeatureResult { Id = "featureId2", Name = Provider2Namespace + "/" + Feature1Name, Properties = new FeatureProperties { State = "Unregistered", }, Type = "Microsoft.Features/feature" }; var pagableResult = new Page<FeatureResult>(); //var listResult = new[] { provider1RegisteredFeature, provider1UnregisteredFeature, provider2UnregisteredFeature }; var listResult = new List<FeatureResult>() { provider1RegisteredFeature, provider1UnregisteredFeature, provider2UnregisteredFeature }; pagableResult.SetItemValue<FeatureResult>(listResult); var result = new AzureOperationResponse<IPage<FeatureResult>>() { Body = pagableResult }; this.featureOperationsMock .Setup(f => f.ListAllWithHttpMessagesAsync(null, It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult(result)); // 1. List only registered features of providers this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(1, features.Length); var provider = features.Single(); Assert.Equal(Provider1Namespace, provider.ProviderName, StringComparer.OrdinalIgnoreCase); Assert.Equal(Feature1Name, provider.FeatureName, StringComparer.OrdinalIgnoreCase); Assert.Equal(ProviderFeatureClient.RegisteredStateName, provider.RegistrationState, StringComparer.OrdinalIgnoreCase); }); this.cmdlet.ParameterSetOverride = GetAzureProviderFeatureCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListAllCallPatternAndReset(); // 2. List all features of all providers this.cmdlet.ListAvailable = true; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(listResult.Count(), features.Length); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListAllCallPatternAndReset(); // 3.a. List only registered features of a particular provider - and they exist string providerOfChoice = Provider1Namespace; this.cmdlet.ListAvailable = false; this.cmdlet.ProviderNamespace = providerOfChoice; //pagableResult.SetItemValue<FeatureResult>(new List<FeatureResult>() { provider1RegisteredFeature, provider1UnregisteredFeature }); this.featureOperationsMock .Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>())) .Callback((string providerName, Dictionary<string, List<string>> customHeaders, CancellationToken ignored) => Assert.Equal(providerOfChoice, providerName, StringComparer.OrdinalIgnoreCase)) .Returns(() => Task.FromResult( new AzureOperationResponse<IPage<FeatureResult>>() { Body = pagableResult })); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(1, features.Length); var provider = features.Single(); Assert.Equal(Provider1Namespace, provider.ProviderName, StringComparer.OrdinalIgnoreCase); Assert.Equal(Feature1Name, provider.FeatureName, StringComparer.OrdinalIgnoreCase); Assert.Equal(ProviderFeatureClient.RegisteredStateName, provider.RegistrationState, StringComparer.OrdinalIgnoreCase); }); this.cmdlet.ParameterSetOverride = GetAzureProviderFeatureCmdlet.GetFeatureParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListProviderFeaturesCallPatternAndReset(); // 3.b. List only registered features of a particular provider - and they do not exist providerOfChoice = Provider2Namespace; this.cmdlet.ListAvailable = false; this.cmdlet.ProviderNamespace = providerOfChoice; //pagableResult.SetItemValue<FeatureResult>(new List<FeatureResult>() { provider2UnregisteredFeature }); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(0, features.Length); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListProviderFeaturesCallPatternAndReset(); // 4. List all features of a particular provider providerOfChoice = Provider1Namespace; this.cmdlet.ProviderNamespace = providerOfChoice; this.cmdlet.ListAvailable = true; //pagableResult.SetItemValue<FeatureResult>(new List<FeatureResult>() { provider1RegisteredFeature, provider1UnregisteredFeature }); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(2, features.Length); Assert.True(features.Any(feature => string.Equals(feature.FeatureName, Feature1Name, StringComparison.OrdinalIgnoreCase))); Assert.True(features.Any(feature => string.Equals(feature.FeatureName, Feature2Name, StringComparison.OrdinalIgnoreCase))); Assert.True(features.All(feature => string.Equals(feature.ProviderName, Provider1Namespace, StringComparison.OrdinalIgnoreCase))); }); this.cmdlet.ParameterSetOverride = GetAzureProviderFeatureCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListProviderFeaturesCallPatternAndReset(); // 5. get a single provider feature by name this.cmdlet.ProviderNamespace = Provider2Namespace; this.cmdlet.FeatureName = Feature1Name; this.cmdlet.ListAvailable = false; this.featureOperationsMock .Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), null, It.IsAny<CancellationToken>())) .Callback((string providerName, string featureName, Dictionary<string, List<string>> customHeaders, CancellationToken ignored) => { Assert.Equal(Provider2Namespace, providerName, StringComparer.OrdinalIgnoreCase); Assert.Equal(Feature1Name, featureName, StringComparer.OrdinalIgnoreCase); }) .Returns(() => Task.FromResult(new AzureOperationResponse<FeatureResult>() { Body = provider2UnregisteredFeature })); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny<object>())) .Callback((object obj) => { Assert.IsType<PSProviderFeature[]>(obj); var features = (PSProviderFeature[])obj; Assert.Equal(1, features.Length); var feature = features.Single(); Assert.Equal(Provider2Namespace, feature.ProviderName, StringComparer.OrdinalIgnoreCase); Assert.Equal(Feature1Name, feature.FeatureName, StringComparer.OrdinalIgnoreCase); Assert.Equal("Unregistered", feature.RegistrationState, StringComparer.OrdinalIgnoreCase); }); this.cmdlet.ParameterSetOverride = GetAzureProviderFeatureCmdlet.GetFeatureParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyGetCallPatternAndReset(); }
/// <summary> /// Grants OAuth2 permissions for the relevant resource Ids of an app. /// </summary> /// <param name='body'> /// The relevant app Service Principal Object Id and the Service Principal /// Object Id you want to grant. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <OAuth2PermissionGrant> > CreateWithHttpMessagesAsync(OAuth2PermissionGrant body = default(OAuth2PermissionGrant), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/oauth2PermissionGrants").ToString(); _url = _url.Replace("{tenantID}", System.Uri.EscapeDataString(Client.TenantID)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <OAuth2PermissionGrant>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <OAuth2PermissionGrant>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public static void ExecuteVerifications(EventCmdletBase cmdlet, Mock<IEventsOperations> insinsightsEventOperationsMockightsClientMock, string requiredFieldName, string requiredFieldValue, ref ODataQuery<EventData> filter, ref string selected, DateTime startDate, AzureOperationResponse<IPage<EventData>> response) { // Calling without optional parameters cmdlet.ExecuteCmdlet(); VerifyFilterIsUsable(filter: filter); VerifyStartDateInFilter(filter: filter, startDate: null); VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue); Assert.True(string.Equals(PSEventDataNoDetails.SelectedFieldsForQuery, selected, StringComparison.OrdinalIgnoreCase), "Incorrect nameOrTargetUri clause without optional parameters"); // Calling with only start date cmdlet.StartTime = startDate; cmdlet.ExecuteCmdlet(); VerifyFilterIsUsable(filter: filter); VerifyStartDateInFilter(filter: filter, startDate: startDate); VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue); // Calling with only start and end date cmdlet.EndTime = startDate.AddSeconds(2); cmdlet.ExecuteCmdlet(); VerifyFilterIsUsable(filter: filter); VerifyStartDateInFilter(filter: filter, startDate: startDate); VerifyEndDateInFilter(filter: filter, endDate: startDate.AddSeconds(2)); VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue); // Calling with only caller cmdlet.EndTime = null; cmdlet.Caller = Utilities.Caller; cmdlet.ExecuteCmdlet(); VerifyCallerInCall(filter: filter, startDate: startDate, filedName: requiredFieldName, fieldValue: requiredFieldValue); // Calling with caller and status cmdlet.Status = Utilities.Status; cmdlet.ExecuteCmdlet(); VerifyStatusAndCallerInCall(filter: filter, startDate: startDate, filedName: requiredFieldName, fieldValue: requiredFieldValue); VerifyDetailedOutput(cmdlet: cmdlet, selected: ref selected); VerifyContinuationToken(response: response, insinsightsEventOperationsMockightsClientMock: insinsightsEventOperationsMockightsClientMock, cmdlet: cmdlet); // Execute negative tests cmdlet.StartTime = DateTime.Now.AddSeconds(1); Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.StartTime = DateTime.Now.Subtract(TimeSpan.FromSeconds(20)); cmdlet.EndTime = DateTime.Now.Subtract(TimeSpan.FromSeconds(21)); Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.StartTime = DateTime.Now.Subtract(TimeSpan.FromDays(30)); cmdlet.EndTime = DateTime.Now.Subtract(TimeSpan.FromDays(14)); Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); }
public async Task TestCancelUpdateElasticPoolOperation() { /* * * In this test we only test the cancel operation on resize pool from Premium to Premium * since currently we only support Cancel pool resize operation on Premium <-> Premium * */ string testPrefix = "sqlelasticpoollistcanceloperation-"; using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup("West Europe"); Server server = context.CreateServer(resourceGroup, "westeurope"); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); Dictionary <string, string> tags = new Dictionary <string, string>() { { "tagKey1", "TagValue1" } }; // Create a premium elastic pool with required parameters string epName = SqlManagementTestUtilities.GenerateName(); var epInput = new ElasticPool() { Location = server.Location, Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ElasticPoolEdition.Premium + "Pool"), Tags = tags, }; var elasticPool = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput); SqlManagementTestUtilities.ValidateElasticPool(epInput, elasticPool, epName); Assert.NotNull(elasticPool); // Update elastic pool to Premium with 250 DTU var epUpdateReponse = sqlClient.ElasticPools.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, epName, new ElasticPool() { Location = server.Location, Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ElasticPoolEdition.Premium + "Pool") { Capacity = 250, }, Tags = tags }); if (HttpMockServer.Mode == HttpRecorderMode.Record) { Thread.Sleep(TimeSpan.FromSeconds(15)); } // Get the pool update operation for new added properties on elastic pool operations: ETA, Operation Description and IsCancellable // Expected they have null value since not been updated by operation progress AzureOperationResponse <IPage <ElasticPoolOperation> > response = sqlClient.ElasticPoolOperations.ListByElasticPoolWithHttpMessagesAsync(resourceGroup.Name, server.Name, epName).Result; Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); IList <ElasticPoolOperation> responseObject = response.Body.ToList(); Assert.Single(responseObject); Assert.NotNull(responseObject[0].PercentComplete); Assert.NotNull(responseObject[0].EstimatedCompletionTime); Assert.NotNull(responseObject[0].Description); Assert.NotNull(responseObject[0].IsCancellable); // Cancel the elastic pool update operation string requestId = responseObject[0].Name; sqlClient.ElasticPoolOperations.Cancel(resourceGroup.Name, server.Name, epName, Guid.Parse(requestId)); CloudException ex = await Assert.ThrowsAsync <CloudException>(() => sqlClient.GetPutOrPatchOperationResultAsync(epUpdateReponse.Result, new Dictionary <string, List <string> >(), CancellationToken.None)); Assert.Contains("OperationCancelled", ex.Body.Code); // Make sure the elastic pool is not updated due to cancel operation var epGetResponse = sqlClient.ElasticPools.Get(resourceGroup.Name, server.Name, epName); Assert.Equal(125, epGetResponse.Dtu); Assert.Equal("Premium", epGetResponse.Edition); } }
/// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } string apiVersion = "2016-02-29"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Gets all available service aliases for this resource group in this region. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='location'> /// The location. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <AvailableServiceAlias> > > ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string location, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2019-08-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("location", location); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/availableServiceAliases").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <AvailableServiceAlias> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <AvailableServiceAlias> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Initializes PATCH LRO Operation /// </summary> /// <param name="client"></param> /// <param name="response"></param> /// <param name="customHeaders"></param> /// <param name="cancellationToken"></param> public PATCHLro(IAzureClient client, AzureOperationResponse <TResourceBody, TRequestHeaders> response, Dictionary <string, List <string> > customHeaders, CancellationToken cancellationToken) : base(client, response, customHeaders, cancellationToken) { }
/// <summary> /// Gets a Latency Scorecard for a given Experiment /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// The Profile identifier associated with the Tenant and Partner /// </param> /// <param name='experimentName'> /// The Experiment identifier associated with the Experiment /// </param> /// <param name='aggregationInterval'> /// The aggregation interval of the Latency Scorecard. Possible values include: /// 'Daily', 'Weekly', 'Monthly' /// </param> /// <param name='endDateTimeUTC'> /// The end DateTime of the Latency Scorecard in UTC /// </param> /// <param name='country'> /// The country associated with the Latency Scorecard. Values are country ISO /// codes as specified here- https://www.iso.org/iso-3166-country-codes.html /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <LatencyScorecard> > GetLatencyScorecardsWithHttpMessagesAsync(string resourceGroupName, string profileName, string experimentName, string aggregationInterval, string endDateTimeUTC = default(string), string country = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (profileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "profileName"); } if (profileName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(profileName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "profileName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (experimentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "experimentName"); } if (experimentName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(experimentName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "experimentName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (aggregationInterval == null) { throw new ValidationException(ValidationRules.CannotBeNull, "aggregationInterval"); } string apiVersion = "2019-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("experimentName", experimentName); tracingParameters.Add("endDateTimeUTC", endDateTimeUTC); tracingParameters.Add("country", country); tracingParameters.Add("aggregationInterval", aggregationInterval); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetLatencyScorecards", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}/LatencyScorecard").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{experimentName}", System.Uri.EscapeDataString(experimentName)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (endDateTimeUTC != null) { _queryParameters.Add(string.Format("endDateTimeUTC={0}", System.Uri.EscapeDataString(endDateTimeUTC))); } if (country != null) { _queryParameters.Add(string.Format("country={0}", System.Uri.EscapeDataString(country))); } if (aggregationInterval != null) { _queryParameters.Add(string.Format("aggregationInterval={0}", System.Uri.EscapeDataString(aggregationInterval))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <LatencyScorecard>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LatencyScorecard>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// The Generatevpnclientpackage operation generates Vpn client package for /// P2S client of the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn /// client package operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { #region 1. Send Async request to generate vpn client package // 1. Send Async request to generate vpn client package string baseUrl = NetworkManagementClient.BaseUri.ToString(); string apiVersion = NetworkManagementClient.ApiVersion; if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } // Construct URL var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/" + "providers/Microsoft.Network/virtualnetworkgateways/{virtualNetworkGatewayName}/generatevpnclientpackage").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayName}", Uri.EscapeDataString(virtualNetworkGatewayName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(NetworkManagementClient.SubscriptionId)); url += "?" + string.Join("&", string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); // Serialize Request string requestContent = JsonConvert.SerializeObject(parameters, NetworkManagementClient.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (NetworkManagementClient.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await NetworkManagementClient.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request cancellationToken.ThrowIfCancellationRequested(); var client = this.NetworkManagementClient as NetworkManagementClient; HttpClient httpClient = client.HttpClient; HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 202) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1}", statusCode, string.IsNullOrEmpty(responseContent) ? "NotAvailable" : responseContent)); } // Create Result var result = new AzureOperationResponse<string>(); result.Request = httpRequest; result.Response = httpResponse; string locationResultsUrl = string.Empty; // Retrieve the location from LocationUri if (httpResponse.Headers.Contains("Location")) { locationResultsUrl = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } else { throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation Failed as no valid Location header received in response!")); } if (string.IsNullOrEmpty(locationResultsUrl)) { throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation Failed as no valid Location header value received in response!")); } #endregion #region 2. Wait for Async operation to succeed and then Get the content i.e. VPN Client package Url from locationResults //Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(60000); // 2. Wait for Async operation to succeed DateTime startTime = DateTime.UtcNow; DateTime giveUpAt = DateTime.UtcNow.AddMinutes(3); // Send the Get locationResults request for operaitonId till either we get StatusCode 200 or it time outs (3 minutes in this case) while (true) { HttpRequestMessage newHttpRequest = new HttpRequestMessage(); newHttpRequest.Method = new HttpMethod("GET"); newHttpRequest.RequestUri = new Uri(locationResultsUrl); if (NetworkManagementClient.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await NetworkManagementClient.Credentials.ProcessHttpRequestAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); } HttpResponseMessage newHttpResponse = await httpClient.SendAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); if ((int)newHttpResponse.StatusCode != 200) { if (DateTime.UtcNow > giveUpAt) { string newResponseContent = await newHttpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1} while retrieving " + "the Vpnclient PackageUrl!", newHttpResponse.StatusCode, string.IsNullOrEmpty(newResponseContent) ? "NotAvailable" : newResponseContent)); } else { // Wait for 15 seconds before retrying Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(15000); } } else { // Get the content i.e.VPN Client package Url from locationResults result.Body = newHttpResponse.Content.ReadAsStringAsync().Result; return result; } } #endregion }
public void SetIntuneAndroidMAMPolicyCmdlet_WithInValidArgs_Test() { // Set-up the expected Policy var resPolicy = new AzureOperationResponse<AndroidMAMPolicy>(); var expectedMAMPolicy = new AndroidMAMPolicy() { FriendlyName = "expectedPolicyFriendlyName", }; resPolicy.Body = expectedMAMPolicy; // Set up the mock methods intuneClientMock.Setup(f => f.Android.PatchMAMPolicyWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<AndroidMAMPolicy>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(resPolicy)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set the cmdline args and Execute the cmdlet this.cmdlet.FriendlyName = "expectedPolicyFriendlyName"; this.cmdlet.Force = true; this.cmdlet.PinNumRetry = -1; try { this.cmdlet.ExecuteCmdlet(); } catch (Exception e) { // Verify the result Assert.IsType<PSArgumentOutOfRangeException>(e); commandRuntimeMock.Verify(f => f.WriteObject(expectedMAMPolicy), Times.Never()); } }
public void GetBatchComputeNodeLoginSettingsParametersTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testIaasPool"; cmdlet.ComputeNodeId = "computeNode01"; string ipAddress = "104.214.75.220"; // Don't go to the service on an Get RemoteLoginSettings call AzureOperationResponse <ComputeNodeGetRemoteLoginSettingsResult, ComputeNodeGetRemoteLoginSettingsHeaders> response = BatchTestHelpers.CreateRemoteLoginSettingsGetResponse(ipAddress); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ComputeNodeGetRemoteLoginSettingsOptions, AzureOperationResponse <ComputeNodeGetRemoteLoginSettingsResult, ComputeNodeGetRemoteLoginSettingsHeaders> >(responseToUse: response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later PSRemoteLoginSettings loginSettings = null; commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSRemoteLoginSettings>())) .Callback <object>(p => loginSettings = (PSRemoteLoginSettings)p); // Verify no exceptions when required parameter is set cmdlet.ExecuteCmdlet(); Assert.Equal(ipAddress, loginSettings.IPAddress); }
/// <summary> /// Deletes a private endpoint connection. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the service instance. /// </param> /// <param name='workspaceName'> /// The name of workspace resource. /// </param> /// <param name='privateEndpointConnectionName'> /// The name of the private endpoint connection associated with the Azure /// resource /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorDetailsException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (workspaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName"); } if (workspaceName != null) { if (workspaceName.Length > 24) { throw new ValidationException(ValidationRules.MaxLength, "workspaceName", 24); } if (workspaceName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "workspaceName", 3); } } if (privateEndpointConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("privateEndpointConnectionName", privateEndpointConnectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthcareApis/workspaces/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName)); _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new ErrorDetailsException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorDetails _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorDetails>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public SubscriptionClient GetSubscriptionClientVer2019() { var tenantMock = new Mock <ITenantsOperations>(); tenantMock.Setup(t => t.ListWithHttpMessagesAsync(It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())) .Returns( (Dictionary <string, List <string> > ch, CancellationToken token) => { if (TenantListQueueVer2019 != null && TenantListQueueVer2019.Any()) { return(ListTenantQueueDequeueVer2019()); } var tenants = _tenants.Select((k) => new TenantIdDescription(id: k, tenantId: k)); var mockPage = new MockPage <TenantIdDescription>(tenants.ToList()); AzureOperationResponse <IPage <TenantIdDescription> > r = new AzureOperationResponse <IPage <TenantIdDescription> > { Body = mockPage }; return(Task.FromResult(r)); } ); var subscriptionMock = new Mock <ISubscriptionsOperations>(); subscriptionMock.Setup( s => s.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns( (string subId, Dictionary <string, List <string> > ch, CancellationToken token) => { if (SubGetQueueVer2019 != null && SubGetQueueVer2019.Any()) { return(GetSubQueueDequeueVer2019()); } AzureOperationResponse <Subscription> result = new AzureOperationResponse <Subscription> { RequestId = Guid.NewGuid().ToString() }; if (_subscriptionSet.Contains(subId)) { result.Body = new Subscription( id: subId, subscriptionId: subId, tenantId: null, displayName: GetSubscriptionNameFromId(subId), state: SubscriptionState.Enabled, subscriptionPolicies: null, authorizationSource: null); } return(Task.FromResult(result)); }); subscriptionMock.Setup( (s) => s.ListWithHttpMessagesAsync(null, It.IsAny <CancellationToken>())).Returns( (Dictionary <string, List <string> > ch, CancellationToken token) => { if (SubListQueueVer2019 != null && SubListQueueVer2019.Any()) { return(ListSubQueueDequeueVer2019()); } AzureOperationResponse <IPage <Subscription> > result = null; if (_subscriptions.Count > 0) { var subscriptionList = _subscriptions.Dequeue(); result = new AzureOperationResponse <IPage <Subscription> > { RequestId = Guid.NewGuid().ToString(), Body = new MockPage <Subscription>( new List <Subscription>( subscriptionList.Select( sub => new Subscription( id: sub, subscriptionId: sub, tenantId: null, displayName: GetSubscriptionNameFromId(sub), state: SubscriptionState.Enabled, subscriptionPolicies: null, authorizationSource: null))), "LinkToNextPage") }; } return(Task.FromResult(result)); }); subscriptionMock.Setup( (s) => s.ListNextWithHttpMessagesAsync("LinkToNextPage", null, It.IsAny <CancellationToken>())).Returns( (string nextLink, Dictionary <string, List <string> > ch, CancellationToken token) => { AzureOperationResponse <IPage <Subscription> > result = null; if (_subscriptions.Count > 0) { var subscriptionList = _subscriptions.Dequeue(); result = new AzureOperationResponse <IPage <Subscription> > { RequestId = Guid.NewGuid().ToString(), Body = new MockPage <Subscription>( new List <Subscription>( subscriptionList.Select( sub => new Subscription( id: sub, subscriptionId: sub, tenantId: null, displayName: GetSubscriptionNameFromId(sub), state: SubscriptionState.Disabled, subscriptionPolicies: null, authorizationSource: null)))) }; } return(Task.FromResult(result)); }); var client = new Mock <SubscriptionClient>() { CallBase = true }; client.SetupGet(c => c.Subscriptions).Returns(subscriptionMock.Object); client.SetupGet(c => c.Tenants).Returns(tenantMock.Object); return(client.Object); }
private ISubscriptionsOperations GetSubscriptionMock(List <Subscription> subscriptionGetList, List <List <Subscription> > subscriptionListLists, List <bool> HasNextPage) { if (HasNextPage == null && subscriptionListLists != null) { HasNextPage = Enumerable.Repeat(false, subscriptionListLists.Count).ToList(); } var subscriptionMock = new Mock <ISubscriptionsOperations>(); if (subscriptionGetList != null) { subscriptionMock.Setup( s => s.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns( (string subId, Dictionary <string, List <string> > ch, CancellationToken token) => { if (SubGetQueueVer2019 != null && SubGetQueueVer2019.Any()) { return(GetSubQueueDequeueVer2019()); } AzureOperationResponse <Subscription> result = new AzureOperationResponse <Subscription>() { RequestId = Guid.NewGuid().ToString() }; if (subscriptionGetList.Any()) { result.Body = subscriptionGetList.First(); subscriptionGetList.RemoveAt(0); } return(Task.FromResult(result)); }); } subscriptionMock.Setup( (s) => s.ListWithHttpMessagesAsync(null, It.IsAny <CancellationToken>())).Returns( (Dictionary <string, List <string> > ch, CancellationToken token) => { if (SubListQueueVer2019 != null && SubListQueueVer2019.Any()) { return(ListSubQueueDequeueVer2019()); } AzureOperationResponse <IPage <Subscription> > result = null; if (subscriptionListLists.Any() && HasNextPage.Any()) { result = new AzureOperationResponse <IPage <Subscription> > { RequestId = Guid.NewGuid().ToString(), Body = HasNextPage.First() ? new MockPage <Subscription>(subscriptionListLists.FirstOrDefault(), "LinkToNextPage") : new MockPage <Subscription>(subscriptionListLists.FirstOrDefault()) }; subscriptionListLists.RemoveAt(0); HasNextPage.RemoveAt(0); } return(Task.FromResult(result)); }); subscriptionMock.Setup( (s) => s.ListNextWithHttpMessagesAsync("LinkToNextPage", null, It.IsAny <CancellationToken>())).Returns( (string nextLink, Dictionary <string, List <string> > ch, CancellationToken token) => { AzureOperationResponse <IPage <Subscription> > result = null; if (subscriptionListLists.Any() && HasNextPage.Any()) { result = new AzureOperationResponse <IPage <Subscription> > { RequestId = Guid.NewGuid().ToString(), Body = new MockPage <Subscription>(subscriptionListLists.LastOrDefault()) }; subscriptionListLists.RemoveAt(0); HasNextPage.RemoveAt(0); } return(Task.FromResult(result)); }); return(subscriptionMock.Object); }
public static void CopyRuntimeProperties(AzureOperationResponse source, AzureOperationResponse target) { target.RequestId = source.RequestId; target.StatusCode = source.StatusCode; }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (!string.IsNullOrEmpty(this.Name)) { if (Status) { var result = this.VirtualMachineClient.Get(this.ResourceGroupName, this.Name, InstanceViewExpand); WriteObject(result.ToPSVirtualMachineInstanceView(this.ResourceGroupName, this.Name)); } else { var result = this.VirtualMachineClient.GetWithHttpMessagesAsync( this.ResourceGroupName, this.Name).GetAwaiter().GetResult(); var psResult = Mapper.Map <PSVirtualMachine>(result); if (result.Body != null) { psResult = Mapper.Map <PSVirtualMachine>(result.Body); } WriteObject(psResult); } } else { AzureOperationResponse <IPage <VirtualMachine> > vmListResult = null; if (!string.IsNullOrEmpty(this.ResourceGroupName)) { vmListResult = this.VirtualMachineClient.ListWithHttpMessagesAsync(this.ResourceGroupName) .GetAwaiter().GetResult(); } else if (this.NextLink != null) { vmListResult = this.VirtualMachineClient.ListNextWithHttpMessagesAsync(this.NextLink.ToString()) .GetAwaiter().GetResult(); } else { vmListResult = this.VirtualMachineClient.ListAllWithHttpMessagesAsync() .GetAwaiter().GetResult(); } var psResultList = new List <PSVirtualMachine>(); while (vmListResult != null) { if (vmListResult.Body != null) { foreach (var item in vmListResult.Body) { var psItem = Mapper.Map <PSVirtualMachine>(item); psItem = Mapper.Map(vmListResult, psItem); psResultList.Add(psItem); } } if (!string.IsNullOrEmpty(vmListResult.Body.NextPageLink)) { vmListResult = this.VirtualMachineClient.ListNextWithHttpMessagesAsync(vmListResult.Body.NextPageLink) .GetAwaiter().GetResult(); } else { vmListResult = null; } } WriteObject(psResultList, true); } }); }
/// <summary> /// Initializes DELETE LRO Operation /// </summary> /// <param name="client"></param> /// <param name="response"></param> /// <param name="customHeaders"></param> /// <param name="cancellationToken"></param> public DeleteLro(IAzureClient client, AzureOperationResponse <TResourceBody, TRequestHeaders> response, Dictionary <string, List <string> > customHeaders, CancellationToken cancellationToken) : base(client, response, customHeaders, cancellationToken) { SetFinalGetCallback = false; }
public void WhenGettingATaskFromTheService_ApplicationPackageReferencesAreMapped() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = "task-1"; cmdlet.JobId = "job-1"; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a Get CloudTask call string applicationId = "foo"; string applicationVersion = "beta"; ProxyModels.CloudTask cloudTask = new ProxyModels.CloudTask { Id = "task-1", ApplicationPackageReferences = new[] { new ProxyModels.ApplicationPackageReference(applicationId, applicationVersion) } }; AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(cloudTask); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <ProxyModels.TaskGetOptions, AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior> { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later var pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the task returned from the OM to the pipeline Assert.Single(pipeline); Assert.Equal(cmdlet.Id, pipeline[0].Id); var psApplicationPackageReference = pipeline[0].ApplicationPackageReferences.First(); Assert.Equal(applicationId, psApplicationPackageReference.ApplicationId); Assert.Equal(applicationVersion, psApplicationPackageReference.Version); }
public void GetIntuneiOSMAMApp_ReturnsNoItem_Test() { // Set up an empty expected App var expectedRespose = new AzureOperationResponse<IPage<Application>>(); IPage<Application> expectedResultPage = new Page<Application>(); expectedRespose.Body = expectedResultPage; // Set up the mock methods intuneClientMock.Setup(f => f.GetAppsWithHttpMessagesAsync( expectedLocation.HostName, It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); intuneClientMock.Setup(f => f.GetAppsNextWithHttpMessagesAsync( It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(expectedRespose)); commandRuntimeMock.Setup(m => m.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())) .Returns(() => true); // Set cmdline args and execute the cmdlet this.cmdlet.ExecuteCmdlet(); // Verify the result commandRuntimeMock.Verify(f => f.WriteObject(expectedResultPage, true), Times.Once()); }
/// <summary> /// Updates Vault encryption config. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='parameters'> /// Vault encryption input config request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> UpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, BackupResourceEncryptionConfigResource parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEncryptionConfigs/backupResourceEncryptionConfig").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Get null duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <System.TimeSpan?> > GetNullWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.TimeSpan?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Sets status of data slices over a time range for a specific table. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to set status of data slices. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task <AzureOperationResponse> SetStatusAsync(string resourceGroupName, string dataFactoryName, string tableName, DataSliceSetStatusParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (tableName != null && tableName.Length > 260) { throw new ArgumentOutOfRangeException("tableName"); } if (Regex.IsMatch(tableName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("tableName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "SetStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/tables/"; url = url + Uri.EscapeDataString(tableName); url = url + "/slices/setstatus"; List <string> queryParameters = new List <string>(); if (parameters.DataSliceRangeStartTime != null) { queryParameters.Add("start=" + Uri.EscapeDataString(parameters.DataSliceRangeStartTime)); } if (parameters.DataSliceRangeEndTime != null) { queryParameters.Add("end=" + Uri.EscapeDataString(parameters.DataSliceRangeEndTime)); } queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataSliceSetStatusParametersValue = new JObject(); requestDoc = dataSliceSetStatusParametersValue; if (parameters.SliceState != null) { dataSliceSetStatusParametersValue["SliceState"] = parameters.SliceState; } if (parameters.UpdateType != null) { dataSliceSetStatusParametersValue["UpdateType"] = parameters.UpdateType; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }