-
Notifications
You must be signed in to change notification settings - Fork 2
/
Event.cs
1002 lines (869 loc) · 40.2 KB
/
Event.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Validation;
using System.Globalization;
using System.Text;
using System.Web;
using GalleryServerPro.Business;
using GalleryServerPro.Business.Interfaces;
using GalleryServerPro.Events.CustomExceptions;
using GalleryServerPro.Events.Properties;
namespace GalleryServerPro.Events
{
/// <summary>
/// Represents an application event or error that occurrs during the execution of Gallery Server Pro code.
/// </summary>
public class Event : IEvent, IComparable
{
#region Private Fields
private readonly List<KeyValuePair<string, string>> _cookies = new List<KeyValuePair<string, string>>(5);
private readonly List<KeyValuePair<string, string>> _eventData = new List<KeyValuePair<string, string>>(1);
private readonly string _exceptionType;
private readonly List<KeyValuePair<string, string>> _formVariables = new List<KeyValuePair<string, string>>();
private readonly int _galleryId;
private readonly List<KeyValuePair<string, string>> _innerExData = new List<KeyValuePair<string, string>>(1);
private readonly string _innerExMessage;
private readonly string _innerExSource;
private readonly string _innerExStackTrace;
private readonly string _innerExTargetSite;
private readonly string _innerExType;
private readonly string _message;
private readonly List<KeyValuePair<string, string>> _serverVariables = new List<KeyValuePair<string, string>>(60);
private readonly List<KeyValuePair<string, string>> _sessionVariables = new List<KeyValuePair<string, string>>(5);
private readonly string _source;
private readonly string _stackTrace;
private readonly string _targetSite;
private readonly DateTime _timeStampUtc;
private string _url;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value that uniquely identifies an application event.
/// </summary>
/// <value>A value that uniquely identifies an application event.</value>
public int EventId { get; set; }
/// <summary>
/// Gets or sets the type of the event.
/// </summary>
/// <value>The type of the event.</value>
public EventType EventType { get; set; }
/// <summary>
/// Gets the ID of the gallery that is the source of this event.
/// </summary>
/// <value>The ID of the gallery that is the source of this event</value>
public int GalleryId
{
get { return _galleryId; }
}
/// <summary>
/// Gets the UTC date and time the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The date and time the event occurred.</value>
public DateTime TimestampUtc
{
get { return _timeStampUtc; }
}
/// <summary>
/// Gets the message associated with the event. Guaranteed to not be null.
/// </summary>
/// <value>The message associated with the event.</value>
public string Message
{
get { return _message; }
}
/// <summary>
/// Gets the data associated with the event. When <see cref="EventType" /> is <see cref="Business.EventType.Error" />,
/// any items in the exception data are added. Guaranteed to not be null.
/// </summary>
/// <value>The data associate with the exception.</value>
public List<KeyValuePair<string, string>> EventData
{
get { return _eventData; }
}
/// <summary>
/// Gets the type of the exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The type of the exception.</value>
public string ExType
{
get { return _exceptionType; }
}
/// <summary>
/// Gets the source of the exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The source of the exception.</value>
public string ExSource
{
get { return _source; }
}
/// <summary>
/// Gets the target site of the exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The target site of the exception.</value>
public string ExTargetSite
{
get { return _targetSite; }
}
/// <summary>
/// Gets the stack trace of the exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The stack trace of the exception.</value>
public string ExStackTrace
{
get { return _stackTrace; }
}
/// <summary>
/// Gets the type of the inner exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The type of the inner exception.</value>
public string InnerExType
{
get { return _innerExType; }
}
/// <summary>
/// Gets the message of the inner exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The message of the inner exception.</value>
public string InnerExMessage
{
get { return _innerExMessage; }
}
/// <summary>
/// Gets the source of the inner exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The source of the inner exception.</value>
public string InnerExSource
{
get { return _innerExSource; }
}
/// <summary>
/// Gets the target site of the inner exception. Guaranteed to not be null.
/// </summary>
/// <value>The target site of the inner exception.</value>
public string InnerExTargetSite
{
get { return _innerExTargetSite; }
}
/// <summary>
/// Gets the stack trace of the inner exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. Guaranteed to not be null.
/// </summary>
/// <value>The stack trace of the inner exception.</value>
public string InnerExStackTrace
{
get { return _innerExStackTrace; }
}
/// <summary>
/// Gets the URL of the page where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The URL of the page where the event occurred.</value>
public string Url
{
get { return (!String.IsNullOrEmpty(_url) ? _url : Resources.Err_Missing_Data_Txt); }
}
/// <summary>
/// Gets the HTTP user agent where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The HTTP user agent where the event occurred.</value>
public string HttpUserAgent
{
get
{
KeyValuePair<string, string> httpUserAgent = _serverVariables.Find(delegate(KeyValuePair<string, string> kvp) { return (String.Compare(kvp.Key, "HTTP_USER_AGENT", StringComparison.OrdinalIgnoreCase) == 0); });
return httpUserAgent.Value ?? Resources.Err_Missing_Data_Txt;
}
}
/// <summary>
/// Gets the data associated with the inner exception. Contains a value only when <see cref="EventType" />
/// is <see cref="Business.EventType.Error" />. This is extracted from <see cref="System.Exception.Data" />.
/// Guaranteed to not be null.
/// </summary>
/// <value>The data associate with the inner exception.</value>
public ReadOnlyCollection<KeyValuePair<string, string>> InnerExData
{
get { return _innerExData.AsReadOnly(); }
}
/// <summary>
/// Gets the form variables from the web page where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The form variables from the web page where the event occurred.</value>
public ReadOnlyCollection<KeyValuePair<string, string>> FormVariables
{
get { return _formVariables.AsReadOnly(); }
}
/// <summary>
/// Gets the cookies from the web page where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The cookies from the web page where the event occurred.</value>
public ReadOnlyCollection<KeyValuePair<string, string>> Cookies
{
get { return _cookies.AsReadOnly(); }
}
/// <summary>
/// Gets the session variables from the web page where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The session variables from the web page where the event occurred.</value>
public ReadOnlyCollection<KeyValuePair<string, string>> SessionVariables
{
get { return _sessionVariables.AsReadOnly(); }
}
/// <summary>
/// Gets the server variables from the web page where the event occurred. Guaranteed to not be null.
/// </summary>
/// <value>The server variables from the web page where the event occurred.</value>
public ReadOnlyCollection<KeyValuePair<string, string>> ServerVariables
{
get { return _serverVariables.AsReadOnly(); }
}
/// <summary>
/// Gets the CSS class definitions that can be used to style the HTML generated by the HTML methods in this object.
/// </summary>
/// <value>
/// The CSS class definitions that can be used to style the HTML generated by the HTML methods in this object.
/// </value>
public string CssStyles
{
get
{
return @"
<style type=""text/css"">
.gsp_ns {font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px;}
.gsp_ns ul { margin: 0; padding: 0; }
.gsp_ns .gsp_event_h1 { margin: .5em 0 .5em 0;color:#800;font-size: 1.4em;}
.gsp_ns .gsp_event_h2 { background-color:#cdc9c2;font-size: 1.2em; font-weight: bold;margin:1em 0 0 0;padding:.4em 0 .4em 4px;}
.gsp_ns .gsp_event_table {width:100%;border:1px solid #cdc9c2;}
.gsp_ns .gsp_event_table td {vertical-align:top;padding:4px;}
.gsp_ns .gsp_event_col1 {background-color:#dcd8cf;white-space:nowrap;width:150px;border-bottom:1px solid #fff;}
.gsp_ns .gsp_event_col2 {border-bottom:1px solid #dcd8cf;}
.gsp_ns .gsp_event_item {}
.gsp_ns p { margin: 0 0 0.2em 0; padding: 0.2em 0 0 0; }
</style>
<!--[if gte mso 9]><!-- Outlook 2007 and higher -->
<style type=""text/css"">
.gsp_ns table {font: 12px Verdana, Arial, Helvetica, sans-serif;}
.gsp_ns .gsp_event_h2 { background-color:transparent;}
</style>
<![endif]-->
";
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Event" /> class.
/// </summary>
/// <param name="msg">The event message to record.</param>
/// <param name="data">Additional optional data to record. May be null.</param>
/// <param name="galleryId">The ID of the gallery the <paramref name="msg" /> is associated with. If it is not specific to a gallery
/// or the gallery ID is unknown, specify the ID for the template gallery.</param>
/// <param name="eventType">Type of the event. Defaults to <see cref="Business.EventType.Info" /> when not specified.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="galleryId" /> is <see cref="Int32.MinValue" />.</exception>
internal Event(string msg, int galleryId, EventType eventType = EventType.Info, Dictionary<string, string> data = null)
{
if (galleryId == int.MinValue)
throw new ArgumentOutOfRangeException("galleryId", string.Format("The galleryId parameter in the Event contructor must represent an existing gallery. Instead, it was {0}", galleryId));
EventId = int.MinValue;
EventType = eventType;
_message = msg;
_galleryId = galleryId;
_timeStampUtc = DateTime.UtcNow;
_exceptionType = String.Empty;
_source = String.Empty;
_targetSite = String.Empty;
_stackTrace = String.Empty;
_innerExType = String.Empty;
_innerExMessage = String.Empty;
_innerExSource = String.Empty;
_innerExTargetSite = String.Empty;
_innerExStackTrace = String.Empty;
if (data != null)
{
foreach (var dataItem in data)
{
_eventData.Add(dataItem);
}
}
ExtractVersion();
ExtractHttpContextInfo();
}
/// <summary>
/// Initializes a new instance of the <see cref="Event" /> class.
/// </summary>
/// <param name="ex">The exception to use as the source for a new instance of this object.</param>
/// <param name="galleryId">
/// The ID of the gallery the <paramref name="ex">exception</paramref> is associated with.
/// If the exception is not specific to a gallery or the gallery ID is unknown, specify the ID for the
/// template gallery.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="ex" /> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="galleryId" /> is <see cref="Int32.MinValue" />.</exception>
internal Event(Exception ex, int galleryId)
{
if (ex == null)
throw new ArgumentNullException("ex");
if (galleryId == int.MinValue)
throw new ArgumentOutOfRangeException("galleryId", string.Format("The galleryId parameter in the Event contructor must represent an existing gallery. Instead, it was {0}", galleryId));
EventId = int.MinValue;
EventType = EventType.Error;
_galleryId = galleryId;
_timeStampUtc = DateTime.UtcNow;
var missingDataText = Resources.Err_Missing_Data_Txt;
_exceptionType = ex.GetType().ToString();
_message = ex.Message;
_source = ex.Source ?? missingDataText;
_targetSite = (ex.TargetSite == null) ? missingDataText : ex.TargetSite.ToString();
_stackTrace = ex.StackTrace ?? missingDataText;
foreach (DictionaryEntry entry in ex.Data)
{
string value = (entry.Value != null ? entry.Value.ToString() : String.Empty);
_eventData.Add(new KeyValuePair<string, string>(entry.Key.ToString(), value));
}
var valEx = ex as DbEntityValidationException;
if (valEx != null)
{
int i = 1, j = 1;
foreach (DbEntityValidationResult valErr in valEx.EntityValidationErrors)
{
var msg1 = String.Format(CultureInfo.InvariantCulture, "Entity {0} ({1}) IsValid={2}", valErr.Entry.Entity.GetType(), valErr.Entry.State, valErr.IsValid);
_eventData.Add(new KeyValuePair<string, string>(String.Concat("Entity Validation Error #", i++), msg1));
foreach (DbValidationError dbValErr in valErr.ValidationErrors)
{
string msg2 = String.Format(CultureInfo.InvariantCulture, "{0} - {1}", dbValErr.PropertyName, dbValErr.ErrorMessage);
_eventData.Add(new KeyValuePair<string, string>(String.Concat("Validation Error #", j++), msg2));
}
}
}
var innerEx = ex.InnerException;
if (innerEx == null)
{
_innerExType = String.Empty;
_innerExMessage = String.Empty;
_innerExSource = String.Empty;
_innerExTargetSite = String.Empty;
_innerExStackTrace = String.Empty;
}
else
{
var innerExCounter = 0;
while (innerEx != null)
{
innerExCounter++;
if (innerExCounter == 1)
{
// This is the first inner exception.
_innerExType = innerEx.GetType().ToString();
_innerExMessage = innerEx.Message ?? missingDataText;
_innerExSource = innerEx.Source ?? missingDataText;
_innerExTargetSite = (innerEx.TargetSite == null) ? missingDataText : innerEx.TargetSite.ToString();
_innerExStackTrace = innerEx.StackTrace ?? missingDataText;
foreach (DictionaryEntry entry in innerEx.Data)
{
_innerExData.Add(new KeyValuePair<string, string>(entry.Key.ToString(), entry.Value.ToString()));
}
}
else
{
// The inner exception has one or more of its own inner exceptions. Add this data to the existing inner exception fields.
_innerExType = String.Format(CultureInfo.InvariantCulture, "{0};{1} Inner ex #{2}: {3}", _innerExType, Environment.NewLine, innerExCounter, innerEx.GetType());
_innerExMessage = String.Format(CultureInfo.InvariantCulture, "{0};{1} Inner ex #{2}: {3}", _innerExMessage, Environment.NewLine, innerExCounter, innerEx.Message);
_innerExSource = String.Format(CultureInfo.InvariantCulture, "{0};{1} Inner ex #{2}: {3}", _innerExSource, Environment.NewLine, innerExCounter, innerEx.Source ?? missingDataText);
_innerExTargetSite = String.Format(CultureInfo.InvariantCulture, "{0};{1} Inner ex #{2}: {3}", _innerExTargetSite, Environment.NewLine, innerExCounter, (innerEx.TargetSite == null) ? missingDataText : innerEx.TargetSite.ToString());
_innerExStackTrace = String.Format(CultureInfo.InvariantCulture, "{0}{0};{1} Inner ex #{2}: {3}", _innerExStackTrace, Environment.NewLine, innerExCounter, innerEx.StackTrace ?? missingDataText);
foreach (DictionaryEntry entry in innerEx.Data)
{
string key = String.Format(CultureInfo.InvariantCulture, "Inner ex #{0} data: {1}", innerExCounter, entry.Key);
_innerExData.Add(new KeyValuePair<string, string>(key, entry.Value.ToString()));
}
}
innerEx = innerEx.InnerException;
}
}
ExtractVersion();
ExtractHttpContextInfo();
}
/// <summary>
/// Initializes a new instance of the <see cref="Event" /> class.
/// </summary>
/// <param name="eventId">The app event ID.</param>
/// <param name="eventType">Type of the event.</param>
/// <param name="galleryId">The gallery ID.</param>
/// <param name="timeStamp">The time stamp.</param>
/// <param name="exType">Type of the exception.</param>
/// <param name="message">The message.</param>
/// <param name="eventData">The exception data.</param>
/// <param name="source">The source.</param>
/// <param name="targetSite">The target site.</param>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="innerExType">Type of the inner exception.</param>
/// <param name="innerExMessage">The inner exception message.</param>
/// <param name="innerExSource">The inner exception source.</param>
/// <param name="innerExTargetSite">The inner exception target site.</param>
/// <param name="innerExStackTrace">The inner exception stack trace.</param>
/// <param name="innerExData">The inner exception data.</param>
/// <param name="url">The URL where the exception occurred.</param>
/// <param name="formVariables">The form variables.</param>
/// <param name="cookies">The cookies.</param>
/// <param name="sessionVariables">The session variables.</param>
/// <param name="serverVariables">The server variables.</param>
internal Event(int eventId, EventType eventType, int galleryId, DateTime timeStamp, string exType, string message, List<KeyValuePair<string, string>> eventData, string source, string targetSite, string stackTrace, string innerExType, string innerExMessage, string innerExSource, string innerExTargetSite, string innerExStackTrace, List<KeyValuePair<string, string>> innerExData, string url, List<KeyValuePair<string, string>> formVariables, List<KeyValuePair<string, string>> cookies, List<KeyValuePair<string, string>> sessionVariables, List<KeyValuePair<string, string>> serverVariables)
{
EventId = eventId;
EventType = eventType;
_galleryId = galleryId;
_timeStampUtc = timeStamp;
_exceptionType = exType;
_message = message;
_source = source;
_targetSite = targetSite;
_stackTrace = stackTrace;
_eventData = eventData;
_innerExType = innerExType;
_innerExMessage = innerExMessage;
_innerExSource = innerExSource;
_innerExTargetSite = innerExTargetSite;
_innerExStackTrace = innerExStackTrace;
_innerExData = innerExData;
_url = url;
_formVariables = formVariables;
_cookies = cookies;
_sessionVariables = sessionVariables;
_serverVariables = serverVariables;
}
#endregion
#region Public Methods
/// <summary>
/// Formats the name of the specified <paramref name="item" /> into an HTML paragraph tag. Example: If
/// <paramref name="item" /> = ErrorItem.StackTrace, the text "Stack Trace" is returned as the content of the tag.
/// </summary>
/// <param name="item">The enum value to be used as the content of the paragraph element. It is HTML encoded.</param>
/// <returns>Returns an HTML paragraph tag.</returns>
public string ToHtmlName(EventItem item)
{
return ToHtmlParagraph(item, "gsp_event_item");
}
/// <summary>
/// Formats the value of the specified <paramref name="item" /> into an HTML paragraph tag. Example: If
/// <paramref name="item" /> = ErrorItem.StackTrace, the action stack trace data associated with the current error
/// is returned as the content of the tag. If present, line breaks (\r\n) are converted to <br /> tags.
/// </summary>
/// <param name="item">
/// The enum value indicating the error item to be used as the content of the paragraph element.
/// The text is HTML encoded.
/// </param>
/// <returns>Returns an HTML paragraph tag.</returns>
public string ToHtmlValue(EventItem item)
{
switch (item)
{
case EventItem.EventId:
return ToHtmlParagraph(EventId.ToString(CultureInfo.InvariantCulture));
case EventItem.EventType:
return ToHtmlParagraph(EventType.ToString());
case EventItem.Url:
return ToHtmlParagraph(Url);
case EventItem.Timestamp:
return ToHtmlParagraph(TimestampUtc.ToString(CultureInfo.CurrentCulture));
case EventItem.ExType:
return ToHtmlParagraph(ExType);
case EventItem.Message:
return ToHtmlParagraph(Message);
case EventItem.ExSource:
return ToHtmlParagraph(ExSource);
case EventItem.ExTargetSite:
return ToHtmlParagraph(ExTargetSite);
case EventItem.ExStackTrace:
return ToHtmlParagraph(ExStackTrace);
case EventItem.ExData:
return ToHtmlParagraphs(EventData);
case EventItem.InnerExType:
return ToHtmlParagraph(InnerExType);
case EventItem.InnerExMessage:
return ToHtmlParagraph(InnerExMessage);
case EventItem.InnerExSource:
return ToHtmlParagraph(InnerExSource);
case EventItem.InnerExTargetSite:
return ToHtmlParagraph(InnerExTargetSite);
case EventItem.InnerExStackTrace:
return ToHtmlParagraph(InnerExStackTrace);
case EventItem.InnerExData:
return ToHtmlParagraphs(InnerExData);
case EventItem.GalleryId:
return ToHtmlParagraph(GalleryId.ToString(CultureInfo.InvariantCulture));
case EventItem.HttpUserAgent:
return ToHtmlParagraph(HttpUserAgent);
case EventItem.FormVariables:
return ToHtmlParagraphs(FormVariables);
case EventItem.Cookies:
return ToHtmlParagraphs(Cookies);
case EventItem.SessionVariables:
return ToHtmlParagraphs(SessionVariables);
case EventItem.ServerVariables:
return ToHtmlParagraphs(ServerVariables);
default:
throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "Encountered unexpected EventItem enum value {0}. Event.ToHtmlValue() is not designed to handle this enum value. The function must be updated.", item));
}
}
/// <summary>
/// Generate HTML containing detailed information about the application event. Does not include the outer html
/// and body tag. The HTML may contain references to CSS classes for formatting purposes, so be sure to include
/// these CSS definitions in the containing web page. These CSS definitions can be accessed through the
/// <see cref="CssStyles" /> property.
/// </summary>
/// <returns>Returns an HTML formatted string containing detailed information about the event.</returns>
public string ToHtml()
{
var sb = new StringBuilder(20000);
AddHtmlErrorInfo(sb);
return sb.ToString();
}
/// <summary>
/// Generate a complete HTML page containing detailed information about the application event. Includes the outer html
/// and body tag, including definitions for the CSS classes that are referenced within the body. Does not depend
/// on external style sheets or other resources. This method can be used to generate the body of an HTML e-mail.
/// </summary>
/// <returns>Returns an HTML formatted string containing detailed information about the event.</returns>
public string ToHtmlPage()
{
var sb = new StringBuilder(20000);
sb.AppendLine("<!DOCTYPE html>");
sb.AppendLine("<html>");
sb.AppendLine("<head>");
sb.Append(CssStyles);
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<div class=\"gsp_ns\">");
sb.AppendLine(String.Concat("<p>", Resources.Err_Email_Body_Prefix, "</p>"));
AddHtmlErrorInfo(sb);
sb.AppendLine("</div>");
sb.AppendLine("</body></html>");
return sb.ToString();
}
#region IComparable Members
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance is less than
/// <paramref name="obj" />. Zero This instance is equal to <paramref name="obj" />. Greater than zero This instance is greater than
/// <paramref name="obj" />.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="obj" /> is not the same type as this instance.
/// </exception>
public int CompareTo(object obj)
{
if (obj == null)
return -1;
var other = obj as IEvent;
if (other != null)
return -TimestampUtc.CompareTo(other.TimestampUtc);
return -1;
}
#endregion
/// <summary>
/// Create a new instance of <see cref="IEvent" /> from the specified <paramref name="ex" /> and associate it with
/// the specified <paramref name="galleryId" />.
/// </summary>
/// <param name="ex">The exception to use as the source for a new instance of this object.</param>
/// <param name="galleryId">The ID of the gallery the <paramref name="ex">exception</paramref> is associated with.
/// If the exception is not specific to a gallery or the gallery ID is unknown, specify the ID of the template gallery.
/// </param>
/// <returns>Returns an <see cref="IEvent" /> containing information about <paramref name="ex" />.</returns>
public static IEvent Create(Exception ex, int galleryId)
{
return new Event(ex, galleryId);
}
#endregion
#region Private Methods
/// <summary>
/// Extract information from the current HTTP context and assign to member variables.
/// </summary>
private void ExtractHttpContextInfo()
{
if (HttpContext.Current == null)
{
_url = "Not Available";
return;
}
try
{
_url = HttpContext.Current.Request.Url.AbsoluteUri;
}
catch (HttpException)
{
_url = "Not Available";
return;
}
var form = HttpContext.Current.Request.Form;
for (int i = 0; i < form.Count; i++)
{
_formVariables.Add(new KeyValuePair<string, string>(form.Keys[i], form[i]));
}
var cookies = HttpContext.Current.Request.Cookies;
foreach (string item in cookies)
{
var cookie = cookies[item];
if (cookie != null)
_cookies.Add(new KeyValuePair<string, string>(cookie.Name, cookie.Value));
}
var session = HttpContext.Current.Session;
if (session != null)
{
foreach (string item in session)
{
_sessionVariables.Add(new KeyValuePair<string, string>(item, session[item].ToString()));
}
}
var serverVariables = HttpContext.Current.Request.ServerVariables;
for (var i = 0; i < serverVariables.Count; i++)
{
var key = serverVariables.Keys[i];
var value = serverVariables[i];
var serverVarsToSkip = new[] { "ALL_HTTP", "ALL_RAW" };
// Skip empty values & "ALL_HTTP" & "ALL_RAW" because their values are itemized in the rest of the collection
if (String.IsNullOrWhiteSpace(value) || Array.IndexOf(serverVarsToSkip, key) >= 0)
continue;
_serverVariables.Add(new KeyValuePair<string, string>(serverVariables.Keys[i], value));
}
}
/// <summary>
/// Formats the specified <paramref name="item" /> into an HTML paragraph tag with a class attribute of
/// <paramref name="cssClassName" />. The string representation of <paramref name="item" />
/// is extracted from a resource file and will closely resemble the enum value. Example: If <paramref name="item" /> = ErrorItem.StackTrace,
/// the text "Stack Trace" is used.
/// </summary>
/// <param name="item">The enum value to be used as the content of the paragraph element. It is HTML encoded.</param>
/// <param name="cssClassName">The name of the CSS class to assign to the paragraph element.</param>
/// <returns>Returns an HTML paragraph tag.</returns>
private static string ToHtmlParagraph(EventItem item, string cssClassName)
{
return ToHtmlParagraph(EventController.GetFriendlyEnum(item), cssClassName);
}
/// <summary>
/// Formats the specified string into an HTML paragraph tag with a class attribute of <paramref name="cssClassName" />.
/// </summary>
/// <param name="str">The string to be assigned as the content of the paragraph element. It is HTML encoded.</param>
/// <param name="cssClassName">The name of the CSS class to assign to the paragraph element. Defaults to "gsp_event_item"
/// when not specified.</param>
/// <returns>Returns an HTML paragraph tag.</returns>
private static string ToHtmlParagraph(string str, string cssClassName = "gsp_event_item")
{
return String.Concat("<p class='", cssClassName, "'>", HtmlEncode(str), "</p>");
}
private static string HtmlEncode(string str)
{
return (str == null ? null : HttpUtility.HtmlEncode(str).Replace("\r\n", "<br />"));
}
/// <summary>
/// Formats the <see cref="list" /> into one or more HTML paragraph tags where the key and value of each item are
/// concatenated with a colon between them (e.g. <p class='gsp_event_item'>HTTP_HOST: localhost.</p>)
/// A CSS class named "gsp_event_item" is automatically assigned to each paragraph element. The value property of
/// each collection item is processed so that it contains a space character every 70 characters or so. This is
/// required to allow HTML rendering engines to wrap the text. Guaranteed to return at least one paragraph
/// element. If <paramref name="list" /> is null or does not contain any items, a single paragraph element is
/// returned containing a string indicating there are not any items (e.g. "<none>")
/// </summary>
/// <param name="list">
/// The list containing the items to convert to HTML paragraph tags. The key and value of
/// each collection item is HTML encoded.
/// </param>
/// <returns>Returns one or more HTML paragraph tags.</returns>
private static string ToHtmlParagraphs(ICollection<KeyValuePair<string, string>> list)
{
if ((list == null) || (list.Count == 0))
return ToHtmlParagraph(Resources.Err_No_Data_Txt);
if (list.Count > 6)
{
var sb = new StringBuilder();
foreach (var pair in list)
{
sb.AppendLine("<p class='gsp_event_item'>");
sb.AppendLine(HtmlEncode(String.Concat(pair.Key, ": ", MakeHtmlLineWrapFriendly(pair.Value))));
sb.AppendLine("</p>");
}
return sb.ToString();
}
var listString = String.Empty;
foreach (var pair in list)
{
listString += String.Concat("<p class='gsp_event_item'>", HtmlEncode(String.Concat(pair.Key, ": ", MakeHtmlLineWrapFriendly(pair.Value))), "</p>");
}
return listString;
}
/// <overloads>Formats the data into an HTML table.</overloads>
/// <summary>
/// Formats the <paramref name="item" /> into an HTML table. Valid only for <see cref="EventItem" /> values that are collections.
/// </summary>
/// <param name="item">
/// The item to format into an HTML table. Must be one of the following enum values: FormVariables, Cookies,
/// SessionVariables, ServerVariables
/// </param>
/// <returns>Returns an HTML table.</returns>
private string ToHtmlTable(EventItem item)
{
string htmlValue;
switch (item)
{
case EventItem.FormVariables:
htmlValue = ToHtmlTable(FormVariables);
break;
case EventItem.Cookies:
htmlValue = ToHtmlTable(Cookies);
break;
case EventItem.SessionVariables:
htmlValue = ToHtmlTable(SessionVariables);
break;
case EventItem.ServerVariables:
htmlValue = ToHtmlTable(ServerVariables);
break;
default:
throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "Encountered unexpected EventItem enum value {0}. Event.ToHtmlTable() is not designed to handle this enum value. The function must be updated.", item));
}
return htmlValue;
}
/// <summary>
/// Formats the <paramref name="list" /> into a two-column HTML table where the first column contains the key and the second
/// contains the value. The table is assigned the CSS class "gsp_event_table"; each table cell in the first column has a CSS
/// class "gsp_event_col1", the second column has a CSS class "gsp_event_col2". Each cell contains a paragraph tag with a CSS
/// class "gsp_event_item" and the paragraphs content is either the key or value of the list item. If <paramref name="list" />
/// is null or doesn't contain any items, return a one-cell table with a message indicating there isn't any data (e.g. "<none>").
/// </summary>
/// <param name="list">The list to format into an HTML table. Keys and values are HTML encoded.</param>
/// <returns>Returns an HTML table.</returns>
private static string ToHtmlTable(ICollection<KeyValuePair<string, string>> list)
{
if ((list == null) || (list.Count == 0))
{
// No items. Just build simple table with message indicating there isn't any data.
return String.Format(CultureInfo.InvariantCulture, @"
<table cellpadding='0' cellspacing='0' class='gsp_event_table'>
<tr><td>{0}</td></tr>
</table>", ToHtmlParagraph(Resources.Err_No_Data_Txt));
}
if (list.Count > 6)
{
// More than 6 items. Use StringBuilder when dealing with lots of items.
var sb = new StringBuilder();
sb.AppendLine("<table cellpadding='0' cellspacing='0' class='gsp_event_table'>");
foreach (var pair in list)
{
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlParagraph(pair.Key), ToHtmlParagraph(MakeHtmlLineWrapFriendly(pair.Value)));
}
sb.AppendLine("</table>");
return sb.ToString();
}
// list contains between 1 and 6 items. Use standard string concatenation to build table
var listString = "<table cellpadding='0' cellspacing='0' class='gsp_event_table'>";
foreach (var pair in list)
{
listString += String.Format(CultureInfo.InvariantCulture, "<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlParagraph(pair.Key), ToHtmlParagraph(MakeHtmlLineWrapFriendly(pair.Value)));
}
listString += "</table>";
return listString;
}
/// <summary>
/// Add HTML formatted text to <paramref name="sb" /> that contains information about the current error.
/// </summary>
/// <param name="sb">The StringBuilder to add HTML data to.</param>
private void AddHtmlErrorInfo(StringBuilder sb)
{
sb.AppendLine(ToHtmlParagraph(String.Concat((EventType == EventType.Error ? Resources.Err_Msg_Label : String.Empty), " ", Message), "gsp_event_h1"));
AddHtmlEventSummary(sb);
AddEventSection(sb, EventItem.FormVariables);
AddEventSection(sb, EventItem.Cookies);
AddEventSection(sb, EventItem.SessionVariables);
AddEventSection(sb, EventItem.ServerVariables);
}
/// <summary>
/// Add HTML formatted text to <paramref name="sb" /> that contains summary information about the current error.
/// </summary>
/// <param name="sb">The StringBuilder to add HTML data to.</param>
private void AddHtmlEventSummary(StringBuilder sb)
{
sb.AppendLine(ToHtmlParagraph(Resources.Err_Summary, "gsp_event_h2"));
sb.AppendLine("<table cellpadding='0' cellspacing='0' class='gsp_event_table'>");
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.Url), ToHtmlValue(EventItem.Url));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.Timestamp), ToHtmlValue(EventItem.Timestamp));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.ExType), ToHtmlValue(EventItem.ExType));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.Message), ToHtmlValue(EventItem.Message));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.ExSource), ToHtmlValue(EventItem.ExSource));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.ExTargetSite), ToHtmlValue(EventItem.ExTargetSite));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.ExStackTrace), ToHtmlValue(EventItem.ExStackTrace));
if (EventData.Count > 0)
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.ExData), ToHtmlValue(EventItem.ExData));
if (!String.IsNullOrEmpty(InnerExType))
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExType), ToHtmlValue(EventItem.InnerExType));
if (!String.IsNullOrEmpty(InnerExMessage))
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExMessage), ToHtmlValue(EventItem.InnerExMessage));
if (!String.IsNullOrEmpty(InnerExSource))
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExSource), ToHtmlValue(EventItem.InnerExSource));
if (!String.IsNullOrEmpty(InnerExTargetSite))
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExTargetSite), ToHtmlValue(EventItem.InnerExTargetSite));
if (!String.IsNullOrEmpty(InnerExStackTrace))
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExStackTrace), ToHtmlValue(EventItem.InnerExStackTrace));
if (InnerExData.Count > 0)
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.InnerExData), ToHtmlValue(EventItem.InnerExData));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.EventId), ToHtmlValue(EventItem.EventId));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.GalleryId), ToHtmlValue(EventItem.GalleryId));
sb.AppendFormat("<tr><td class='gsp_event_col1'>{0}</td><td class='gsp_event_col2'>{1}</td></tr>\n", ToHtmlName(EventItem.HttpUserAgent), ToHtmlValue(EventItem.HttpUserAgent));
sb.AppendLine("</table>");
}
/// <summary>
/// Guarantee that <paramref name="value" /> contains a space character at least every 70 characters, inserting one if necessary.
/// Use this function to prepare text that will be sent to an HTML rendering engine. Without a space character to assist the
/// engine with line breaks, the text may be rendered in a single line, forcing the user to scroll to the right.
/// </summary>
/// <param name="value">The string to process.</param>
/// <returns>
/// Returns <paramref name="value" /> with a space character inserted as needed.
/// </returns>
private static string MakeHtmlLineWrapFriendly(string value)
{
const int maxLineLength = 70;
int numCharsSinceSpace = 0;
if (String.IsNullOrEmpty(value))
return String.Empty;
if (value.Length < maxLineLength)
return value;
var sb = new StringBuilder(value.Length + 20);
foreach (var ch in value)
{
sb.Append(ch);
if (numCharsSinceSpace > maxLineLength)
{
sb.Append(" ");
numCharsSinceSpace = 0;
}
numCharsSinceSpace++;
if (char.IsWhiteSpace(ch))
numCharsSinceSpace = 0;
}
return sb.ToString();
}
/// <summary>
/// Add an HTML formatted section to <paramref name="sb" /> with data related to <paramref name="item" />.
/// </summary>
/// <param name="sb">The StringBuilder to add HTML data to.</param>
/// <param name="item">The <see cref="EventItem" /> value specifying the error section to build.</param>
private void AddEventSection(StringBuilder sb, EventItem item)
{
sb.AppendLine(ToHtmlParagraph(item, "gsp_event_h2"));
sb.AppendLine(ToHtmlTable(item));
}
private void ExtractVersion()
{
_eventData.Add(new KeyValuePair<string, string>("Version", GalleryDataSchemaVersionEnumHelper.ConvertGalleryDataSchemaVersionToString(Data.GalleryDb.DataSchemaVersion)));
}
#endregion