/// <summary>
        /// The Update Bgp Peering operation updates an existing bgp peering or
        /// creates a new one if one doesn't exist.
        /// </summary>
        /// <param name='serviceKey'>
        /// The service key representing the relationship between Azure and the
        /// customer.
        /// </param>
        /// <param name='accessType'>
        /// Whether the peering is private or public.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Update Bgp Peering operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Bgp Peering Operation Response.
        /// </returns>
        public async Task <BgpPeeringGetResponse> UpdateAsync(string serviceKey, BgpPeeringAccessType accessType, BgpPeeringUpdateParameters 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("accessType", accessType);
                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.BgpPeering.BeginUpdateAsync(serviceKey, accessType, 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 BGP peering could not be updated due to an internal server error.";
                    throw new ArgumentException(exStr);
                }
                cancellationToken.ThrowIfCancellationRequested();
                BgpPeeringGetResponse getResult = await client.BgpPeering.GetAsync(serviceKey, accessType, cancellationToken).ConfigureAwait(false);

                if (shouldTrace)
                {
                    Tracing.Exit(invocationId, result);
                }

                return(getResult);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
        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 <IBgpPeeringOperations>();

            BgpPeeringGetResponse expected =
                new BgpPeeringGetResponse()
            {
                BgpPeering = new AzureBgpPeering()
                {
                    AzureAsn            = azureAsn,
                    PeerAsn             = peerAsn,
                    PrimaryAzurePort    = primaryAzurePort,
                    PrimaryPeerSubnet   = primaryPeerSubnet,
                    SecondaryAzurePort  = secondaryAzurePort,
                    SecondaryPeerSubnet = secondayPeerSubnet,
                    State  = state,
                    VlanId = vlanId
                },
                RequestId  = "",
                StatusCode = new HttpStatusCode()
            };
            var t = new Task <BgpPeeringGetResponse>(() => expected);

            t.Start();

            bgpMock.Setup(
                f =>
                f.NewAsync(It.Is <string>(x => x == serviceKey),
                           It.Is <BgpPeeringAccessType>(
                               y => y == accessType),
                           It.Is <BgpPeeringNewParameters>(
                               z =>
                               z.PeerAsn == peerAsn && z.PrimaryPeerSubnet == primaryPeerSubnet &&
                               z.SecondaryPeerSubnet == secondayPeerSubnet && z.VlanId == vlanId),
                           It.IsAny <CancellationToken>()))
            .Returns((string sKey, BgpPeeringAccessType atype, BgpPeeringNewParameters param, CancellationToken cancellation) => t);
            client.SetupGet(f => f.BgpPeering).Returns(bgpMock.Object);

            NewAzureBGPPeeringCommand cmdlet = new NewAzureBGPPeeringCommand()
            {
                ServiceKey          = 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.AreEqual(expected.BgpPeering.State, actual.State);
            Assert.AreEqual(expected.BgpPeering.PrimaryAzurePort, actual.PrimaryAzurePort);
        }
        /// <summary>
        /// The Get Bgp Peering operation retrieves the bgp peering for the
        /// dedicated circuit with the specified service key.
        /// </summary>
        /// <param name='serviceKey'>
        /// The servicee key representing the dedicated circuit.
        /// </param>
        /// <param name='accessType'>
        /// Whether the peering is private or public.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Bgp Peering Operation Response.
        /// </returns>
        public async Task <BgpPeeringGetResponse> GetAsync(string serviceKey, BgpPeeringAccessType accessType, CancellationToken cancellationToken)
        {
            // Validate
            if (serviceKey == null)
            {
                throw new ArgumentNullException("serviceKey");
            }

            // Tracing
            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("accessType", accessType);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/networking/dedicatedcircuits/" + serviceKey + "/bgppeerings/" + accessType + "?api-version=1.0";

            // 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.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    BgpPeeringGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new BgpPeeringGetResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement bgpPeeringElement = responseDoc.Element(XName.Get("BgpPeering", "http://schemas.microsoft.com/windowsazure"));
                    if (bgpPeeringElement != null)
                    {
                        AzureBgpPeering bgpPeeringInstance = new AzureBgpPeering();
                        result.BgpPeering = bgpPeeringInstance;

                        XElement azureAsnElement = bgpPeeringElement.Element(XName.Get("AzureAsn", "http://schemas.microsoft.com/windowsazure"));
                        if (azureAsnElement != null)
                        {
                            uint azureAsnInstance = uint.Parse(azureAsnElement.Value, CultureInfo.InvariantCulture);
                            bgpPeeringInstance.AzureAsn = azureAsnInstance;
                        }

                        XElement peerAsnElement = bgpPeeringElement.Element(XName.Get("PeerAsn", "http://schemas.microsoft.com/windowsazure"));
                        if (peerAsnElement != null)
                        {
                            uint peerAsnInstance = uint.Parse(peerAsnElement.Value, CultureInfo.InvariantCulture);
                            bgpPeeringInstance.PeerAsn = peerAsnInstance;
                        }

                        XElement primaryAzurePortElement = bgpPeeringElement.Element(XName.Get("PrimaryAzurePort", "http://schemas.microsoft.com/windowsazure"));
                        if (primaryAzurePortElement != null)
                        {
                            string primaryAzurePortInstance = primaryAzurePortElement.Value;
                            bgpPeeringInstance.PrimaryAzurePort = primaryAzurePortInstance;
                        }

                        XElement primaryPeerSubnetElement = bgpPeeringElement.Element(XName.Get("PrimaryPeerSubnet", "http://schemas.microsoft.com/windowsazure"));
                        if (primaryPeerSubnetElement != null)
                        {
                            string primaryPeerSubnetInstance = primaryPeerSubnetElement.Value;
                            bgpPeeringInstance.PrimaryPeerSubnet = primaryPeerSubnetInstance;
                        }

                        XElement secondaryAzurePortElement = bgpPeeringElement.Element(XName.Get("SecondaryAzurePort", "http://schemas.microsoft.com/windowsazure"));
                        if (secondaryAzurePortElement != null)
                        {
                            string secondaryAzurePortInstance = secondaryAzurePortElement.Value;
                            bgpPeeringInstance.SecondaryAzurePort = secondaryAzurePortInstance;
                        }

                        XElement secondaryPeerSubnetElement = bgpPeeringElement.Element(XName.Get("SecondaryPeerSubnet", "http://schemas.microsoft.com/windowsazure"));
                        if (secondaryPeerSubnetElement != null)
                        {
                            string secondaryPeerSubnetInstance = secondaryPeerSubnetElement.Value;
                            bgpPeeringInstance.SecondaryPeerSubnet = secondaryPeerSubnetInstance;
                        }

                        XElement stateElement = bgpPeeringElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                        if (stateElement != null)
                        {
                            BGPPeeringState stateInstance = (BGPPeeringState)Enum.Parse(typeof(BGPPeeringState), stateElement.Value, false);
                            bgpPeeringInstance.State = stateInstance;
                        }

                        XElement vlanIdElement = bgpPeeringElement.Element(XName.Get("VlanId", "http://schemas.microsoft.com/windowsazure"));
                        if (vlanIdElement != null)
                        {
                            uint vlanIdInstance = uint.Parse(vlanIdElement.Value, CultureInfo.InvariantCulture);
                            bgpPeeringInstance.VlanId = vlanIdInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }