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