-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathErrorFormatter.cs
2047 lines (1701 loc) · 79.4 KB
/
ErrorFormatter.cs
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="ErrorFormatter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*********************************
Class hierarchy
ErrorFormatter (abstract)
UnhandledErrorFormatter
SecurityErrorFormatter
UseLastUnhandledErrorFormatter
TemplatedMailRuntimeErrorFormatter
PageNotFoundErrorFormatter
PageForbiddenErrorFormatter
GenericApplicationErrorFormatter
FormatterWithFileInfo (abstract)
ParseErrorFormatter
ConfigErrorFormatter
DynamicCompileErrorFormatter
TemplatedMailCompileErrorFormatter
UrlAuthFailedErrorFormatter
TraceHandlerErrorFormatter
TemplatedMailErrorFormatterGenerator
AuthFailedErrorFormatter
FileAccessFailedErrorFormatter
PassportAuthFailedErrorFormatter
**********************************/
/*
* Object used to put together ASP.NET HTML error messages
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web {
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.IO;
using System.Globalization;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Util;
using System.Web.Compilation;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.CodeDom.Compiler;
using System.ComponentModel;
using Debug=System.Web.Util.Debug;
using System.Web.Management;
using System.Configuration;
using System.Security;
using System.Security.Permissions;
/*
* This is an abstract base class from which we derive other formatters.
*/
internal abstract class ErrorFormatter {
private StringCollection _adaptiveMiscContent;
private StringCollection _adaptiveStackTrace;
protected bool _dontShowVersion = false;
internal bool _fusionLogWritten = false;
internal const string startExpandableBlock =
"<br><div class=\"expandable\" onclick=\"OnToggleTOCLevel1('{0}')\">" +
"{1}" +
":</div>\r\n" +
"<div id=\"{0}\" style=\"display: none;\">\r\n" +
" <br>";
internal const string startColoredSquare =
" <table width=100% bgcolor=\"#ffffcc\">\r\n" +
" <tr>\r\n" +
" <td>\r\n" +
" <code>";
internal const string endColoredSquare =
" </code>\r\n\r\n" +
" </td>\r\n" +
" </tr>\r\n" +
" </table>\r\n\r\n";
internal const string endExpandableBlock =
" \r\n\r\n" +
"</div>\r\n";
internal const string toggleScript = @"
<script type=""text/javascript"">
function OnToggleTOCLevel1(level2ID)
{
var elemLevel2 = document.getElementById(level2ID);
if (elemLevel2.style.display == 'none')
{
elemLevel2.style.display = '';
}
else {
elemLevel2.style.display = 'none';
}
}
</script>
";
protected const string BeginLeftToRightTag = "<div dir=\"ltr\">";
protected const string EndLeftToRightTag = "</div>";
internal static bool RequiresAdaptiveErrorReporting(HttpContext context)
{
// If HostingInit failed, don't try to continue, as we are not sufficiently
// initialized to execute this code (VSWhidbey 210495)
if (HttpRuntime.HostingInitFailed)
return false;
HttpRequest request = (context != null) ? context.Request : null;
if (context != null && context.WorkerRequest is System.Web.SessionState.StateHttpWorkerRequest)
return false;
// Request.Browser might throw if the configuration file has some
// bad format.
HttpBrowserCapabilities browser = null;
try {
browser = (request != null) ? request.Browser : null;
}
catch {
return false;
}
if (browser != null &&
browser["requiresAdaptiveErrorReporting"] == "true") {
return true;
}
return false;
}
private Literal CreateBreakLiteral() {
Literal breakControl = new Literal();
breakControl.Text = "<br/>";
return breakControl;
}
private Label CreateLabelFromText(String text) {
Label label = new Label();
label.Text = text;
return label;
}
// Return error message in markup using adaptive rendering of web
// controls. This would also set the corresponding headers of the
// response accordingly so content can be shown properly on devices.
// This method has been added with the same signature of
// GetHtmlErrorMessage for consistency.
internal virtual string GetAdaptiveErrorMessage(HttpContext context, bool dontShowSensitiveInfo) {
// This call will compute and set all the necessary properties of
// this instance of ErrorFormatter. Then the controls below can
// collect info from the properties. The returned html is safely
// ignored.
GetHtmlErrorMessage(dontShowSensitiveInfo);
// We need to inform the Response object that adaptive error is used
// so it can adjust the status code right before headers are written out.
// It is because some mobile devices/browsers can display a page
// content only if it is a normal response instead of response that
// has error status code.
context.Response.UseAdaptiveError = true;
try {
Page page = new ErrorFormatterPage();
page.EnableViewState = false;
HtmlForm form = new HtmlForm();
page.Controls.Add(form);
IParserAccessor formAdd = (IParserAccessor) form;
// Display a server error text with the application name
Label label = CreateLabelFromText(SR.GetString(SR.Error_Formatter_ASPNET_Error, HttpRuntime.AppDomainAppVirtualPath));
label.ForeColor = Color.Red;
label.Font.Bold = true;
label.Font.Size = FontUnit.Large;
formAdd.AddParsedSubObject(label);
formAdd.AddParsedSubObject(CreateBreakLiteral());
// Title
label = CreateLabelFromText(ErrorTitle);
label.ForeColor = Color.Maroon;
label.Font.Bold = true;
label.Font.Italic = true;
formAdd.AddParsedSubObject(label);
formAdd.AddParsedSubObject(CreateBreakLiteral());
// Description
formAdd.AddParsedSubObject(CreateLabelFromText(SR.GetString(SR.Error_Formatter_Description) + " " + Description));
formAdd.AddParsedSubObject(CreateBreakLiteral());
// Misc Title
String miscTitle = MiscSectionTitle;
if (!String.IsNullOrEmpty(miscTitle)) {
formAdd.AddParsedSubObject(CreateLabelFromText(miscTitle));
formAdd.AddParsedSubObject(CreateBreakLiteral());
}
// Misc Info
StringCollection miscContent = AdaptiveMiscContent;
if (miscContent != null && miscContent.Count > 0) {
foreach (String contentLine in miscContent) {
formAdd.AddParsedSubObject(CreateLabelFromText(contentLine));
formAdd.AddParsedSubObject(CreateBreakLiteral());
}
}
// File & line# info
String sourceFilePath = GetDisplayPath();
if (!String.IsNullOrEmpty(sourceFilePath)) {
String text = SR.GetString(SR.Error_Formatter_Source_File) + " " + sourceFilePath;
formAdd.AddParsedSubObject(CreateLabelFromText(text));
formAdd.AddParsedSubObject(CreateBreakLiteral());
text = SR.GetString(SR.Error_Formatter_Line) + " " + SourceFileLineNumber;
formAdd.AddParsedSubObject(CreateLabelFromText(text));
formAdd.AddParsedSubObject(CreateBreakLiteral());
}
// Stack trace info
StringCollection stackTrace = AdaptiveStackTrace;
if (stackTrace != null && stackTrace.Count > 0) {
foreach (String stack in stackTrace) {
formAdd.AddParsedSubObject(CreateLabelFromText(stack));
formAdd.AddParsedSubObject(CreateBreakLiteral());
}
}
// Temporarily use a string writer to capture the output and
// return it accordingly.
StringWriter stringWriter = new StringWriter(CultureInfo.CurrentCulture);
TextWriter textWriter = context.Response.SwitchWriter(stringWriter);
page.ProcessRequest(context);
context.Response.SwitchWriter(textWriter);
return stringWriter.ToString();
}
catch {
return GetStaticErrorMessage(context);
}
}
private string GetPreferredRenderingType(HttpContext context) {
HttpRequest request = (context != null) ? context.Request : null;
// Request.Browser might throw if the configuration file has some
// bad format.
HttpBrowserCapabilities browser = null;
try {
browser = (request != null) ? request.Browser : null;
}
catch {
return String.Empty;
}
return ((browser != null) ? browser["preferredRenderingType"] : String.Empty);
}
private string GetStaticErrorMessage(HttpContext context) {
string preferredRenderingType = GetPreferredRenderingType(context);
Debug.Assert(preferredRenderingType != null);
string errorMessage;
if (StringUtil.StringStartsWithIgnoreCase(preferredRenderingType, "xhtml")) {
errorMessage = FormatStaticErrorMessage(StaticErrorFormatterHelper.XhtmlErrorBeginTemplate,
StaticErrorFormatterHelper.XhtmlErrorEndTemplate);
}
else if (StringUtil.StringStartsWithIgnoreCase(preferredRenderingType, "wml")) {
errorMessage = FormatStaticErrorMessage(StaticErrorFormatterHelper.WmlErrorBeginTemplate,
StaticErrorFormatterHelper.WmlErrorEndTemplate);
// VSWhidbey 161754: In the case that headers have been written,
// we should try to set the content type only if needed.
const string wmlContentType = "text/vnd.wap.wml";
if (String.Compare(context.Response.ContentType, 0,
wmlContentType, 0, wmlContentType.Length,
StringComparison.OrdinalIgnoreCase) != 0) {
context.Response.ContentType = wmlContentType;
}
}
else {
errorMessage = FormatStaticErrorMessage(StaticErrorFormatterHelper.ChtmlErrorBeginTemplate,
StaticErrorFormatterHelper.ChtmlErrorEndTemplate);
}
return errorMessage;
}
private string FormatStaticErrorMessage(string errorBeginTemplate,
string errorEndTemplate) {
StringBuilder errorContent = new StringBuilder();
// Server error text with the application name and Title
string errorHeader = SR.GetString(SR.Error_Formatter_ASPNET_Error, HttpRuntime.AppDomainAppVirtualPath);
errorContent.Append(String.Format(CultureInfo.CurrentCulture, errorBeginTemplate, errorHeader, ErrorTitle));
// Description
errorContent.Append(SR.GetString(SR.Error_Formatter_Description) + " " + Description);
errorContent.Append(StaticErrorFormatterHelper.Break);
// Misc Title
String miscTitle = MiscSectionTitle;
if (miscTitle != null && miscTitle.Length > 0) {
errorContent.Append(miscTitle);
errorContent.Append(StaticErrorFormatterHelper.Break);
}
// Misc Info
StringCollection miscContent = AdaptiveMiscContent;
if (miscContent != null && miscContent.Count > 0) {
foreach (String contentLine in miscContent) {
errorContent.Append(contentLine);
errorContent.Append(StaticErrorFormatterHelper.Break);
}
}
// File & line# info
String sourceFilePath = GetDisplayPath();
if (!String.IsNullOrEmpty(sourceFilePath)) {
String text = SR.GetString(SR.Error_Formatter_Source_File) + " " + sourceFilePath;
errorContent.Append(text);
errorContent.Append(StaticErrorFormatterHelper.Break);
text = SR.GetString(SR.Error_Formatter_Line) + " " + SourceFileLineNumber;
errorContent.Append(text);
errorContent.Append(StaticErrorFormatterHelper.Break);
}
// Stack trace info
StringCollection stackTrace = AdaptiveStackTrace;
if (stackTrace != null && stackTrace.Count > 0) {
foreach (String stack in stackTrace) {
errorContent.Append(stack);
errorContent.Append(StaticErrorFormatterHelper.Break);
}
}
errorContent.Append(errorEndTemplate);
return errorContent.ToString();
}
internal string GetErrorMessage() {
return GetErrorMessage(HttpContext.Current, true);
}
// Return error message by checking if adaptive error formatting
// should be used.
internal virtual string GetErrorMessage(HttpContext context, bool dontShowSensitiveInfo) {
if (RequiresAdaptiveErrorReporting(context)) {
return GetAdaptiveErrorMessage(context, dontShowSensitiveInfo);
}
return GetHtmlErrorMessage(dontShowSensitiveInfo);
}
internal /*public*/ string GetHtmlErrorMessage() {
return GetHtmlErrorMessage(true);
}
internal /*public*/ string GetHtmlErrorMessage(bool dontShowSensitiveInfo) {
// Give the formatter a chance to prepare its state
PrepareFormatter();
StringBuilder sb = new StringBuilder();
//
sb.Append("<!DOCTYPE html>\r\n");
sb.Append("<html");
// VSWhidbey 477678: Honor right to left language text format.
if (IsTextRightToLeft) {
sb.Append(" dir=\"rtl\"");
}
sb.Append(">\r\n");
sb.Append(" <head>\r\n");
sb.Append(" <title>" + ErrorTitle + "</title>\r\n");
sb.Append(" <meta name=\"viewport\" content=\"width=device-width\" />\r\n");
sb.Append(" <style>\r\n");
sb.Append(" body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n");
sb.Append(" p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n");
sb.Append(" b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n");
sb.Append(" H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n");
sb.Append(" H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n");
sb.Append(" pre {font-family:\"Consolas\",\"Lucida Console\",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}\r\n");
sb.Append(" .marker {font-weight: bold; color: black;text-decoration: none;}\r\n");
sb.Append(" .version {color: gray;}\r\n");
sb.Append(" .error {margin-bottom: 10px;}\r\n");
sb.Append(" .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:pointer; }\r\n");
sb.Append(" @media screen and (max-width: 639px) {\r\n");
sb.Append(" pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }\r\n");
sb.Append(" }\r\n");
sb.Append(" @media screen and (max-width: 479px) {\r\n");
sb.Append(" pre { width: 280px; }\r\n");
sb.Append(" }\r\n");
sb.Append(" </style>\r\n");
sb.Append(" </head>\r\n\r\n");
sb.Append(" <body bgcolor=\"white\">\r\n\r\n");
sb.Append(" <span><H1>" + SR.GetString(SR.Error_Formatter_ASPNET_Error, HttpRuntime.AppDomainAppVirtualPath) + "<hr width=100% size=1 color=silver></H1>\r\n\r\n");
sb.Append(" <h2> <i>" + ErrorTitle + "</i> </h2></span>\r\n\r\n");
sb.Append(" <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n");
// Top-level description
sb.Append(" <b> " + SR.GetString(SR.Error_Formatter_Description) + " </b>" + Description + "\r\n");
sb.Append(" <br><br>\r\n\r\n");
// Error details
WriteErrorDetails(sb, dontShowSensitiveInfo);
// Footer
if (!(dontShowSensitiveInfo || _dontShowVersion)) { // don't show version for security reasons
sb.Append(" <hr width=100% size=1 color=silver>\r\n\r\n");
sb.Append(" <b>" + SR.GetString(SR.Error_Formatter_Version) + "</b> " +
SR.GetString(SR.Error_Formatter_CLR_Build) + VersionInfo.ClrVersion +
SR.GetString(SR.Error_Formatter_ASPNET_Build) + VersionInfo.EngineVersion + "\r\n\r\n");
}
sb.Append(" </font>\r\n\r\n");
sb.Append(" </body>\r\n");
sb.Append("</html>\r\n");
sb.Append(PostMessage);
return sb.ToString();
}
internal void WriteErrorDetails(StringBuilder sb, bool dontShowSensitiveInfo) {
// Error Message
if (MiscSectionTitle != null) {
sb.Append(" <b> " + MiscSectionTitle + ": </b>" + MiscSectionContent + "<br><br>\r\n\r\n");
}
// Source Code Box
WritePrimaryBox(sb, dontShowSensitiveInfo);
// Additional config lines
ConfigurationErrorsException configErrors = Exception as ConfigurationErrorsException;
if (configErrors != null && configErrors.Errors.Count > 1) {
sb.Append(String.Format(CultureInfo.InvariantCulture, startExpandableBlock, "additionalConfigurationErrors",
SR.GetString(SR.TmplConfigurationAdditionalError)));
sb.Append(startColoredSquare + "<pre>");
//
// Get the configuration message as though there were user code on the stack,
// so that the full path to the configuration file is not shown if the app
// does not have PathDiscoveryPermission.
//
bool revertPermitOnly = false;
try {
PermissionSet ps = HttpRuntime.NamedPermissionSet;
if (ps != null) {
ps.PermitOnly();
revertPermitOnly = true;
}
int errorNumber = 0;
foreach(ConfigurationException configurationError in configErrors.Errors) {
if (errorNumber > 0) {
sb.Append(configurationError.Message);
sb.Append("<BR/>\r\n");
}
errorNumber++;
}
}
finally {
if (revertPermitOnly) {
CodeAccessPermission.RevertPermitOnly();
}
}
sb.Append("</pre>" + endColoredSquare);
sb.Append(endExpandableBlock);
sb.Append(toggleScript);
}
// FusionLog
// If it's a FileNotFoundException/FileLoadException/BadImageFormatException with a FusionLog,
// write it out (ASURT 83587)
if (!dontShowSensitiveInfo && Exception != null) {
// (Only display the fusion log in medium or higher (ASURT 126827)
if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) {
WriteFusionLogWithAssert(sb);
}
}
// Stack Trace Box
WriteSecondaryBox(sb, dontShowSensitiveInfo);
}
protected virtual void WritePrimaryBox(StringBuilder sb, bool dontShowSensitiveInfo) {
WriteColoredSquare(sb, ColoredSquareTitle, ColoredSquareDescription, ColoredSquareContent, WrapColoredSquareContentLines);
if (ShowSourceFileInfo) {
string displayPath = GetDisplayPath();
if (displayPath == null)
displayPath = SR.GetString(SR.Error_Formatter_No_Source_File);
sb.Append(" <b> " + SR.GetString(SR.Error_Formatter_Source_File) + " </b> " + displayPath + "<b> " + SR.GetString(SR.Error_Formatter_Line) + " </b> " + SourceFileLineNumber + "\r\n");
sb.Append(" <br><br>\r\n\r\n");
}
}
protected virtual void WriteSecondaryBox(StringBuilder sb, bool dontShowSensitiveInfo) {
WriteColoredSquare(sb, ColoredSquare2Title, ColoredSquare2Description, ColoredSquare2Content, false);
}
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void WriteFusionLogWithAssert(StringBuilder sb) {
for (Exception e = Exception; e != null; e = e.InnerException) {
string fusionLog = null;
string filename = null;
FileNotFoundException fnfException = e as FileNotFoundException;
if (fnfException != null) {
fusionLog = fnfException.FusionLog;
filename = fnfException.FileName;
}
FileLoadException flException = e as FileLoadException;
if (flException != null) {
fusionLog = flException.FusionLog;
filename = flException.FileName;
}
BadImageFormatException bifException = e as BadImageFormatException;
if (bifException != null) {
fusionLog = bifException.FusionLog;
filename = bifException.FileName;
}
if (!String.IsNullOrEmpty(fusionLog)) {
WriteColoredSquare(sb,
SR.GetString(SR.Error_Formatter_FusionLog),
SR.GetString(SR.Error_Formatter_FusionLogDesc, filename),
HttpUtility.HtmlEncode(fusionLog),
false /*WrapColoredSquareContentLines*/);
_fusionLogWritten = true;
break;
}
}
}
protected void WriteColoredSquare(StringBuilder sb, string title, string description,
string content, bool wrapContentLines) {
if (title != null) {
sb.Append(" <b>" + title + ":</b> " + description + "<br><br>\r\n\r\n");
sb.Append(startColoredSquare);
if (!wrapContentLines)
sb.Append("<pre>");
sb.Append("\r\n\r\n");
sb.Append(content);
if (!wrapContentLines)
sb.Append("</pre>");
sb.Append(endColoredSquare);
sb.Append(" <br>\r\n\r\n");
}
}
internal /*public*/ virtual void PrepareFormatter() {
// VSWhidbey 139210: ErrorFormatter object might be reused and
// the properties would be gone through again. So we need to
// clear the adaptive error content to avoid duplicate content.
if (_adaptiveMiscContent != null) {
_adaptiveMiscContent.Clear();
}
if (_adaptiveStackTrace != null) {
_adaptiveStackTrace.Clear();
}
}
/*
* Return the associated exception object (if any)
*/
protected virtual Exception Exception {
get { return null; }
}
/*
* Return the type of error. e.g. "Compilation Error."
*/
protected abstract string ErrorTitle {
get;
}
/*
* Return a description of the error
* e.g. "An error occurred during the compilation of a resource required to service"
*/
protected abstract string Description {
get;
}
/*
* A section used differently by different types of errors (title)
* e.g. "Compiler Error Message"
* e.g. "Exception Details"
*/
protected abstract string MiscSectionTitle {
get;
}
/*
* A section used differently by different types of errors (content)
* e.g. "BC30198: Expected: )"
* e.g. "System.NullReferenceException"
*/
protected abstract string MiscSectionContent {
get;
}
/*
* e.g. "Source Error"
*/
protected virtual string ColoredSquareTitle {
get { return null;}
}
/*
* Optional text between color square title and the color square itself
*/
protected virtual string ColoredSquareDescription {
get { return null;}
}
/*
* e.g. a piece of source code with the error context
*/
protected virtual string ColoredSquareContent {
get { return null;}
}
/*
* If false, use a <pre></pre> tag around it
*/
protected virtual bool WrapColoredSquareContentLines {
get { return false;}
}
/*
* e.g. "Source Error"
*/
protected virtual string ColoredSquare2Title {
get { return null;}
}
/*
* Optional text between color square title and the color square itself
*/
protected virtual string ColoredSquare2Description {
get { return null;}
}
/*
* e.g. a piece of source code with the error context
*/
protected virtual string ColoredSquare2Content {
get { return null;}
}
/*
* Misc content which will be shown to mobile devices
* e.g. compile error code
*/
protected virtual StringCollection AdaptiveMiscContent {
get {
if (_adaptiveMiscContent == null) {
_adaptiveMiscContent = new StringCollection();
}
return _adaptiveMiscContent;
}
}
/*
* Exception stack trace which will be shown to mobile devices
* e.g. stack trace of a runtime error
*/
protected virtual StringCollection AdaptiveStackTrace {
get {
if (_adaptiveStackTrace == null) {
_adaptiveStackTrace = new StringCollection();
}
return _adaptiveStackTrace;
}
}
/*
* Determines whether SourceFileName and SourceFileLineNumber will be used
*/
protected abstract bool ShowSourceFileInfo {
get;
}
/*
* e.g. d:\samples\designpreview\test.aspx
*/
protected virtual string PhysicalPath {
get { return null;}
}
/*
* e.g. /myapp/test.aspx
*/
protected virtual string VirtualPath {
get { return null;}
}
/*
* The line number in the source file
*/
protected virtual int SourceFileLineNumber {
get { return 0;}
}
protected virtual String PostMessage {
get { return null; }
}
/*
* Does this error have only information that we want to
* show over the web to random users?
*/
internal virtual bool CanBeShownToAllUsers {
get { return false;}
}
// VSWhidbey 477678: Respect current language text format that is right
// to left. To be used by subclasses who need to adjust text format for
// code area accordingly.
protected static bool IsTextRightToLeft {
get {
return CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft;
}
}
protected string WrapWithLeftToRightTextFormatIfNeeded(string content) {
if (IsTextRightToLeft) {
content = BeginLeftToRightTag + content + EndLeftToRightTag;
}
return content;
}
// Make an HTTP line pragma from a virtual path
internal static string MakeHttpLinePragma(string virtualPath) {
string server = "http://server";
// We should only append a "/" if the virtual path does not
// already start with "/". Otherwise, we end up with double
// slashes, eg http://server//vpp/foo.aspx , and this breaks
// the VirtualPathProvider. (DevDiv 157238)
if (virtualPath != null && !virtualPath.StartsWith("/", StringComparison.Ordinal)) {
server += "/";
}
return (new Uri(server + virtualPath)).ToString();
}
internal static string GetSafePath(string linePragma) {
// First, check if it's an http line pragma
string virtualPath = GetVirtualPathFromHttpLinePragma(linePragma);
// If so, just return the virtual path
if (virtualPath != null)
return virtualPath;
// If not, it must be a physical path, which we need to make safe
return HttpRuntime.GetSafePath(linePragma);
}
internal static string GetVirtualPathFromHttpLinePragma(string linePragma) {
if (String.IsNullOrEmpty(linePragma))
return null;
try {
Uri uri = new Uri(linePragma);
if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
return uri.LocalPath;
}
catch {}
return null;
}
internal static string ResolveHttpFileName(string linePragma) {
// When running under VS debugger, we use URL's instead of paths in our #line pragmas.
// When we detect this situation, we need to do a MapPath to get back to the file name (ASURT 76211/114867)
string virtualPath = GetVirtualPathFromHttpLinePragma(linePragma);
// If we didn't detect a virtual path, just return the input
if (virtualPath == null)
return linePragma;
return HostingEnvironment.MapPathInternal(virtualPath);
}
/*
* This can be either a virtual or physical path, depending on what's available
*/
private string GetDisplayPath() {
if (VirtualPath != null)
return VirtualPath;
// It used to be an Assert on the following check but since
// adaptive error rendering uses this method where both
// VirtualPath and PhysicalPath might not set, it is changed to
// an if statement.
if (PhysicalPath != null)
return HttpRuntime.GetSafePath(PhysicalPath);
return null;
}
}
/*
* This formatter is used for runtime exceptions that don't fall into a
* specific category.
*/
internal class UnhandledErrorFormatter : ErrorFormatter {
protected Exception _e;
protected Exception _initialException;
protected ArrayList _exStack = new ArrayList();
protected string _physicalPath;
protected int _line;
private string _coloredSquare2Content;
private bool _fGeneratedCodeOnStack;
protected String _message;
protected String _postMessage;
internal UnhandledErrorFormatter(Exception e) : this(e, null, null){
}
internal UnhandledErrorFormatter(Exception e, String message, String postMessage) {
_message = message;
_postMessage = postMessage;
_e = e;
}
internal /*public*/ override void PrepareFormatter() {
// Build a stack of exceptions
for (Exception e = _e; e != null; e = e.InnerException) {
_exStack.Add(e);
// Keep track of the initial exception (first one thrown)
_initialException = e;
}
// Get the Square2Content first so the line number gets calculated
_coloredSquare2Content = ColoredSquare2Content;
}
protected override Exception Exception {
get { return _e; }
}
protected override string ErrorTitle {
get {
// Use the exception's message if there is one
string msg = _initialException.Message;
if (!String.IsNullOrEmpty(msg))
return HttpUtility.FormatPlainTextAsHtml(msg);
// Otherwise, use some default string
return SR.GetString(SR.Unhandled_Err_Error);
}
}
protected override string Description {
get {
if (_message != null) {
return _message;
}
else {
return SR.GetString(SR.Unhandled_Err_Desc);
}
}
}
protected override string MiscSectionTitle {
get { return SR.GetString(SR.Unhandled_Err_Exception_Details);}
}
protected override string MiscSectionContent {
get {
string exceptionName = _initialException.GetType().FullName;
StringBuilder msg = new StringBuilder(exceptionName);
string adaptiveMiscLine = exceptionName;
if (_initialException.Message != null) {
string errorMessage = HttpUtility.FormatPlainTextAsHtml(_initialException.Message);
msg.Append(": ");
msg.Append(errorMessage);
adaptiveMiscLine += ": " + errorMessage;
}
AdaptiveMiscContent.Add(adaptiveMiscLine);
if (_initialException is UnauthorizedAccessException) {
msg.Append("\r\n<br><br>");
String errDesc = SR.GetString(SR.Unauthorized_Err_Desc1);
errDesc = HttpUtility.HtmlEncode(errDesc);
msg.Append(errDesc);
AdaptiveMiscContent.Add(errDesc);
msg.Append("\r\n<br><br>");
errDesc = SR.GetString(SR.Unauthorized_Err_Desc2);
errDesc = HttpUtility.HtmlEncode(errDesc);
msg.Append(errDesc);
AdaptiveMiscContent.Add(errDesc);
}
else if (_initialException is HostingEnvironmentException) {
String details = ((HostingEnvironmentException)_initialException).Details;
if (!String.IsNullOrEmpty(details)) {
msg.Append("\r\n<br><br><b>");
msg.Append(details);
msg.Append("</b>");
AdaptiveMiscContent.Add(details);
}
}
return msg.ToString();
}
}
protected override string ColoredSquareTitle {
get { return SR.GetString(SR.TmplCompilerSourceSecTitle);}
}
protected override string ColoredSquareContent {
get {
// If we couldn't get line info for the error, display a standard message
if (_physicalPath == null) {
const string BeginLeftToRightMarker = "BeginMarker";
const string EndLeftToRightMarker = "EndMarker";
bool setLeftToRightMarker = false;
// The error text depends on whether .aspx code was found on the stack
// Also, if trust is less than medium, never display the message that
// explains how to turn on debugging, since it's not allowed (Whidbey 9176)
string msg;
if (!_fGeneratedCodeOnStack ||
!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) {
msg = SR.GetString(SR.Src_not_available_nodebug);
}
else {
if (IsTextRightToLeft) {
setLeftToRightMarker = true;
}
// Because the resource string has both normal language text and config/code samples,
// left-to-right markup tags need to be wrapped around the config/code samples if
// right to left language format is being used.
//
// Note that the retrieved resource string will be passed to the call
// HttpUtility.FormatPlainTextAsHtml(), which does HtmlEncode. In order to preserve
// the left-to-right markup tags, the resource string has been added with markers
// that identify the beginnings and ends of config/code samples. After
// FormatPlainTextAsHtml() is called, and the markers will be replaced with
// left-to-right markup tags below.
msg = SR.GetString(SR.Src_not_available,
((setLeftToRightMarker) ? BeginLeftToRightMarker : string.Empty),
((setLeftToRightMarker) ? EndLeftToRightMarker : string.Empty),
((setLeftToRightMarker) ? BeginLeftToRightMarker : string.Empty),
((setLeftToRightMarker) ? EndLeftToRightMarker : string.Empty));
}
msg = HttpUtility.FormatPlainTextAsHtml(msg);
if (setLeftToRightMarker) {
// If only <div dir=ltr> was used to wrap around the left-to-right code text,
// the font rendering on Firefox was not good. We use <code> in addition to
// the <div> tag to workaround the problem.
const string BeginLeftToRightTags = "</code>" + BeginLeftToRightTag + "<code>";
const string EndLeftToRightTags = "</code>" + EndLeftToRightTag + "<code>";
msg = msg.Replace(BeginLeftToRightMarker, BeginLeftToRightTags);
msg = msg.Replace(EndLeftToRightMarker, EndLeftToRightTags);
}
return msg;
}