|
22 | 22 | using System.Collections;
|
23 | 23 | using Microsoft.Azure.Commands.Tags.Model;
|
24 | 24 | using System.Collections.Generic;
|
| 25 | +using System.Net.Http; |
| 26 | +using Microsoft.Rest.Azure; |
| 27 | +using Microsoft.Azure.Management.Network.Models; |
| 28 | +using Microsoft.Rest; |
| 29 | +using Microsoft.Azure.Common.Authentication; |
| 30 | +using Newtonsoft.Json; |
| 31 | +using System.Text; |
| 32 | +using System.Net.Http.Headers; |
| 33 | +using System.Net; |
| 34 | +using System.Linq; |
| 35 | +using System.Threading.Tasks; |
| 36 | +using System.Threading; |
| 37 | +using Microsoft.Azure.Management.Internal.Resources.Models; |
25 | 38 |
|
26 | 39 | namespace Microsoft.Azure.Commands.Network
|
27 | 40 | {
|
@@ -65,10 +78,164 @@ public override void ExecuteCmdlet()
|
65 | 78 | vpnClientParams.ProcessorArchitecture = this.ProcessorArchitecture;
|
66 | 79 | var vnetVpnClientParametersModel = Mapper.Map<MNM.VpnClientParameters>(vpnClientParams);
|
67 | 80 |
|
68 |
| - string packageUrl = this.VirtualNetworkGatewayClient.Generatevpnclientpackage(ResourceGroupName, VirtualNetworkGatewayName, vnetVpnClientParametersModel); |
| 81 | + //TODO:- This code is added just for current release of P2S feature as Generatevpnclientpackage API is broken & need to be fixed on server side as well as in overall Poweshell flow |
| 82 | + //string packageUrl = this.VirtualNetworkGatewayClient.Generatevpnclientpackage(ResourceGroupName, VirtualNetworkGatewayName, vnetVpnClientParametersModel); |
| 83 | + string packageUrl = Generatevpnclientpackage(ResourceGroupName, VirtualNetworkGatewayName, vnetVpnClientParametersModel); |
69 | 84 |
|
70 | 85 | WriteObject(packageUrl);
|
71 | 86 | }
|
| 87 | + |
| 88 | + public string Generatevpnclientpackage(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) |
| 89 | + { |
| 90 | + return Task.Factory.StartNew(() => GeneratevpnclientpackageAsync(resourceGroupName, virtualNetworkGatewayName, parameters)).Unwrap().GetAwaiter().GetResult(); |
| 91 | + } |
| 92 | + |
| 93 | + public async Task<string> GeneratevpnclientpackageAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) |
| 94 | + { |
| 95 | + AzureOperationResponse<string> result = await this.GeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); |
| 96 | + return result.Body; |
| 97 | + } |
| 98 | + |
| 99 | + /// <summary> |
| 100 | + /// The Generatevpnclientpackage operation generates Vpn client package for |
| 101 | + /// P2S client of the virtual network gateway in the specified resource group |
| 102 | + /// through Network resource provider. |
| 103 | + /// </summary> |
| 104 | + /// <param name='resourceGroupName'> |
| 105 | + /// The name of the resource group. |
| 106 | + /// </param> |
| 107 | + /// <param name='virtualNetworkGatewayName'> |
| 108 | + /// The name of the virtual network gateway. |
| 109 | + /// </param> |
| 110 | + /// <param name='parameters'> |
| 111 | + /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn |
| 112 | + /// client package operation through Network resource provider. |
| 113 | + /// </param> |
| 114 | + /// <param name='customHeaders'> |
| 115 | + /// Headers that will be added to request. |
| 116 | + /// </param> |
| 117 | + /// <param name='cancellationToken'> |
| 118 | + /// The cancellation token. |
| 119 | + /// </param> |
| 120 | + public async Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) |
| 121 | + { |
| 122 | + #region 1. Send Async request to generate vpn client package |
| 123 | + |
| 124 | + // 1. Send Async request to generate vpn client package |
| 125 | + string baseUrl = this.NetworkClient.NetworkManagementClient.BaseUri.ToString(); |
| 126 | + string apiVersion = this.NetworkClient.NetworkManagementClient.ApiVersion; |
| 127 | + |
| 128 | + if (resourceGroupName == null) |
| 129 | + { |
| 130 | + throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); |
| 131 | + } |
| 132 | + if (virtualNetworkGatewayName == null) |
| 133 | + { |
| 134 | + throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayName"); |
| 135 | + } |
| 136 | + if (parameters == null) |
| 137 | + { |
| 138 | + throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); |
| 139 | + } |
| 140 | + |
| 141 | + // Construct URL |
| 142 | + var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualnetworkgateways/{virtualNetworkGatewayName}/generatevpnclientpackage").ToString(); |
| 143 | + url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); |
| 144 | + url = url.Replace("{virtualNetworkGatewayName}", Uri.EscapeDataString(virtualNetworkGatewayName)); |
| 145 | + url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.NetworkClient.NetworkManagementClient.SubscriptionId)); |
| 146 | + url += "?" + string.Join("&", string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); |
| 147 | + |
| 148 | + // Create HTTP transport objects |
| 149 | + HttpRequestMessage httpRequest = new HttpRequestMessage(); |
| 150 | + httpRequest.Method = new HttpMethod("POST"); |
| 151 | + httpRequest.RequestUri = new Uri(url); |
| 152 | + // Set Headers |
| 153 | + httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); |
| 154 | + |
| 155 | + // Serialize Request |
| 156 | + string requestContent = JsonConvert.SerializeObject(parameters, this.NetworkClient.NetworkManagementClient.SerializationSettings); |
| 157 | + httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); |
| 158 | + httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); |
| 159 | + |
| 160 | + // Set Credentials |
| 161 | + if (this.NetworkClient.NetworkManagementClient.Credentials != null) |
| 162 | + { |
| 163 | + cancellationToken.ThrowIfCancellationRequested(); |
| 164 | + await this.NetworkClient.NetworkManagementClient.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); |
| 165 | + } |
| 166 | + // Send Request |
| 167 | + cancellationToken.ThrowIfCancellationRequested(); |
| 168 | + HttpClient httpClient = new HttpClient(); |
| 169 | + HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); |
| 170 | + |
| 171 | + HttpStatusCode statusCode = httpResponse.StatusCode; |
| 172 | + cancellationToken.ThrowIfCancellationRequested(); |
| 173 | + if ((int)statusCode != 202) |
| 174 | + { |
| 175 | + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); |
| 176 | + throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1}", |
| 177 | + statusCode, string.IsNullOrEmpty(responseContent) ? "NotAvailable" : responseContent)); |
| 178 | + } |
| 179 | + |
| 180 | + // Create Result |
| 181 | + var result = new AzureOperationResponse<string>(); |
| 182 | + result.Request = httpRequest; |
| 183 | + result.Response = httpResponse; |
| 184 | + if (httpResponse.Headers.Contains("x-ms-request-id")) |
| 185 | + { |
| 186 | + result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); |
| 187 | + } |
| 188 | + else |
| 189 | + { |
| 190 | + throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation Failed as no valid status code received in response!")); |
| 191 | + } |
| 192 | + |
| 193 | + string operationId = result.RequestId; |
| 194 | + #endregion |
| 195 | + |
| 196 | + #region 2. Wait for Async operation to succeed |
| 197 | + |
| 198 | + Thread.Sleep(TimeSpan.FromSeconds(60)); |
| 199 | + |
| 200 | + // 2. Wait for Async operation to succeed |
| 201 | + var locationResultsUrl = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/westus.validation/operationResults/{operationId}").ToString(); |
| 202 | + locationResultsUrl = locationResultsUrl.Replace("{operationId}", Uri.EscapeDataString(operationId)); |
| 203 | + locationResultsUrl = locationResultsUrl.Replace("{subscriptionId}", Uri.EscapeDataString(this.NetworkClient.NetworkManagementClient.SubscriptionId)); |
| 204 | + locationResultsUrl += "?" + string.Join("&", string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); |
| 205 | + HttpRequestMessage newHttpRequest = new HttpRequestMessage(); |
| 206 | + newHttpRequest.Method = new HttpMethod("GET"); |
| 207 | + newHttpRequest.RequestUri = new Uri(locationResultsUrl); |
| 208 | + |
| 209 | + if (this.NetworkClient.NetworkManagementClient.Credentials != null) |
| 210 | + { |
| 211 | + cancellationToken.ThrowIfCancellationRequested(); |
| 212 | + await this.NetworkClient.NetworkManagementClient.Credentials.ProcessHttpRequestAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); |
| 213 | + } |
| 214 | + HttpResponseMessage newHttpResponse = await httpClient.SendAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); |
| 215 | + |
| 216 | + if ((int)newHttpResponse.StatusCode != 200) |
| 217 | + { |
| 218 | + if (!string.IsNullOrEmpty(newHttpResponse.Content.ReadAsStringAsync().Result)) |
| 219 | + { |
| 220 | + result.Body = newHttpResponse.Content.ReadAsStringAsync().Result; |
| 221 | + } |
| 222 | + else |
| 223 | + { |
| 224 | + string newResponseContent = await newHttpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); |
| 225 | + throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1} while retrieving the Vpnclient PackageUrl!", |
| 226 | + newHttpResponse.StatusCode, string.IsNullOrEmpty(newResponseContent) ? "NotAvailable" : newResponseContent)); |
| 227 | + } |
| 228 | + } |
| 229 | + #endregion |
| 230 | + |
| 231 | + #region 3. Get the content i.e. VPN Client package Url from locationResults |
| 232 | + |
| 233 | + // 3. Get the content i.e. VPN Client package Url from locationResults |
| 234 | + result.Body = newHttpResponse.Content.ReadAsStringAsync().Result; |
| 235 | + return result; |
| 236 | + #endregion |
| 237 | + |
| 238 | + } |
72 | 239 | }
|
73 | 240 | }
|
74 | 241 |
|
0 commit comments