public void RemoveAzureDedicatedCircuitSuccessful() { string serviceKey = "aa28cd19-b10a-41ff-981b-53c6bbf15ead"; ExpressRouteOperationStatusResponse expected = new ExpressRouteOperationStatusResponse() { Status = ExpressRouteOperationStatus.Successful, HttpStatusCode = HttpStatusCode.OK }; MockCommandRuntime mockCommandRuntime = new MockCommandRuntime(); Mock <ExpressRouteManagementClient> client = InitExpressRouteManagementClient(); var dcMock = new Mock <IDedicatedCircuitOperations>(); var t = new Task <ExpressRouteOperationStatusResponse>(() => expected); t.Start(); dcMock.Setup(f => f.RemoveAsync(It.Is <string>(sKey => sKey == serviceKey), It.IsAny <CancellationToken>())).Returns((string sKey, CancellationToken cancellation) => t); client.SetupGet(f => f.DedicatedCircuits).Returns(dcMock.Object); RemoveAzureDedicatedCircuitCommand cmdlet = new RemoveAzureDedicatedCircuitCommand() { ServiceKey = serviceKey, CommandRuntime = mockCommandRuntime, ExpressRouteClient = new ExpressRouteClient(client.Object) }; cmdlet.ExecuteCmdlet(); Assert.True(mockCommandRuntime.VerboseStream[0].Contains(serviceKey)); }
public void CanRemoveDedicatedCircuit() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var expressRouteClient = GetCustomerExpressRouteManagementClient(); var provider = expressRouteClient.DedicatedCircuitServiceProviders.List().Single(p => p.Name.Equals(GetProviderName(), StringComparison.CurrentCultureIgnoreCase)); var location = provider.DedicatedCircuitLocations.Split(',').First(); var bandwidth = provider.DedicatedCircuitBandwidths.First().Bandwidth; var circuitName = TestUtilities.GenerateName("circuit"); var newParams = new DedicatedCircuitNewParameters() { Bandwidth = bandwidth, CircuitName = circuitName, Location = location, ServiceProviderName = provider.Name }; var newResponse = expressRouteClient.DedicatedCircuits.New(newParams); TestUtilities.ValidateOperationResponse(newResponse); Guid serviceKey; Assert.True(Guid.TryParse(newResponse.Data, out serviceKey)); ExpressRouteOperationStatusResponse removeResponse = expressRouteClient.DedicatedCircuits.Remove(serviceKey.ToString()); TestUtilities.ValidateOperationResponse(removeResponse); } }
/// <summary> /// The Remove Dedicated Circuit Link operation deletes an existing /// dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Service Key associated with the dedicated circuit. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); Tracing.Enter(invocationId, this, "RemoveAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuitLink.BeginRemoveAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while (result.Status == ExpressRouteOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (client != null && shouldTrace) { client.Dispose(); } } }
public void NewAzureDedicatedCircuitLinkSuccessful() { // Setup string serviceKey = "aa28cd19-b10a-41ff-981b-53c6bbf15ead"; string vNetName = "DedicatedCircuitNetwork"; MockCommandRuntime mockCommandRuntime = new MockCommandRuntime(); Mock <ExpressRouteManagementClient> client = InitExpressRouteManagementClient(); var dclMock = new Mock <IDedicatedCircuitLinkOperations>(); DedicatedCircuitLinkGetResponse expected = new DedicatedCircuitLinkGetResponse() { DedicatedCircuitLink = new AzureDedicatedCircuitLink() { VnetName = vNetName, State = DedicatedCircuitLinkState.Provisioned }, RequestId = "", StatusCode = new HttpStatusCode() }; var tGet = new Task <DedicatedCircuitLinkGetResponse>(() => expected); tGet.Start(); ExpressRouteOperationStatusResponse expectedStatus = new ExpressRouteOperationStatusResponse() { HttpStatusCode = HttpStatusCode.OK }; var tNew = new Task <ExpressRouteOperationStatusResponse>(() => expectedStatus); tNew.Start(); dclMock.Setup(f => f.NewAsync(It.Is <string>(x => x == serviceKey), It.Is <string>(y => y == vNetName), It.IsAny <CancellationToken>())).Returns((string sKey, string vNet, CancellationToken cancellation) => tNew); dclMock.Setup(f => f.GetAsync(It.Is <string>(skey => skey == serviceKey), It.Is <string>(vnet => vnet == vNetName), It.IsAny <CancellationToken>())).Returns((string skey, string vnet, CancellationToken cancellation) => tGet); client.SetupGet(f => f.DedicatedCircuitLinks).Returns(dclMock.Object); NewAzureDedicatedCircuitLinkCommand cmdlet = new NewAzureDedicatedCircuitLinkCommand() { ServiceKey = Guid.Parse(serviceKey), VNetName = vNetName, CommandRuntime = mockCommandRuntime, ExpressRouteClient = new ExpressRouteClient(client.Object) }; cmdlet.ExecuteCmdlet(); // Assert AzureDedicatedCircuitLink actual = mockCommandRuntime.OutputPipeline[0] as AzureDedicatedCircuitLink; Assert.Equal <string>(expected.DedicatedCircuitLink.VnetName, actual.VnetName); Assert.Equal(expected.DedicatedCircuitLink.State.ToString(), actual.State.ToString()); }
public void RemoveFailsIfCircuitDoesNotExist() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var expressRouteClient = GetCustomerExpressRouteManagementClient(); var removeResponse = new ExpressRouteOperationStatusResponse(); var exception = Assert.Throws <CloudException>(() => removeResponse = expressRouteClient.DedicatedCircuits.Remove(FakeServiceKey)); Assert.Equal(exception.Error.Code, "BadRequest"); Assert.True(exception.Error.Message.Contains(FakeServiceKey) && exception.Error.Message.Contains("is not valid or could not be found")); } }
public AzureBgpPeering NewAzureBGPPeering(Guid serviceKey, PeerAddressTypeValues peerAddressType, string advertisedPublicPrefixes, UInt32 customerAsn, UInt32 peerAsn, string primaryPeerSubnet, string routingRegistryName, string secondaryPeerSubnet, UInt32 vlanId, BgpPeeringAccessType accessType, string sharedKey = null, UInt32 legacyMode = 0) { ExpressRouteOperationStatusResponse result = null; if (peerAddressType == PeerAddressTypeValues.IPv4) { result = Client.BorderGatewayProtocolPeerings.New(serviceKey.ToString(), accessType, new BorderGatewayProtocolPeeringNewParameters() { AdvertisedPublicPrefixes = advertisedPublicPrefixes, LegacyMode = legacyMode, CustomerAutonomousSystemNumber = customerAsn, PeerAutonomousSystemNumber = peerAsn, PrimaryPeerSubnet = primaryPeerSubnet, RoutingRegistryName = routingRegistryName, SecondaryPeerSubnet = secondaryPeerSubnet, SharedKey = sharedKey, VirtualLanId = vlanId, }); } else { result = Client.BorderGatewayProtocolPeerings.New(serviceKey.ToString(), accessType, new BorderGatewayProtocolPeeringNewParameters() { AdvertisedPublicPrefixesIpv6 = advertisedPublicPrefixes, LegacyMode = legacyMode, CustomerAutonomousSystemNumberIpv6 = customerAsn, PeerAutonomousSystemNumber = peerAsn, PrimaryPeerSubnetIpv6 = primaryPeerSubnet, RoutingRegistryNameIpv6 = routingRegistryName, SecondaryPeerSubnetIpv6 = secondaryPeerSubnet, SharedKey = sharedKey, VirtualLanId = vlanId, }); } if (result.HttpStatusCode.Equals(HttpStatusCode.OK)) { return(GetAzureBGPPeering(serviceKey, accessType)); } else { throw new Exception(result.Error.ToString()); } }
public void RemoveAzureBgpPeeringSuccessful() { // Setup string serviceKey = "aa28cd19-b10a-41ff-981b-53c6bbf15ead"; BgpPeeringAccessType accessType = BgpPeeringAccessType.Private; BgpPeerAddressType peerAddressType = BgpPeerAddressType.All; MockCommandRuntime mockCommandRuntime = new MockCommandRuntime(); Mock <ExpressRouteManagementClient> client = InitExpressRouteManagementClient(); var bgpMock = new Mock <IBorderGatewayProtocolPeeringOperations>(); ExpressRouteOperationStatusResponse expected = new ExpressRouteOperationStatusResponse() { Status = ExpressRouteOperationStatus.Successful, HttpStatusCode = HttpStatusCode.OK }; var t = new Task <ExpressRouteOperationStatusResponse>(() => expected); t.Start(); bgpMock.Setup(f => f.RemoveAsync(It.Is <string>(sKey => sKey == serviceKey), It.Is <BgpPeeringAccessType>( y => y == accessType), It.Is <BgpPeerAddressType>(z => z == peerAddressType), It.IsAny <CancellationToken>())) .Returns((string sKey, BgpPeeringAccessType aType, BgpPeerAddressType pType, CancellationToken cancellation) => t); client.SetupGet(f => f.BorderGatewayProtocolPeerings).Returns(bgpMock.Object); RemoveAzureBGPPeeringCommand cmdlet = new RemoveAzureBGPPeeringCommand() { ServiceKey = Guid.Parse(serviceKey), AccessType = accessType, PeerAddressType = BgpPeerAddressType.All, CommandRuntime = mockCommandRuntime, ExpressRouteClient = new ExpressRouteClient(client.Object) }; cmdlet.ExecuteCmdlet(); Assert.True(mockCommandRuntime.VerboseStream[0].Contains(serviceKey)); }
public void CreateFailsIfBandwidthDoesNotExist() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var expressRouteClient = GetCustomerExpressRouteManagementClient(); var provider = expressRouteClient.DedicatedCircuitServiceProviders.List().Single(p => p.Name.Equals(GetProviderName(), StringComparison.CurrentCultureIgnoreCase)); var location = provider.DedicatedCircuitLocations.Split(',').First(); var circuitName = TestUtilities.GenerateName("circuit"); var newParams = new DedicatedCircuitNewParameters() { Bandwidth = DefaultCircuitBandwidth, CircuitName = circuitName, Location = location, ServiceProviderName = provider.Name }; var newResponse = new ExpressRouteOperationStatusResponse(); var exception = Assert.Throws <CloudException>(() => newResponse = expressRouteClient.DedicatedCircuits.New(newParams)); Assert.Equal(exception.Error.Code, "ResourceNotFound"); Assert.True(exception.Error.Message.Contains(DefaultCircuitBandwidth.ToString()) && exception.Error.Message.Contains("does not exist")); } }
/// <summary> /// The New Dedicated Circuit operation creates a new dedicated circuit. /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Network Gateway operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Dedicated Circuit operation response. /// </returns> public async Task <DedicatedCircuitGetResponse> NewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "NewAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuit.BeginNewAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while (result.Status == ExpressRouteOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; } if (result.Status == ExpressRouteOperationStatus.Failed) { string exStr = "A new dedicated circuit could not be created due to an internal server error."; throw new ArgumentException(exStr); } cancellationToken.ThrowIfCancellationRequested(); DedicatedCircuitGetResponse getResult = await client.DedicatedCircuit.GetAsync(result.Data, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.Exit(invocationId, result); } return(getResult); } finally { if (client != null && shouldTrace) { client.Dispose(); } } }
/// <summary> /// The Update Cross Connection operation updates an existing cross /// connection. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the relationship between /// Azure and the customer. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Bgp Peering operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Cross Connection Operation Response. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.CrossConnectionGetResponse> UpdateAsync(string serviceKey, CrossConnectionUpdateParameters parameters, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse originalResponse = await client.CrossConnection.BeginUpdateAsync(serviceKey, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while (result.Status == ExpressRouteOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; } if (result.Status == ExpressRouteOperationStatus.Failed) { string exStr = "The cross connection could not be updated due to an internal server error."; throw new ArgumentException(exStr); } cancellationToken.ThrowIfCancellationRequested(); CrossConnectionGetResponse getResult = await client.CrossConnection.GetAsync(serviceKey, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.Exit(invocationId, result); } return(getResult); } finally { if (client != null && shouldTrace) { client.Dispose(); } } }
/// <summary> /// The Remove Dedicated Circuit Link operation deletes an existing /// dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. Service Key associated with the dedicated circuit. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (vnetName == null) { throw new ArgumentNullException("vnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/vnets/"; url = url + Uri.EscapeDataString(vnetName); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=1.0"); 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.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // 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.BadRequest) { 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 ExpressRouteOperationStatusResponse result = null; // Deserialize Response result = new ExpressRouteOperationStatusResponse(); result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public void NewAzureDedicatedCircuitSuccessful() { // Setup string circuitName = "TestCircuit"; uint bandwidth = 10; string serviceProviderName = "TestProvider"; string location = "us-west"; string serviceKey = "aa28cd19-b10a-41ff-981b-53c6bbf15ead"; MockCommandRuntime mockCommandRuntime = new MockCommandRuntime(); Mock <ExpressRouteManagementClient> client = InitExpressRouteManagementClient(); var dcMock = new Mock <IDedicatedCircuitOperations>(); DedicatedCircuitGetResponse expected = new DedicatedCircuitGetResponse() { DedicatedCircuit = new AzureDedicatedCircuit() { CircuitName = circuitName, Bandwidth = bandwidth, Location = location, ServiceProviderName = serviceProviderName, ServiceKey = serviceKey, ServiceProviderProvisioningState = ProviderProvisioningState.NotProvisioned, Status = DedicatedCircuitState.Enabled, }, RequestId = "", StatusCode = new HttpStatusCode() }; var tGet = new Task <DedicatedCircuitGetResponse>(() => expected); tGet.Start(); ExpressRouteOperationStatusResponse expectedStatus = new ExpressRouteOperationStatusResponse() { HttpStatusCode = HttpStatusCode.OK, Data = serviceKey }; var tNew = new Task <ExpressRouteOperationStatusResponse>(() => expectedStatus); tNew.Start(); dcMock.Setup(f => f.NewAsync(It.Is <DedicatedCircuitNewParameters>(x => x.Bandwidth == bandwidth && x.CircuitName == circuitName && x.Location == location && x.ServiceProviderName == serviceProviderName), It.IsAny <CancellationToken>())).Returns((DedicatedCircuitNewParameters param, CancellationToken cancellation) => tNew); dcMock.Setup(f => f.GetAsync(It.Is <string>(sKey => sKey == serviceKey), It.IsAny <CancellationToken>())).Returns((string sKey, CancellationToken cancellation) => tGet); client.SetupGet(f => f.DedicatedCircuits).Returns(dcMock.Object); NewAzureDedicatedCircuitCommand cmdlet = new NewAzureDedicatedCircuitCommand() { CircuitName = circuitName, Bandwidth = bandwidth, Location = location, ServiceProviderName = serviceProviderName, CommandRuntime = mockCommandRuntime, ExpressRouteClient = new ExpressRouteClient(client.Object) }; cmdlet.ExecuteCmdlet(); // Assert AzureDedicatedCircuit actual = mockCommandRuntime.OutputPipeline[0] as AzureDedicatedCircuit; Assert.Equal <string>(expected.DedicatedCircuit.CircuitName, actual.CircuitName); Assert.Equal <uint>(expected.DedicatedCircuit.Bandwidth, actual.Bandwidth); Assert.Equal <string>(expected.DedicatedCircuit.Location, actual.Location); Assert.Equal <string>(expected.DedicatedCircuit.ServiceProviderName, actual.ServiceProviderName); Assert.Equal(expected.DedicatedCircuit.ServiceProviderProvisioningState, actual.ServiceProviderProvisioningState); Assert.Equal(expected.DedicatedCircuit.Status, actual.Status); Assert.Equal <string>(expected.DedicatedCircuit.ServiceKey, actual.ServiceKey); }
public void RemoveFailsIfCircuitDoesNotExist() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var expressRouteClient = GetCustomerExpressRouteManagementClient(); var removeResponse = new ExpressRouteOperationStatusResponse(); var exception = Assert.Throws<CloudException>(() => removeResponse = expressRouteClient.DedicatedCircuits.Remove(FakeServiceKey)); Assert.Equal(exception.Error.Code, "BadRequest"); Assert.True(exception.Error.Message.Contains(FakeServiceKey) && exception.Error.Message.Contains("is not valid or could not be found")); } }
public void CreateFailsIfBandwidthDoesNotExist() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var expressRouteClient = GetCustomerExpressRouteManagementClient(); var provider = expressRouteClient.DedicatedCircuitServiceProviders.List().Single(p => p.Name.Equals(GetProviderName(), StringComparison.CurrentCultureIgnoreCase)); var location = provider.DedicatedCircuitLocations.Split(',').First(); var circuitName = TestUtilities.GenerateName("circuit"); var newParams = new DedicatedCircuitNewParameters() { Bandwidth = DefaultCircuitBandwidth, CircuitName = circuitName, Location = location, ServiceProviderName = provider.Name }; var newResponse = new ExpressRouteOperationStatusResponse(); var exception = Assert.Throws<CloudException>(() => newResponse = expressRouteClient.DedicatedCircuits.New(newParams)); Assert.Equal(exception.Error.Code, "ResourceNotFound"); Assert.True(exception.Error.Message.Contains(DefaultCircuitBandwidth.ToString()) && exception.Error.Message.Contains("does not exist")); } }
public void NewAzureBgpPeeringSuccessful() { // Setup string serviceKey = "aa28cd19-b10a-41ff-981b-53c6bbf15ead"; UInt32 peerAsn = 64496; string primaryPeerSubnet = "aaa"; string secondayPeerSubnet = "bbb"; UInt32 azureAsn = 64494; string primaryAzurePort = "8081"; string secondaryAzurePort = "8082"; var state = BgpPeeringState.Enabled; uint vlanId = 2; var accessType = BgpPeeringAccessType.Private; MockCommandRuntime mockCommandRuntime = new MockCommandRuntime(); Mock <ExpressRouteManagementClient> client = InitExpressRouteManagementClient(); var bgpMock = new Mock <IBorderGatewayProtocolPeeringOperations>(); BorderGatewayProtocolPeeringGetResponse expectedBgp = new BorderGatewayProtocolPeeringGetResponse { BgpPeering = new AzureBgpPeering() { AzureAsn = azureAsn, PeerAsn = peerAsn, PrimaryAzurePort = primaryAzurePort, PrimaryPeerSubnet = primaryPeerSubnet, SecondaryAzurePort = secondaryAzurePort, SecondaryPeerSubnet = secondayPeerSubnet, State = state, VlanId = vlanId }, RequestId = "", StatusCode = new HttpStatusCode() }; ExpressRouteOperationStatusResponse expectedStatus = new ExpressRouteOperationStatusResponse() { HttpStatusCode = HttpStatusCode.OK }; var tGet = new Task <BorderGatewayProtocolPeeringGetResponse>(() => expectedBgp); tGet.Start(); var tNew = new Task <ExpressRouteOperationStatusResponse>(() => expectedStatus); tNew.Start(); bgpMock.Setup( f => f.NewAsync(It.Is <string>(x => x == serviceKey), It.Is <BgpPeeringAccessType>( y => y == accessType), It.Is <BorderGatewayProtocolPeeringNewParameters>( z => z.PeerAutonomousSystemNumber == peerAsn && z.PrimaryPeerSubnet == primaryPeerSubnet && z.SecondaryPeerSubnet == secondayPeerSubnet && z.VirtualLanId == vlanId), It.IsAny <CancellationToken>())) .Returns((string sKey, BgpPeeringAccessType atype, BorderGatewayProtocolPeeringNewParameters param, CancellationToken cancellation) => tNew); client.SetupGet(f => f.BorderGatewayProtocolPeerings).Returns(bgpMock.Object); bgpMock.Setup( f => f.GetAsync(It.Is <string>(x => x == serviceKey), It.Is <BgpPeeringAccessType>( y => y == accessType), It.IsAny <CancellationToken>())) .Returns((string sKey, BgpPeeringAccessType atype, CancellationToken cancellation) => tGet); client.SetupGet(f => f.BorderGatewayProtocolPeerings).Returns(bgpMock.Object); NewAzureBGPPeeringCommand cmdlet = new NewAzureBGPPeeringCommand() { ServiceKey = Guid.Parse(serviceKey), AccessType = accessType, PeerAsn = peerAsn, PrimaryPeerSubnet = primaryPeerSubnet, SecondaryPeerSubnet = secondayPeerSubnet, SharedKey = null, VlanId = vlanId, CommandRuntime = mockCommandRuntime, ExpressRouteClient = new ExpressRouteClient(client.Object) }; cmdlet.ExecuteCmdlet(); // Assert AzureBgpPeering actual = mockCommandRuntime.OutputPipeline[0] as AzureBgpPeering; Assert.Equal(expectedBgp.BgpPeering.State, actual.State); Assert.Equal(expectedBgp.BgpPeering.PrimaryAzurePort, actual.PrimaryAzurePort); }
/// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken) { // Validate if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = "/" + (this.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Credentials.SubscriptionId)) + "/services/networking/operation/" + Uri.EscapeDataString(operationId); 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.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-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 ExpressRouteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationElement != null) { XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { string dataInstance = dataElement.Value; result.Data = dataInstance; } XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } 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(); } } }
/// <summary> /// The New Dedicated Circuit Link operation creates a new dedicated /// circuit link. /// </summary> /// <param name='serviceKey'> /// Required. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <ExpressRouteOperationStatusResponse> NewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "NewAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse response = await client.DedicatedCircuitLinks.BeginNewAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == ExpressRouteOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != ExpressRouteOperationStatus.Successful) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return(result); }