forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert-HTML.cs
More file actions
611 lines (558 loc) · 20 KB
/
Copy pathconvert-HTML.cs
File metadata and controls
611 lines (558 loc) · 20 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Net;
using System.Text;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
///
/// Class comment
///
/// </summary>
[Cmdlet(VerbsData.ConvertTo, "Html", DefaultParameterSetName = "Page",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113290", RemotingCapability = RemotingCapability.None)]
public sealed
class ConvertToHtmlCommand : PSCmdlet
{
/// <summary>The incoming object</summary>
/// <value></value>
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = value;
}
}
private PSObject _inputObject;
/// <summary>
/// The list of properties to display
/// These take the form of an MshExpression
/// </summary>
/// <value></value>
[Parameter(Position = 0)]
public object[] Property
{
get
{
return _property;
}
set
{
_property = value;
}
}
private object[] _property;
/// <summary>
/// Text to go after the opening body tag
/// and before the table
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 3)]
public string[] Body
{
get
{
return _body;
}
set
{
_body = value;
}
}
private string[] _body;
/// <summary>
/// Text to go into the head section
/// of the html doc
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 1)]
public string[] Head
{
get
{
return _head;
}
set
{
_head = value;
}
}
private string[] _head;
/// <summary>
/// The string for the title tag
/// The title is also placed in the body of the document
/// before the table between h3 tags
/// If the -Head parameter is used, this parameter has no
/// effect.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "Page", Position = 2)]
[ValidateNotNullOrEmpty]
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
private string _title = "HTML TABLE";
/// <summary>
/// This specifies whether the objects should
/// be rendered as an HTML TABLE or
/// HTML LIST
/// </summary>
/// <value></value>
[Parameter]
[ValidateNotNullOrEmpty]
[ValidateSet("Table", "List")]
public string As
{
get
{
return _as;
}
set
{
_as = value;
}
}
private string _as = "Table";
/// <summary>
/// This specifies a full or partial URI
/// for the CSS information.
/// The html should reference the css file specified
/// </summary>
[Parameter(ParameterSetName = "Page")]
[Alias("cu", "uri")]
[ValidateNotNullOrEmpty]
public Uri CssUri
{
get
{
return _cssuri;
}
set
{
_cssuri = value;
_cssuriSpecified = true;
}
}
private Uri _cssuri;
private bool _cssuriSpecified;
/// <summary>
/// When this switch is specified generate only the
/// HTML representation of the incoming object
/// without the HTML,HEAD,TITLE,BODY,etc tags.
/// </summary>
[Parameter(ParameterSetName = "Fragment")]
[ValidateNotNullOrEmpty]
public SwitchParameter Fragment
{
get
{
return _fragment;
}
set
{
_fragment = value;
}
}
private SwitchParameter _fragment;
/// <summary>
/// Specifies the text to include prior the
/// closing body tag of the HTML output
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PostContent
{
get
{
return _postContent;
}
set
{
_postContent = value;
}
}
private string[] _postContent;
/// <summary>
/// Specifies the text to include after the
/// body tag of the HTML output
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PreContent
{
get
{
return _preContent;
}
set
{
_preContent = value;
}
}
private string[] _preContent;
/// <summary>
/// definitions for hash table keys
/// </summary>
internal static class ConvertHTMLParameterDefinitionKeys
{
internal const string LabelEntryKey = "label";
internal const string AlignmentEntryKey = "alignment";
internal const string WidthEntryKey = "width";
}
/// <summary>
/// This allows for @{e='foo';label='bar';alignment='center';width='20'}
/// </summary>
internal class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition
{
protected override void SetEntries()
{
this.hashEntries.Add(new ExpressionEntryDefinition());
this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, new Type[] { typeof(string) }));
this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, new Type[] { typeof(string) }));
this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, new Type[] { typeof(string) }));
}
}
/// <summary>
/// Create a list of MshParameter from properties
/// </summary>
/// <param name="properties">can be a string, ScriptBlock, or Hashtable</param>
/// <returns></returns>
private List<MshParameter> ProcessParameter(object[] properties)
{
TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
ParameterProcessor processor =
new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition());
if (properties == null)
{
properties = new object[] { "*" };
}
return processor.ProcessParameters(properties, invocationContext);
}
/// <summary>
/// Resolve all wildcards in user input Property into resolvedNameMshParameters
/// </summary>
private void InitializeResolvedNameMshParameters()
{
// temp list of properties with wildcards resolved
ArrayList resolvedNameProperty = new ArrayList();
foreach (MshParameter p in _propertyMshParameterList)
{
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
List<MshExpression> resolvedNames = ex.ResolveNames(_inputObject);
foreach (MshExpression resolvedName in resolvedNames)
{
Hashtable ht = CreateAuxPropertyHT(label, alignment, width);
ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString());
resolvedNameProperty.Add(ht);
}
}
_resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray());
}
private static Hashtable CreateAuxPropertyHT(
string label,
string alignment,
string width)
{
Hashtable ht = new Hashtable();
if (label != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label);
}
if (alignment != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment);
}
if (width != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width);
}
return ht;
}
/// <summary>
/// calls ToString. If an exception occurs, eats it and return string.Empty
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private static string SafeToString(object obj)
{
if (obj == null)
{
return "";
}
try
{
return obj.ToString();
}
catch (Exception)
{
// eats exception if safe
}
return "";
}
/// <summary>
///
/// </summary>
protected override void BeginProcessing()
{
//ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
{
ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
ThrowTerminatingError(er);
}
_propertyMshParameterList = ProcessParameter(_property);
if (!String.IsNullOrEmpty(_title))
{
WebUtility.HtmlEncode(_title);
}
// This first line ensures w3c validation will succeed. However we are not specifying
// an encoding in the HTML because we don't know where the text will be written and
// if a particular encoding will be used.
if (!_fragment)
{
WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
WriteObject("<head>");
WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
if (_cssuriSpecified)
{
WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
}
WriteObject("</head><body>");
if (_body != null)
{
WriteObject(_body, true);
}
}
if (_preContent != null)
{
WriteObject(_preContent, true);
}
WriteObject("<table>");
_isTHWritten = false;
_propertyCollector = new StringCollection();
}
/// <summary>
/// Reads Width and Alignment from Property and write Col tags
/// </summary>
/// <param name="mshParams"></param>
private void WriteColumns(List<MshParameter> mshParams)
{
StringBuilder COLTag = new StringBuilder();
COLTag.Append("<colgroup>");
foreach (MshParameter p in mshParams)
{
COLTag.Append("<col");
string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
if (width != null)
{
COLTag.Append(" width = \"");
COLTag.Append(width);
COLTag.Append("\"");
}
string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
if (alignment != null)
{
COLTag.Append(" align = \"");
COLTag.Append(alignment);
COLTag.Append("\"");
}
COLTag.Append("/>");
}
COLTag.Append("</colgroup>");
// The columngroup and col nodes will be printed in a single line.
WriteObject(COLTag.ToString());
}
/// <summary>
/// Writes the list entries when the As parameter has value List
/// </summary>
private void WriteListEntry()
{
foreach (MshParameter p in _resolvedNameMshParameters)
{
StringBuilder Listtag = new StringBuilder();
Listtag.Append("<tr><td>");
//for writing the property name
WritePropertyName(Listtag, p);
Listtag.Append(":");
Listtag.Append("</td>");
//for writing the property value
Listtag.Append("<td>");
WritePropertyValue(Listtag, p);
Listtag.Append("</td></tr>");
WriteObject(Listtag.ToString());
}
}
/// <summary>
/// To write the Property name
/// </summary>
private void WritePropertyName(StringBuilder Listtag, MshParameter p)
{
//for writing the property name
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
if (label != null)
{
Listtag.Append(label);
}
else
{
MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
Listtag.Append(ex.ToString());
}
}
/// <summary>
/// To write the Property value
/// </summary>
private void WritePropertyValue(StringBuilder Listtag, MshParameter p)
{
MshExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
// get the value of the property
List<MshExpressionResult> resultList = exValue.GetValues(_inputObject);
foreach (MshExpressionResult result in resultList)
{
// create comma sep list for multiple results
if (result.Result != null)
{
string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result));
Listtag.Append(htmlEncodedResult);
}
Listtag.Append(", ");
}
if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal))
{
Listtag.Remove(Listtag.Length - 2, 2);
}
}
/// <summary>
/// To write the Table header for the object property names
/// </summary>
private void WriteTableHeader(StringBuilder THtag, List<MshParameter> resolvedNameMshParameters)
{
//write the property names
foreach (MshParameter p in resolvedNameMshParameters)
{
THtag.Append("<th>");
WritePropertyName(THtag, p);
THtag.Append("</th>");
}
}
/// <summary>
/// To write the Table row for the object property values
/// </summary>
private void WriteTableRow(StringBuilder TRtag, List<MshParameter> resolvedNameMshParameters)
{
//write the property values
foreach (MshParameter p in resolvedNameMshParameters)
{
TRtag.Append("<td>");
WritePropertyValue(TRtag, p);
TRtag.Append("</td>");
}
}
//count of the objects
private int _numberObjects = 0;
/// <summary>
///
///
/// </summary>
protected override void ProcessRecord()
{
// writes the table headers
// it is not in BeginProcessing because the first inputObject is needed for
// the number of columns and column name
if (_inputObject == null || _inputObject == AutomationNull.Value)
{
return;
}
_numberObjects++;
if (!_isTHWritten)
{
InitializeResolvedNameMshParameters();
if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0)
{
return;
}
//if the As parameter is given as List
if (_as.Equals("List", StringComparison.OrdinalIgnoreCase))
{
//if more than one object,write the horizontal rule to put visual separator
if (_numberObjects > 1)
WriteObject("<tr><td><hr></td></tr>");
WriteListEntry();
}
else //if the As parameter is Table, first we have to write the property names
{
WriteColumns(_resolvedNameMshParameters);
StringBuilder THtag = new StringBuilder("<tr>");
//write the table header
WriteTableHeader(THtag, _resolvedNameMshParameters);
THtag.Append("</tr>");
WriteObject(THtag.ToString());
_isTHWritten = true;
}
}
//if the As parameter is Table, write the property values
if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase))
{
StringBuilder TRtag = new StringBuilder("<tr>");
//write the table row
WriteTableRow(TRtag, _resolvedNameMshParameters);
TRtag.Append("</tr>");
WriteObject(TRtag.ToString());
}
}
/// <summary>
///
/// </summary>
protected override void EndProcessing()
{
//if fragment,end with table
WriteObject("</table>");
if (_postContent != null)
WriteObject(_postContent, true);
//if not fragment end with body and html also
if (!_fragment)
{
WriteObject("</body></html>");
}
}
#region private
/// <summary>
/// list of incoming objects to compare
/// </summary>
private bool _isTHWritten;
private StringCollection _propertyCollector;
private List<MshParameter> _propertyMshParameterList;
private List<MshParameter> _resolvedNameMshParameters;
//private string ResourcesBaseName = "ConvertHTMLStrings";
#endregion private
}
}