forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebServiceProxy.cs
More file actions
473 lines (427 loc) · 17 KB
/
Copy pathWebServiceProxy.cs
File metadata and controls
473 lines (427 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/********************************************************************--
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Web.Services.Description;
using System.Web.Services.Discovery;
using System.Management;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using Dbg = System.Management.Automation;
using System.Runtime.InteropServices;
using System.Resources;
using Microsoft.Win32;
using System.Text.RegularExpressions;
namespace Microsoft.PowerShell.Commands
{
#region New-WebServiceProxy
/// <summary>
/// Cmdlet for new-WebService Proxy
/// </summary>
[Cmdlet(VerbsCommon.New, "WebServiceProxy", DefaultParameterSetName = "NoCredentials", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135238")]
public sealed class NewWebServiceProxy : PSCmdlet
{
#region Parameters
/// <summary>
/// URI of the web service
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[ValidateNotNullOrEmpty]
[Alias("WL", "WSDL", "Path")]
public System.Uri Uri
{
get { return _uri; }
set
{
_uri = value;
}
}
private System.Uri _uri;
/// <summary>
/// Parameter Class name
/// </summary>
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty]
[Alias("FileName", "FN")]
public string Class
{
get { return _class; }
set
{
_class = value;
}
}
private string _class;
/// <summary>
/// namespace
/// </summary>
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty]
[Alias("NS")]
public string Namespace
{
get { return _namespace; }
set
{
_namespace = value;
}
}
private string _namespace;
/// <summary>
/// Credential
/// </summary>
[Parameter(ParameterSetName = "Credential")]
[ValidateNotNullOrEmpty]
[Credential]
[Alias("Cred")]
public PSCredential Credential
{
get { return _credential; }
set
{
_credential = value;
}
}
private PSCredential _credential;
/// <summary>
/// use default credential..
/// </summary>
[Parameter(ParameterSetName = "UseDefaultCredential")]
[ValidateNotNull]
[Alias("UDC")]
public SwitchParameter UseDefaultCredential
{
get { return _usedefaultcredential; }
set
{
_usedefaultcredential = value;
}
}
private SwitchParameter _usedefaultcredential;
#endregion
#region overrides
/// <summary>
/// Cache for storing URIs.
/// </summary>
private static Dictionary<Uri, string> s_uriCache = new Dictionary<Uri, string>();
/// <summary>
/// Cache for storing sourcecodehashes.
/// </summary>
private static Dictionary<int, object> s_srccodeCache = new Dictionary<int, object>();
/// <summary>
/// holds the hash code of the source generated.
/// </summary>
private int _sourceHash;
/// <summary>
/// Random class
/// </summary>
private object _cachelock = new object();
private static Random s_rnd = new Random();
/// <summary>
/// BeginProcessing code
/// </summary>
protected override void BeginProcessing()
{
if (_uri.ToString().Trim().Length == 0)
{
Exception ex = new ArgumentException(WebServiceResources.InvalidUri);
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(er);
}
//check if system.web is available.This assembly is not available in win server core.
string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
try
{
Assembly webAssembly = Assembly.Load(AssemblyString);
}
catch (FileNotFoundException ex)
{
ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null);
er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported);
ThrowTerminatingError(er);
}
int sourceCache = 0;
lock (s_uriCache)
{
if (s_uriCache.ContainsKey(_uri))
{
//if uri is present in the cache
string ns;
s_uriCache.TryGetValue(_uri, out ns);
string[] data = ns.Split('|');
if (string.IsNullOrEmpty(_namespace))
{
if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase))
{
_namespace = data[0];
_class = data[1];
}
}
sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture);
}
}
if (string.IsNullOrEmpty(_namespace))
{
_namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName();
}
//if class is null,generate a name for it
if (string.IsNullOrEmpty(_class))
{
_class = "MyClass" + GenerateRandomName();
}
Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class);
if (webserviceproxy == null)
return;
Object instance = InstantiateWebServiceProxy(webserviceproxy);
//to set the credentials into the generated webproxy Object
PropertyInfo[] pinfo = instance.GetType().GetProperties();
foreach (PropertyInfo pr in pinfo)
{
if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase))
{
if (UseDefaultCredential.IsPresent)
{
bool flag = true;
pr.SetValue(instance, flag as object, null);
}
}
if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase))
{
if (Credential != null)
{
NetworkCredential cred = Credential.GetNetworkCredential();
pr.SetValue(instance, cred as object, null);
}
}
}
//disposing the entries in a cache
//Adding to Cache
lock (s_uriCache)
{
s_uriCache.Remove(_uri);
}
if (sourceCache > 0)
{
lock (_cachelock)
{
s_srccodeCache.Remove(sourceCache);
}
}
string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) });
lock (s_uriCache)
{
s_uriCache.Add(_uri, key);
}
lock (_cachelock)
{
s_srccodeCache.Add(_sourceHash, instance);
}
WriteObject(instance, true);
}//End BeginProcessing()
#endregion
#region private
private static ulong s_sequenceNumber = 1;
private static object s_sequenceNumberLock = new object();
/// <summary>
/// Generates a random name
/// </summary>
/// <returns>string </returns>
private string GenerateRandomName()
{
string rndname = null;
string givenuri = _uri.ToString();
for (int i = 0; i < givenuri.Length; i++)
{
Int32 val = System.Convert.ToInt32(givenuri[i], CultureInfo.InvariantCulture);
if ((val >= 65 && val <= 90) || (val >= 48 && val <= 57) || (val >= 97 && val <= 122))
{
rndname += givenuri[i];
}
else
{
rndname += "_";
}
}
string sequenceString;
lock (s_sequenceNumberLock)
{
sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture);
}
if (rndname.Length > 30)
{
return (sequenceString + rndname.Substring(rndname.Length - 30));
}
return (sequenceString + rndname);
}
/// <summary>
/// Generates the Assembly
/// </summary>
/// <param name="NameSpace"></param>
/// <param name="ClassName"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
{
DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
//if paramset is defaultcredential, set the flag in wcclient
if (_usedefaultcredential.IsPresent)
dcp.UseDefaultCredentials = true;
//if paramset is credential, assign the credentials
if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
dcp.Credentials = _credential.GetNetworkCredential();
try
{
dcp.AllowAutoRedirect = true;
dcp.DiscoverAny(_uri.ToString());
dcp.ResolveAll();
}
catch (WebException ex)
{
ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
if (ex.InnerException != null)
er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
WriteError(er);
return null;
}
catch (InvalidOperationException ex)
{
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
WriteError(er);
return null;
}
// create the namespace
CodeNamespace codeNS = new CodeNamespace();
if (!string.IsNullOrEmpty(NameSpace))
codeNS.Name = NameSpace;
//create the class and add it to the namespace
if (!string.IsNullOrEmpty(ClassName))
{
CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
codeClass.IsClass = true;
codeClass.Attributes = MemberAttributes.Public;
codeNS.Types.Add(codeClass);
}
//create a web reference to the uri docs
WebReference wref = new WebReference(dcp.Documents, codeNS);
WebReferenceCollection wrefs = new WebReferenceCollection();
wrefs.Add(wref);
//create a codecompileunit and add the namespace to it
CodeCompileUnit codecompileunit = new CodeCompileUnit();
codecompileunit.Namespaces.Add(codeNS);
WebReferenceOptions wrefOptions = new WebReferenceOptions();
wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
wrefOptions.Verbose = true;
//create a csharpprovider and compile it
CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);
StringBuilder codegenerator = new StringBuilder();
StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture);
try
{
csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
}
catch (NotImplementedException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
WriteError(er);
}
//generate the hashcode of the CodeCompileUnit
_sourceHash = codegenerator.ToString().GetHashCode();
//if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
// return the instance of th eproxy in the cache
if (s_srccodeCache.ContainsKey(_sourceHash))
{
object obj;
s_srccodeCache.TryGetValue(_sourceHash, out obj);
WriteObject(obj, true);
return null;
}
CompilerParameters options = new CompilerParameters();
CompilerResults results = null;
foreach (string warning in Warnings)
{
this.WriteWarning(warning);
}
// add the references to the required assemblies
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.Data.dll");
options.ReferencedAssemblies.Add("System.Xml.dll");
options.ReferencedAssemblies.Add("System.Web.Services.dll");
options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
options.GenerateInMemory = true;
options.TreatWarningsAsErrors = false;
options.WarningLevel = 4;
options.GenerateExecutable = false;
try
{
results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
}
catch (NotImplementedException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
WriteError(er);
}
return results.CompiledAssembly;
}
/// <summary>
/// Function to add all the assemblies required to generate the web proxy
/// </summary>
/// <param name="assembly"></param>
/// <param name="parameters"></param>
private void GetReferencedAssemblies(Assembly assembly, CompilerParameters parameters)
{
if (!parameters.ReferencedAssemblies.Contains(assembly.Location))
{
string location = Path.GetFileName(assembly.Location);
if (!parameters.ReferencedAssemblies.Contains(location))
{
parameters.ReferencedAssemblies.Add(assembly.Location);
foreach (AssemblyName referencedAssembly in assembly.GetReferencedAssemblies())
GetReferencedAssemblies(Assembly.Load(referencedAssembly.FullName), parameters);
}
}
}
/// <summary>
/// Instantiates the object
/// if a type of WebServiceBindingAttribute is not found, throw an exception
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
private object InstantiateWebServiceProxy(Assembly assembly)
{
Type proxyType = null;
//loop through the types of the assembly and identify the type having
// a web service binding attribute
foreach (Type type in assembly.GetTypes())
{
Object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false);
if (obj.Length > 0)
{
proxyType = type;
break;
}
if (proxyType != null) break;
}
System.Management.Automation.Diagnostics.Assert(
proxyType != null,
"Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)");
return assembly.CreateInstance(proxyType.ToString());
}
#endregion
}//end class
#endregion
}//Microsoft.Powershell.commands