16
16
using Microsoft . Azure . Management . Network ;
17
17
using Microsoft . Azure . Common . Authentication . Models ;
18
18
using Microsoft . Azure . Common . Authentication ;
19
+ using Microsoft . Azure . Management . Network . Models ;
20
+ using System . Threading . Tasks ;
21
+ using System . Threading ;
22
+ using Microsoft . Rest . Azure ;
23
+ using System . Collections . Generic ;
24
+ using Microsoft . Rest ;
25
+ using System . Net . Http ;
26
+ using Newtonsoft . Json ;
27
+ using System . Text ;
28
+ using System . Net . Http . Headers ;
29
+ using System . Net ;
30
+ using System . Linq ;
31
+
19
32
namespace Microsoft . Azure . Commands . Network
20
33
{
21
34
public partial class NetworkClient
@@ -41,5 +54,177 @@ public NetworkClient(INetworkManagementClient NetworkManagementClient)
41
54
public NetworkClient ( )
42
55
{
43
56
}
57
+
58
+ public string Generatevpnclientpackage ( string resourceGroupName , string virtualNetworkGatewayName , VpnClientParameters parameters )
59
+ {
60
+ return Task . Factory . StartNew ( ( ) => GeneratevpnclientpackageAsync ( resourceGroupName , virtualNetworkGatewayName , parameters ) ) . Unwrap ( ) . GetAwaiter ( ) . GetResult ( ) ;
61
+ }
62
+
63
+ public async Task < string > GeneratevpnclientpackageAsync ( string resourceGroupName , string virtualNetworkGatewayName , VpnClientParameters parameters ,
64
+ CancellationToken cancellationToken = default ( CancellationToken ) )
65
+ {
66
+ AzureOperationResponse < string > result = await this . GeneratevpnclientpackageWithHttpMessagesAsync ( resourceGroupName , virtualNetworkGatewayName ,
67
+ parameters , null , cancellationToken ) . ConfigureAwait ( false ) ;
68
+ return result . Body ;
69
+ }
70
+
71
+ /// <summary>
72
+ /// The Generatevpnclientpackage operation generates Vpn client package for
73
+ /// P2S client of the virtual network gateway in the specified resource group
74
+ /// through Network resource provider.
75
+ /// </summary>
76
+ /// <param name='resourceGroupName'>
77
+ /// The name of the resource group.
78
+ /// </param>
79
+ /// <param name='virtualNetworkGatewayName'>
80
+ /// The name of the virtual network gateway.
81
+ /// </param>
82
+ /// <param name='parameters'>
83
+ /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn
84
+ /// client package operation through Network resource provider.
85
+ /// </param>
86
+ /// <param name='customHeaders'>
87
+ /// Headers that will be added to request.
88
+ /// </param>
89
+ /// <param name='cancellationToken'>
90
+ /// The cancellation token.
91
+ /// </param>
92
+ public async Task < AzureOperationResponse < string > > GeneratevpnclientpackageWithHttpMessagesAsync ( string resourceGroupName , string virtualNetworkGatewayName ,
93
+ VpnClientParameters parameters , Dictionary < string , List < string > > customHeaders = null , CancellationToken cancellationToken = default ( CancellationToken ) )
94
+ {
95
+ #region 1. Send Async request to generate vpn client package
96
+
97
+ // 1. Send Async request to generate vpn client package
98
+ string baseUrl = NetworkManagementClient . BaseUri . ToString ( ) ;
99
+ string apiVersion = NetworkManagementClient . ApiVersion ;
100
+
101
+ if ( resourceGroupName == null )
102
+ {
103
+ throw new ValidationException ( ValidationRules . CannotBeNull , "resourceGroupName" ) ;
104
+ }
105
+ if ( virtualNetworkGatewayName == null )
106
+ {
107
+ throw new ValidationException ( ValidationRules . CannotBeNull , "virtualNetworkGatewayName" ) ;
108
+ }
109
+ if ( parameters == null )
110
+ {
111
+ throw new ValidationException ( ValidationRules . CannotBeNull , "parameters" ) ;
112
+ }
113
+
114
+ // Construct URL
115
+ var url = new Uri ( new Uri ( baseUrl + ( baseUrl . EndsWith ( "/" ) ? "" : "/" ) ) , "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/" +
116
+ "providers/Microsoft.Network/virtualnetworkgateways/{virtualNetworkGatewayName}/generatevpnclientpackage" ) . ToString ( ) ;
117
+ url = url . Replace ( "{resourceGroupName}" , Uri . EscapeDataString ( resourceGroupName ) ) ;
118
+ url = url . Replace ( "{virtualNetworkGatewayName}" , Uri . EscapeDataString ( virtualNetworkGatewayName ) ) ;
119
+ url = url . Replace ( "{subscriptionId}" , Uri . EscapeDataString ( NetworkManagementClient . SubscriptionId ) ) ;
120
+ url += "?" + string . Join ( "&" , string . Format ( "api-version={0}" , Uri . EscapeDataString ( apiVersion ) ) ) ;
121
+
122
+ // Create HTTP transport objects
123
+ HttpRequestMessage httpRequest = new HttpRequestMessage ( ) ;
124
+ httpRequest . Method = new HttpMethod ( "POST" ) ;
125
+ httpRequest . RequestUri = new Uri ( url ) ;
126
+ // Set Headers
127
+ httpRequest . Headers . TryAddWithoutValidation ( "x-ms-client-request-id" , Guid . NewGuid ( ) . ToString ( ) ) ;
128
+
129
+ // Serialize Request
130
+ string requestContent = JsonConvert . SerializeObject ( parameters , NetworkManagementClient . SerializationSettings ) ;
131
+ httpRequest . Content = new StringContent ( requestContent , Encoding . UTF8 ) ;
132
+ httpRequest . Content . Headers . ContentType = MediaTypeHeaderValue . Parse ( "application/json; charset=utf-8" ) ;
133
+
134
+ // Set Credentials
135
+ if ( NetworkManagementClient . Credentials != null )
136
+ {
137
+ cancellationToken . ThrowIfCancellationRequested ( ) ;
138
+ await NetworkManagementClient . Credentials . ProcessHttpRequestAsync ( httpRequest , cancellationToken ) . ConfigureAwait ( false ) ;
139
+ }
140
+ // Send Request
141
+ cancellationToken . ThrowIfCancellationRequested ( ) ;
142
+ HttpClient httpClient = new HttpClient ( ) ;
143
+ HttpResponseMessage httpResponse = await httpClient . SendAsync ( httpRequest , cancellationToken ) . ConfigureAwait ( false ) ;
144
+
145
+ HttpStatusCode statusCode = httpResponse . StatusCode ;
146
+ cancellationToken . ThrowIfCancellationRequested ( ) ;
147
+ if ( ( int ) statusCode != 202 )
148
+ {
149
+ string responseContent = await httpResponse . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ;
150
+ throw new Exception ( string . Format ( "Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1}" ,
151
+ statusCode , string . IsNullOrEmpty ( responseContent ) ? "NotAvailable" : responseContent ) ) ;
152
+ }
153
+
154
+ // Create Result
155
+ var result = new AzureOperationResponse < string > ( ) ;
156
+ result . Request = httpRequest ;
157
+ result . Response = httpResponse ;
158
+ if ( httpResponse . Headers . Contains ( "x-ms-request-id" ) )
159
+ {
160
+ result . RequestId = httpResponse . Headers . GetValues ( "x-ms-request-id" ) . FirstOrDefault ( ) ;
161
+ }
162
+ else
163
+ {
164
+ throw new Exception ( string . Format ( "Get-AzureRmVpnClientPackage Operation Failed as no valid status code received in response!" ) ) ;
165
+ }
166
+
167
+ string operationId = result . RequestId ;
168
+ #endregion
169
+
170
+ #region 2. Wait for Async operation to succeed and then Get the content i.e. VPN Client package Url from locationResults
171
+ //Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(60000);
172
+
173
+ // 2. Wait for Async operation to succeed
174
+ var locationResultsUrl = new Uri ( new Uri ( baseUrl + ( baseUrl . EndsWith ( "/" ) ? "" : "/" ) ) , "subscriptions/{subscriptionId}/providers/Microsoft.Network/" +
175
+ "locations/westus.validation/operationResults/{operationId}" ) . ToString ( ) ;
176
+ locationResultsUrl = locationResultsUrl . Replace ( "{operationId}" , Uri . EscapeDataString ( operationId ) ) ;
177
+ locationResultsUrl = locationResultsUrl . Replace ( "{subscriptionId}" , Uri . EscapeDataString ( NetworkManagementClient . SubscriptionId ) ) ;
178
+ locationResultsUrl += "?" + string . Join ( "&" , string . Format ( "api-version={0}" , Uri . EscapeDataString ( apiVersion ) ) ) ;
179
+
180
+ DateTime startTime = DateTime . UtcNow ;
181
+ DateTime giveUpAt = DateTime . UtcNow . AddMinutes ( 3 ) ;
182
+
183
+ // Send the Get locationResults request for operaitonId till either we get StatusCode 200 or it time outs (3 minutes in this case)
184
+ while ( true )
185
+ {
186
+ HttpRequestMessage newHttpRequest = new HttpRequestMessage ( ) ;
187
+ newHttpRequest . Method = new HttpMethod ( "GET" ) ;
188
+ newHttpRequest . RequestUri = new Uri ( locationResultsUrl ) ;
189
+
190
+ if ( NetworkManagementClient . Credentials != null )
191
+ {
192
+ cancellationToken . ThrowIfCancellationRequested ( ) ;
193
+ await NetworkManagementClient . Credentials . ProcessHttpRequestAsync ( newHttpRequest , cancellationToken ) . ConfigureAwait ( false ) ;
194
+ }
195
+
196
+ HttpResponseMessage newHttpResponse = await httpClient . SendAsync ( newHttpRequest , cancellationToken ) . ConfigureAwait ( false ) ;
197
+
198
+ if ( ( int ) newHttpResponse . StatusCode != 200 )
199
+ {
200
+ if ( DateTime . UtcNow > giveUpAt )
201
+ {
202
+ if ( ! string . IsNullOrEmpty ( newHttpResponse . Content . ReadAsStringAsync ( ) . Result ) )
203
+ {
204
+ result . Body = newHttpResponse . Content . ReadAsStringAsync ( ) . Result ;
205
+ }
206
+ else
207
+ {
208
+ string newResponseContent = await newHttpResponse . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ;
209
+ throw new Exception ( string . Format ( "Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1} while retrieving " +
210
+ "the Vpnclient PackageUrl!" ,
211
+ newHttpResponse . StatusCode , string . IsNullOrEmpty ( newResponseContent ) ? "NotAvailable" : newResponseContent ) ) ;
212
+ }
213
+ }
214
+ else
215
+ {
216
+ // Wait for 15 seconds before retrying
217
+ Microsoft . WindowsAzure . Commands . Utilities . Common . TestMockSupport . Delay ( 15000 ) ;
218
+ }
219
+ }
220
+ else
221
+ {
222
+ // Get the content i.e.VPN Client package Url from locationResults
223
+ result . Body = newHttpResponse . Content . ReadAsStringAsync ( ) . Result ;
224
+ return result ;
225
+ }
226
+ }
227
+ #endregion
228
+ }
44
229
}
45
230
}
0 commit comments