Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EventLog.cs « diagnosticts « system « monitoring « services « System « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1c8e71440db50159d988da901715385cb53d0809 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
//------------------------------------------------------------------------------
// <copyright file="EventLog.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

//#define RETRY_ON_ALL_ERRORS

namespace System.Diagnostics {
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Diagnostics;
    using System;
    using Microsoft.Win32;
    using Microsoft.Win32.SafeHandles;
    using System.IO;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Globalization;
    using System.ComponentModel.Design;
    using System.Security;
    using System.Security.Permissions;
    using System.Reflection;
    using System.Runtime.Versioning;
    using System.Runtime.CompilerServices;
    using System.Diagnostics.CodeAnalysis;

    /// <devdoc>
    ///    <para>
    ///       Provides interaction with Windows 2000 event logs.
    ///    </para>
    /// </devdoc>
    [
    DefaultEvent("EntryWritten"),
    InstallerType("System.Diagnostics.EventLogInstaller, " + AssemblyRef.SystemConfigurationInstall),
    MonitoringDescription(SR.EventLogDesc)
    ]
    public class EventLog : Component, ISupportInitialize {

        private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog";
        internal const string DllName = "EventLogMessages.dll";
        private const string eventLogMutexName = "netfxeventlog.1.0";

        private const int DefaultMaxSize = 512 * 1024;
        private const int DefaultRetention = 7 * SecondsPerDay;
        private const int SecondsPerDay = 60 * 60 * 24;

        private EventLogInternal m_underlyingEventLog;
        
        // Whether we need backward compatible OS patch work or not
        private static volatile bool s_CheckedOsVersion; 
        private static volatile bool s_SkipRegPatch;

        private static bool SkipRegPatch {
            get {
                if (!s_CheckedOsVersion) {
                    OperatingSystem os = Environment.OSVersion;
                    s_SkipRegPatch = (os.Platform == PlatformID.Win32NT) && (os.Version.Major > 5);
                    s_CheckedOsVersion = true;
                }
                return s_SkipRegPatch;
            }
        }

        internal static PermissionSet _UnsafeGetAssertPermSet() {
            // SEC_NOTE: All callers should already be guarded by EventLogPermission demand.
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            // We need RegistryPermission 
            RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
            permissionSet.AddPermission(registryPermission);

            // It is not enough to just assert RegistryPermission, for some regkeys
            // we need to assert EnvironmentPermission too
            EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
            permissionSet.AddPermission(environmentPermission);

            // For remote machine registry access UnmanagdCodePermission is required.
            SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            permissionSet.AddPermission(securityPermission);

            return permissionSet;
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Diagnostics.EventLog'/>
        ///       class.
        ///    </para>
        /// </devdoc>
        public EventLog() : this("", ".", "") {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public EventLog(string logName) : this(logName, ".", "") {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public EventLog(string logName, string machineName) : this(logName, machineName, "") {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public EventLog(string logName, string machineName, string source) {
            m_underlyingEventLog = new EventLogInternal(logName, machineName, source, this);
        }

        /// <devdoc>
        ///    <para>
        ///       Gets the contents of the event log.
        ///    </para>
        /// </devdoc>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [MonitoringDescription(SR.LogEntries)]
        public EventLogEntryCollection Entries {
            get {
                return m_underlyingEventLog.Entries;
            }
        }

        /// <devdoc>
        ///    <para>
        ///    </para>
        /// </devdoc>
        [Browsable(false)]
        public string LogDisplayName {
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
            get {
                return m_underlyingEventLog.LogDisplayName;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the name of the log to read from and write to.
        ///    </para>
        /// </devdoc>
        [TypeConverter("System.Diagnostics.Design.LogConverter, " + AssemblyRef.SystemDesign)]
        [ReadOnly(true)]
        [MonitoringDescription(SR.LogLog)]
        [DefaultValue("")]
        [SettingsBindable(true)]
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "Microsoft: Safe, oldLog.machineName doesn't change")]
        [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Microsoft: By design, see justification above assert")]
        public string Log {
            get {
                return m_underlyingEventLog.Log;
            }
            set {
                EventLogInternal newLog = new EventLogInternal(value, m_underlyingEventLog.MachineName, m_underlyingEventLog.Source, this);
                EventLogInternal oldLog = m_underlyingEventLog;

                // EnableRaisingEvents and Close demand Write permission but that permission might be removed upstack
                // previously we didn't call Close() since we were reusing the same object.  We assert the permission here.
                new EventLogPermission(EventLogPermissionAccess.Write, oldLog.machineName).Assert();
                if (oldLog.EnableRaisingEvents) {
                    newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
                    newLog.EnableRaisingEvents = true;
                }
                m_underlyingEventLog = newLog;
                oldLog.Close();
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the name of the computer on which to read or write events.
        ///    </para>
        /// </devdoc>
        [ReadOnly(true)]
        [MonitoringDescription(SR.LogMachineName)]
        [DefaultValue(".")]
        [SettingsBindable(true)]
        [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Microsoft: By design, see justification above assert")]
        public string MachineName {
            get {
                return m_underlyingEventLog.MachineName;
            }
            set {
                EventLogInternal newLog = new EventLogInternal(m_underlyingEventLog.logName, value, m_underlyingEventLog.sourceName, this);
                EventLogInternal oldLog = m_underlyingEventLog;

                // EnableRaisingEvents and Close demand Write permission but that permission might be removed upstack
                // previously we didn't call Close() since we were reusing the same object.  We assert the permission here.
                new EventLogPermission(EventLogPermissionAccess.Write, oldLog.machineName).Assert();
                if (oldLog.EnableRaisingEvents) {
                    newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
                    newLog.EnableRaisingEvents = true;
                }
                m_underlyingEventLog = newLog;
                oldLog.Close();
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Browsable(false)]
        [ComVisible(false)]
        public long MaximumKilobytes {
            get {
                return m_underlyingEventLog.MaximumKilobytes;
            }

            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
            set {
                m_underlyingEventLog.MaximumKilobytes = value;
            }
        }

        [Browsable(false)]
        [ComVisible(false)]
        public OverflowAction OverflowAction {
            get {
                return m_underlyingEventLog.OverflowAction;
            }
        }

        [Browsable(false)]
        [ComVisible(false)]
        public int MinimumRetentionDays {
            get {
                return m_underlyingEventLog.MinimumRetentionDays;
            }
        }

        // EventLogInternal needs to know if the component is in design mode but
        // the DesignMode property is protected.
        internal bool ComponentDesignMode {
            get {
                return this.DesignMode;
            }
        }

        // Expose for EventLogInternal
        internal object ComponentGetService(Type service) {
            return GetService(service);
        }

        /// <devdoc>
        /// </devdoc>
        [Browsable(false)]
        [MonitoringDescription(SR.LogMonitoring)]
        [DefaultValue(false)]
        public bool EnableRaisingEvents {
            get {
                return m_underlyingEventLog.EnableRaisingEvents;
            }
            set {
                m_underlyingEventLog.EnableRaisingEvents = value;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Represents the object used to marshal the event handler
        ///       calls issued as a result of an <see cref='System.Diagnostics.EventLog'/>
        ///       change.
        ///    </para>
        /// </devdoc>
        [Browsable(false)]
        [DefaultValue(null)]
        [MonitoringDescription(SR.LogSynchronizingObject)]
        public ISynchronizeInvoke SynchronizingObject {
        [HostProtection(Synchronization=true)]
            get {
                return m_underlyingEventLog.SynchronizingObject;
            }

            set {
                m_underlyingEventLog.SynchronizingObject = value;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or
        ///       sets the application name (source name) to register and use when writing to the event log.
        ///    </para>
        /// </devdoc>
        [ReadOnly(true)]
        [TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)]
        [MonitoringDescription(SR.LogSource)]
        [DefaultValue("")]
        [SettingsBindable(true)]
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "Microsoft: Safe, oldLog.machineName doesn't change")]
        [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Microsoft: By design, see justification above assert")]
        public string Source {
            get {
                return m_underlyingEventLog.Source;
            }
            set {
                EventLogInternal newLog = new EventLogInternal(m_underlyingEventLog.Log, m_underlyingEventLog.MachineName, CheckAndNormalizeSourceName(value), this);
                EventLogInternal oldLog = m_underlyingEventLog;

                // EnableRaisingEvents and Close demand Write permission but that permission might be removed upstack
                // previously we didn't call Close() since we were reusing the same object.  We assert the permission here.
                new EventLogPermission(EventLogPermissionAccess.Write, oldLog.machineName).Assert();
                if (oldLog.EnableRaisingEvents) {
                    newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
                    newLog.EnableRaisingEvents = true;
                }
                m_underlyingEventLog = newLog;
                oldLog.Close();
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Occurs when an entry is written to the event log.
        ///    </para>
        /// </devdoc>
        [MonitoringDescription(SR.LogEntryWritten)]
        public event EntryWrittenEventHandler EntryWritten {
            add {
                m_underlyingEventLog.EntryWritten += value;
            }
            remove {
                m_underlyingEventLog.EntryWritten -= value;
            }
        }

        /// <devdoc>
        /// </devdoc>
        public void BeginInit() {
            m_underlyingEventLog.BeginInit();
        }

        /// <devdoc>
        ///    <para>
        ///       Clears
        ///       the event log by removing all entries from it.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]  // Should anyone ever call this, other than an event log viewer?
        [ResourceConsumption(ResourceScope.Machine)]
        public void Clear() {
            m_underlyingEventLog.Clear();
        }

        /// <devdoc>
        ///    <para>
        ///       Closes the event log and releases read and write handles.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        public void Close() {
            m_underlyingEventLog.Close();
        }

        /// <devdoc>
        ///    <para> Establishes an application, using the
        ///       specified <see cref='System.Diagnostics.EventLog.Source'/> , as a valid event source for
        ///       writing entries
        ///       to a log on the local computer. This method
        ///       can also be used to create
        ///       a new custom log on the local computer.</para>
        /// </devdoc>
        public static void CreateEventSource(string source, string logName) {
            CreateEventSource(new EventSourceCreationData(source, logName, "."));
        }

        /// <devdoc>
        ///    <para>Establishes an application, using the specified
        ///    <see cref='System.Diagnostics.EventLog.Source'/> as a valid event source for writing
        ///       entries to a log on the computer
        ///       specified by <paramref name="machineName"/>. This method can also be used to create a new
        ///       custom log on the given computer.</para>
        /// </devdoc>
        [Obsolete("This method has been deprecated.  Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        public static void CreateEventSource(string source, string logName, string machineName) {
            CreateEventSource(new EventSourceCreationData(source, logName, machineName));
        }

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public static void CreateEventSource(EventSourceCreationData sourceData) {
            if (sourceData == null)
                throw new ArgumentNullException("sourceData");

            string logName = sourceData.LogName;
            string source = sourceData.Source;
            string machineName = sourceData.MachineName;

            // verify parameters
            Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Checking arguments");
            if (!SyntaxCheck.CheckMachineName(machineName)) {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }
            if (logName == null || logName.Length==0)
                logName = "Application";
            if (!ValidLogName(logName, false))
                throw new ArgumentException(SR.GetString(SR.BadLogName));
            if (source == null || source.Length==0)
                throw new ArgumentException(SR.GetString(SR.MissingParameter, "source"));
            if (source.Length + EventLogKey.Length > 254)
                throw new ArgumentException(SR.GetString(SR.ParameterTooLong, "source", 254 - EventLogKey.Length));

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            Mutex mutex = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
                Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Calling SourceExists");
                if (SourceExists(source, machineName, true)) {
                    Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: SourceExists returned true");
                    // don't let them register a source if it already exists
                    // this makes more sense than just doing it anyway, because the source might
                    // be registered under a different log name, and we don't want to create
                    // duplicates.
                    if (".".Equals(machineName))
                        throw new ArgumentException(SR.GetString(SR.LocalSourceAlreadyExists, source));
                    else
                        throw new ArgumentException(SR.GetString(SR.SourceAlreadyExists, source, machineName));
                }

                Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting DllPath");

                //SECREVIEW: Note that EventLog permission is demanded above.
                PermissionSet permissionSet = _UnsafeGetAssertPermSet();
                permissionSet.Assert();
                
                RegistryKey baseKey = null;
                RegistryKey eventKey = null;
                RegistryKey logKey = null;
                RegistryKey sourceLogKey = null;
                RegistryKey sourceKey = null;
                try {
                    Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting local machine regkey");
                    if (machineName == ".")
                        baseKey = Registry.LocalMachine;
                    else
                        baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);

                    eventKey = baseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog", true);
                    if (eventKey == null) {
                        if (!".".Equals(machineName))
                            throw new InvalidOperationException(SR.GetString(SR.RegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source, machineName));
                        else
                            throw new InvalidOperationException(SR.GetString(SR.LocalRegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source));
                    }

                    // The event log system only treats the first 8 characters of the log name as
                    // significant. If they're creating a new log, but that new log has the same
                    // first 8 characters as another log, the system will think they're the same.
                    // Throw an exception to let them know.
                    logKey = eventKey.OpenSubKey(logName, true);
                    if (logKey == null && logName.Length >= 8) {

                        // check for Windows embedded logs file names
                        string logNameFirst8 = logName.Substring(0,8);
                        if ( string.Compare(logNameFirst8,"AppEvent",StringComparison.OrdinalIgnoreCase) ==0  ||
                             string.Compare(logNameFirst8,"SecEvent",StringComparison.OrdinalIgnoreCase) ==0  ||
                             string.Compare(logNameFirst8,"SysEvent",StringComparison.OrdinalIgnoreCase) ==0 )
                            throw new ArgumentException(SR.GetString(SR.InvalidCustomerLogName, logName));

                        string sameLogName = FindSame8FirstCharsLog(eventKey, logName);
                        if ( sameLogName != null )
                            throw new ArgumentException(SR.GetString(SR.DuplicateLogName, logName, sameLogName));
                    }

                    bool createLogKey = (logKey == null);
                    if (createLogKey) {
                        if (SourceExists(logName, machineName, true)) {
                            // don't let them register a log name that already
                            // exists as source name, a source with the same
                            // name as the log will have to be created by default
                            if (".".Equals(machineName))
                                throw new ArgumentException(SR.GetString(SR.LocalLogAlreadyExistsAsSource, logName));
                            else
                                throw new ArgumentException(SR.GetString(SR.LogAlreadyExistsAsSource, logName, machineName));
                        }

                        logKey = eventKey.CreateSubKey(logName);
                                                                        
                        // NOTE: We shouldn't set "Sources" explicitly, the OS will automatically set it.
                        // The EventLog service doesn't use it for anything it is just an helping hand for event viewer filters.
                        // Writing this value explicitly might confuse the service as it might perceive it as a change and 
                        // start initializing again

                        if (!SkipRegPatch) 
                            logKey.SetValue("Sources", new string[] {logName, source}, RegistryValueKind.MultiString);

                        SetSpecialLogRegValues(logKey, logName);

                        // A source with the same name as the log has to be created
                        // by default. It is the behavior expected by EventLog API.
                        sourceLogKey = logKey.CreateSubKey(logName);
                        SetSpecialSourceRegValues(sourceLogKey, sourceData);
                    }

                    if (logName != source) {
                        if (!createLogKey) {
                            SetSpecialLogRegValues(logKey, logName);
                                                        
                            if (!SkipRegPatch) {
                                string[] sources = logKey.GetValue("Sources") as string[];
                                if (sources == null)
                                    logKey.SetValue("Sources", new string[] {logName, source}, RegistryValueKind.MultiString);
                                else {
                                    // We have a ---- with OS EventLog here.
                                    // OS might update Sources as well. We should avoid writing the 
                                    // source name if OS beats us.
                                    if( Array.IndexOf(sources, source) == -1) {
                                        string[] newsources = new string[sources.Length + 1];
                                        Array.Copy(sources, newsources, sources.Length);
                                        newsources[sources.Length] = source;
                                        logKey.SetValue("Sources", newsources, RegistryValueKind.MultiString);
                                    }
                                }
                            }
                        }

                        sourceKey = logKey.CreateSubKey(source);
                        SetSpecialSourceRegValues(sourceKey, sourceData);
                    }
                }
                finally {
                    if (baseKey != null) 
                        baseKey.Close();

                    if (eventKey != null)
                        eventKey.Close();

                    if (logKey != null) {
                        logKey.Flush();
                        logKey.Close();
                    }

                    if (sourceLogKey != null) {
                        sourceLogKey.Flush();
                        sourceLogKey.Close();
                    }

                    if (sourceKey != null) {
                        sourceKey.Flush();
                        sourceKey.Close();
                    }

                    // Revert registry and environment permission asserts
                    CodeAccessPermission.RevertAssert();
                }
            }
            finally {
                if (mutex != null) {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Removes
        ///       an event
        ///       log from the local computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]   // See why someone would delete an event log
        [ResourceConsumption(ResourceScope.Machine)]
        public static void Delete(string logName) {
            Delete(logName, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Removes
        ///       an
        ///       event
        ///       log from the specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]   // See why someone would delete an event log
        [ResourceConsumption(ResourceScope.Machine)]
        public static void Delete(string logName, string machineName) {

            if (!SyntaxCheck.CheckMachineName(machineName))
                throw new ArgumentException(SR.GetString(SR.InvalidParameterFormat, "machineName"));
            if (logName == null || logName.Length==0)
                throw new ArgumentException(SR.GetString(SR.NoLogName));
            if (!ValidLogName(logName, false))
                throw new InvalidOperationException(SR.GetString(SR.BadLogName));

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            //Check environment before even trying to play with the registry
            SharedUtils.CheckEnvironment();

            //SECREVIEW: Note that EventLog permission is demanded above.
            PermissionSet permissionSet = _UnsafeGetAssertPermSet();
            permissionSet.Assert();
            
            RegistryKey eventlogkey = null;

            Mutex mutex = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutex(eventLogMutexName, ref mutex);

                try {
                    eventlogkey  = GetEventLogRegKey(machineName, true);
                    if (eventlogkey  == null) {
                        // there's not even an event log service on the machine.
                        // or, more likely, we don't have the access to read the registry.
                        throw new InvalidOperationException(SR.GetString(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName));
                    }

                    using (RegistryKey logKey = eventlogkey.OpenSubKey(logName)) {
                        if (logKey == null)
                            throw new InvalidOperationException(SR.GetString(SR.MissingLog, logName, machineName));

                        //clear out log before trying to delete it
                        //that way, if we can't delete the log file, no entries will persist because it has been cleared
                        EventLog logToClear = new EventLog(logName, machineName);
                        try {
                            logToClear.Clear();
                        }
                        finally {
                            logToClear.Close();
                        }

                        // 


                        string filename = null;
                        try {
                            //most of the time, the "File" key does not exist, but we'll still give it a whirl
                            filename = (string) logKey.GetValue("File");
                        }
                        catch { }
                        if (filename != null) {
                            try {
                                File.Delete(filename);
                            }
                            catch { }
                        }
                    }

                    // now delete the registry entry
                    eventlogkey.DeleteSubKeyTree(logName);
                }
                finally {
                    if (eventlogkey != null) eventlogkey.Close();
                
                    // Revert registry and environment permission asserts
                    CodeAccessPermission.RevertAssert();
                }
            }
            finally {
                if (mutex != null) mutex.ReleaseMutex();
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Removes the event source
        ///       registration from the event log of the local computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public static void DeleteEventSource(string source) {
            DeleteEventSource(source, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Removes
        ///       the application's event source registration from the specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static void DeleteEventSource(string source, string machineName) {
            if (!SyntaxCheck.CheckMachineName(machineName)) {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            //Check environment before looking at the registry
            SharedUtils.CheckEnvironment();

            //SECREVIEW: Note that EventLog permission is demanded above.
            PermissionSet permissionSet = _UnsafeGetAssertPermSet();
            permissionSet.Assert();
            
            Mutex mutex = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
                RegistryKey key = null;

                // First open the key read only so we can do some checks.  This is important so we get the same 
                // exceptions even if we don't have write access to the reg key. 
                using (key = FindSourceRegistration(source, machineName, true)) {
                    if (key == null) {
                        if (machineName == null)
                            throw new ArgumentException(SR.GetString(SR.LocalSourceNotRegistered, source));
                        else
                            throw new ArgumentException(SR.GetString(SR.SourceNotRegistered, source, machineName, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog"));
                    }
            
                    // Check parent registry key (Event Log Name) and if it's equal to source, then throw an exception.
                    // The reason: each log registry key must always contain subkey (i.e. source) with the same name.
                    string keyname = key.Name;
                    int index = keyname.LastIndexOf('\\');
                    if ( string.Compare(keyname, index+1, source, 0, keyname.Length - index, StringComparison.Ordinal) == 0 )
                        throw new InvalidOperationException(SR.GetString(SR.CannotDeleteEqualSource, source));
                }

                try {
                    // now open it read/write to try to do the actual delete
                    key = FindSourceRegistration(source, machineName, false);
                    key.DeleteSubKeyTree(source);
                                        
                    if (!SkipRegPatch) { 
                        string[] sources = (string[]) key.GetValue("Sources");
                        ArrayList newsources = new ArrayList(sources.Length - 1);

                        for (int i=0; i<sources.Length; i++) {
                            if (sources[i] != source) {
                                newsources.Add(sources[i]);
                            }
                        }
                        string[] newsourcesArray = new string[newsources.Count];
                        newsources.CopyTo(newsourcesArray);

                        key.SetValue("Sources", newsourcesArray, RegistryValueKind.MultiString);
                    }
                }
                finally {
                    if (key != null) {
                        key.Flush();
                        key.Close();
                    }
                
                    // Revert registry and environment permission asserts
                    CodeAccessPermission.RevertAssert();
                }
            }
            finally {
                if (mutex != null)
                    mutex.ReleaseMutex();
            }
        }

        /// <devdoc>
        /// </devdoc>
        protected override void Dispose(bool disposing) {
            if(m_underlyingEventLog != null) {
                m_underlyingEventLog.Dispose(disposing);
            }

            base.Dispose(disposing);
        }

        /// <devdoc>
        /// </devdoc>
        public void EndInit() {
            m_underlyingEventLog.EndInit();
        }

        /// <devdoc>
        ///    <para>
        ///       Determines whether the log
        ///       exists on the local computer.
        ///    </para>
        /// </devdoc>
        public static bool Exists(string logName) {
            return Exists(logName, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Determines whether the
        ///       log exists on the specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public static bool Exists(string logName, string machineName) {
            if (!SyntaxCheck.CheckMachineName(machineName))
                throw new ArgumentException(SR.GetString(SR.InvalidParameterFormat, "machineName"));

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            if (logName == null || logName.Length==0)
                return false;

            //Check environment before looking at the registry
            SharedUtils.CheckEnvironment();

            //SECREVIEW: Note that EventLog permission is demanded above.
            PermissionSet permissionSet = _UnsafeGetAssertPermSet();
            permissionSet.Assert();
            
            RegistryKey eventkey = null;
            RegistryKey logKey = null;

            try {
                eventkey = GetEventLogRegKey(machineName, false);
                if (eventkey == null)
                    return false;

                logKey = eventkey.OpenSubKey(logName, false);         // try to find log file key immediately.
                return (logKey != null );
            }
            finally {
                if (eventkey != null) eventkey.Close();
                if (logKey != null) logKey.Close();
                
                // Revert registry and environment permission asserts
                CodeAccessPermission.RevertAssert();
            }
        }


        // Try to find log file name with the same 8 first characters.
        // Returns 'null' if no "same first 8 chars" log is found.   logName.Length must be > 7
        private static string FindSame8FirstCharsLog(RegistryKey keyParent, string logName) {

            string logNameFirst8 = logName.Substring(0, 8);
            string[] logNames = keyParent.GetSubKeyNames();

            for (int i = 0; i < logNames.Length; i++) {
                string currentLogName = logNames[i];
                if ( currentLogName.Length >= 8  &&
                     string.Compare(currentLogName.Substring(0, 8), logNameFirst8, StringComparison.OrdinalIgnoreCase) == 0)
                    return currentLogName;
            }

            return null;   // not found
        }

        /// <devdoc>
        ///     Gets a RegistryKey that points to the LogName entry in the registry that is
        ///     the parent of the given source on the given machine, or null if none is found.
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly) {
            return FindSourceRegistration(source, machineName, readOnly, false);
        }

        /// <devdoc>
        ///     Gets a RegistryKey that points to the LogName entry in the registry that is
        ///     the parent of the given source on the given machine, or null if none is found.
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate) {
            if (source != null && source.Length != 0) {

                //Check environment before looking at the registry
                SharedUtils.CheckEnvironment();

                //SECREVIEW: Any call to this function must have demmanded
                //                         EventLogPermission before.
                PermissionSet permissionSet = _UnsafeGetAssertPermSet();
                permissionSet.Assert();
                
                RegistryKey eventkey = null;
                try {
                    eventkey = GetEventLogRegKey(machineName, !readOnly);
                    if (eventkey == null) {
                        // there's not even an event log service on the machine.
                        // or, more likely, we don't have the access to read the registry.
                        return null;
                    }

                    StringBuilder inaccessibleLogs = null;
                    
                    // Most machines will return only { "Application", "System", "Security" },
                    // but you can create your own if you want.
                    string[] logNames = eventkey.GetSubKeyNames();
                    for (int i = 0; i < logNames.Length; i++) {
                        // see if the source is registered in this log.
                        // NOTE: A source name must be unique across ALL LOGS!
                        RegistryKey sourceKey = null;
                        try {
                            RegistryKey logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly);
                            if (logKey != null) {
                                sourceKey = logKey.OpenSubKey(source, /*writable*/!readOnly);
                                if (sourceKey != null) {
                                    // found it
                                    return logKey;
                                } else {
                                    logKey.Close();
                                }
                            }
                            // else logKey is null, so we don't need to Close it
                        }
                        catch (UnauthorizedAccessException) {
                            if (inaccessibleLogs == null) {
                                inaccessibleLogs = new StringBuilder(logNames[i]);
                            }
                            else {
                                inaccessibleLogs.Append(", ");
                                inaccessibleLogs.Append(logNames[i]);
                            }
                        }
                        catch (SecurityException) {
                            if (inaccessibleLogs == null) {
                                inaccessibleLogs = new StringBuilder(logNames[i]);
                            }
                            else {
                                inaccessibleLogs.Append(", ");
                                inaccessibleLogs.Append(logNames[i]);
                            }
                        }
                        finally {
                            if (sourceKey != null) sourceKey.Close();
                        }
                    }

                    if (inaccessibleLogs != null)
                        throw new SecurityException(SR.GetString(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs.ToString()));
                    
                }
                finally {
                    if (eventkey != null) eventkey.Close();
                    
                    // Revert registry and environment permission asserts
                    CodeAccessPermission.RevertAssert();
                }
                // didn't see it anywhere
            }

            return null;
        }

        /// <devdoc>
        ///    <para>
        ///       Searches for all event logs on the local computer and
        ///       creates an array of <see cref='System.Diagnostics.EventLog'/>
        ///       objects to contain the
        ///       list.
        ///    </para>
        /// </devdoc>
        public static EventLog[] GetEventLogs() {
            return GetEventLogs(".");
        }

        /// <devdoc>
        ///    <para>
        ///       Searches for all event logs on the given computer and
        ///       creates an array of <see cref='System.Diagnostics.EventLog'/>
        ///       objects to contain the
        ///       list.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public static EventLog[] GetEventLogs(string machineName) {
            if (!SyntaxCheck.CheckMachineName(machineName)) {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            //Check environment before looking at the registry
            SharedUtils.CheckEnvironment();

            string[] logNames = new string[0];
            //SECREVIEW: Note that EventLogPermission is just demmanded above
            PermissionSet permissionSet = _UnsafeGetAssertPermSet();
            permissionSet.Assert();
            
            RegistryKey eventkey = null;
            try {
                // we figure out what logs are on the machine by looking in the registry.
                eventkey = GetEventLogRegKey(machineName, false);
                if (eventkey == null)
                    // there's not even an event log service on the machine.
                    // or, more likely, we don't have the access to read the registry.
                    throw new InvalidOperationException(SR.GetString(SR.RegKeyMissingShort, EventLogKey, machineName));
                // Most machines will return only { "Application", "System", "Security" },
                // but you can create your own if you want.
                logNames = eventkey.GetSubKeyNames();
            }
            finally {
                if (eventkey != null) eventkey.Close();
                // Revert registry and environment permission asserts
                CodeAccessPermission.RevertAssert();
            }

            // now create EventLog objects that point to those logs
            EventLog[] logs = new EventLog[logNames.Length];
            for (int i = 0; i < logNames.Length; i++) {
                EventLog log = new EventLog(logNames[i], machineName);
                logs[i] = log;
            }

            return logs;
        }

        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        internal static RegistryKey GetEventLogRegKey(string machine, bool writable) {
            RegistryKey lmkey = null;
            
            try {
                if (machine.Equals(".")) {
                    lmkey = Registry.LocalMachine;
                }
                else {
                    lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine);

                }
                if (lmkey != null)
                    return lmkey.OpenSubKey(EventLogKey, writable);
            }
            finally {
                if (lmkey != null) lmkey.Close();
            }

            return null;
        }

        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        internal static string GetDllPath(string machineName) {
            return Path.Combine(SharedUtils.GetLatestBuildDllDirectory(machineName), DllName);
        }

        /// <devdoc>
        ///    <para>
        ///       Determines whether an event source is registered on the local computer.
        ///    </para>
        /// </devdoc>
        public static bool SourceExists(string source) {
            return SourceExists(source, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Determines whether an event
        ///       source is registered on a specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public static bool SourceExists(string source, string machineName) {
            return SourceExists(source, machineName, false);
        }

        /// <devdoc>
        ///    <para>
        ///       Determines whether an event
        ///       source is registered on a specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "Microsoft: Safe, machineName doesn't change")]
        internal static bool SourceExists(string source, string machineName, bool wantToCreate) {
            if (!SyntaxCheck.CheckMachineName(machineName)) {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }

            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, machineName);
            permission.Demand();

            using (RegistryKey keyFound = FindSourceRegistration(source, machineName, true, wantToCreate)) {
                return (keyFound != null);
            }
        }

        /// <devdoc>
        ///     Gets the name of the log that the given source name is registered in.
        /// </devdoc>
        public static string LogNameFromSourceName(string source, string machineName) {
            EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
            permission.Demand();

            return _InternalLogNameFromSourceName(source, machineName);
        }

        // No permission check, use with care!
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        internal static string _InternalLogNameFromSourceName(string source, string machineName) {
            using (RegistryKey key = FindSourceRegistration(source, machineName, true)) {
                if (key == null)
                    return "";
                else {
                    string name = key.Name;
                    int whackPos = name.LastIndexOf('\\');
                    // this will work even if whackPos is -1
                    return name.Substring(whackPos+1);
                }
            }
        }


        [ComVisible(false)]
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) {
            m_underlyingEventLog.ModifyOverflowPolicy(action, retentionDays);
        }

        [ComVisible(false)]
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public void RegisterDisplayName(string resourceFile, long resourceId) {
            m_underlyingEventLog.RegisterDisplayName(resourceFile, resourceId);
        }

        // The reasoning behind filling these values is historical. WS03 RTM had a ----
        // between registry changes and EventLog service, which made the service wait 2 secs
        // before retrying to see whether all regkey values are present. To avoid this 
        // potential lag (worst case up to n*2 secs where n is the number of required regkeys) 
        // between creation and being able to write events, we started filling some of these
        // values explicitly but for XP and latter OS releases like WS03 SP1 and Vista this 
        // is not necessary and in some cases like the "File" key it's plain wrong to write. 
        private static void SetSpecialLogRegValues(RegistryKey logKey, string logName) {
            // Set all the default values for this log.  AutoBackupLogfiles only makes sense in 
            // Win2000 SP4, WinXP SP1, and Win2003, but it should alright elsewhere. 

            // Since we use this method on the existing system logs as well as our own,
            // we need to make sure we don't overwrite any existing values. 
            if (logKey.GetValue("MaxSize") == null)
                logKey.SetValue("MaxSize", DefaultMaxSize, RegistryValueKind.DWord);
            if (logKey.GetValue("AutoBackupLogFiles") == null)
                logKey.SetValue("AutoBackupLogFiles", 0, RegistryValueKind.DWord);

            if (!SkipRegPatch) { 
                // In Vista, "retention of events for 'n' days" concept is removed
                if (logKey.GetValue("Retention") == null)
                    logKey.SetValue("Retention", DefaultRetention, RegistryValueKind.DWord);
                
                if (logKey.GetValue("File") == null) { 
                    string filename;
                    if (logName.Length > 8)
                        filename = @"%SystemRoot%\System32\config\" + logName.Substring(0,8) + ".evt";
                    else
                        filename = @"%SystemRoot%\System32\config\" + logName + ".evt";

                    logKey.SetValue("File", filename, RegistryValueKind.ExpandString);
                }
            }
        }

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        private static void SetSpecialSourceRegValues(RegistryKey sourceLogKey, EventSourceCreationData sourceData) {
            if (String.IsNullOrEmpty(sourceData.MessageResourceFile))
                sourceLogKey.SetValue("EventMessageFile", GetDllPath(sourceData.MachineName), RegistryValueKind.ExpandString);
            else 
                sourceLogKey.SetValue("EventMessageFile", FixupPath(sourceData.MessageResourceFile), RegistryValueKind.ExpandString);

            if (!String.IsNullOrEmpty(sourceData.ParameterResourceFile))
                sourceLogKey.SetValue("ParameterMessageFile", FixupPath(sourceData.ParameterResourceFile), RegistryValueKind.ExpandString);

            if (!String.IsNullOrEmpty(sourceData.CategoryResourceFile)) {
                sourceLogKey.SetValue("CategoryMessageFile", FixupPath(sourceData.CategoryResourceFile), RegistryValueKind.ExpandString);
                sourceLogKey.SetValue("CategoryCount", sourceData.CategoryCount, RegistryValueKind.DWord);
            }
        }

        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        private static string FixupPath(string path) {
            if (path[0] == '%')
                return path;
            else
                return Path.GetFullPath(path);
        }
        
        // Format message in specific DLL. Return <null> on failure.
        internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) {

            if (insertionStrings.Length == 0) {
                // UnsafeTryFromatMessage will set FORMAT_MESSAGE_IGNORE_INSERTS when calling into the OS 
                // when there are no insertion strings, in this case we don't have to guard against insertionStrings
                // not having enough data since it is unused when FORMAT_MESSAGE_IGNORE_INSERTS is specified
                return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
            }

            // If you pass in an empty array UnsafeTryFormatMessage will just pull out the message.
            string formatString = UnsafeTryFormatMessage(hModule, messageNum, new string[0]);

            if (formatString == null) {
                return null;
            }

            int largestNumber = 0;

            for (int i = 0; i < formatString.Length; i++) {
                if (formatString[i] == '%') {
                    // See if a number follows this, if so, grab the number.
                    if(formatString.Length > i + 1) {
                        StringBuilder sb = new StringBuilder();
                        while (i + 1 < formatString.Length && Char.IsDigit(formatString[i + 1])) {
                            sb.Append(formatString[i + 1]);
                            i++;
                        }

                        // move over the non number character that broke us out of the loop
                        i++;

                        if (sb.Length > 0) {
                            int num = -1;
                            if (Int32.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num)) {
                                largestNumber = Math.Max(largestNumber, num);
                            }
                        }
                    }
                }
            }

            // Replacement strings are 1 indexed.
            if (largestNumber > insertionStrings.Length) {
                string[] newStrings = new string[largestNumber];
                Array.Copy(insertionStrings, newStrings, insertionStrings.Length);
                for (int i = insertionStrings.Length; i < newStrings.Length; i++) {
                    newStrings[i] = "%" + (i + 1);
                }

                insertionStrings = newStrings;
            }

            return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
        }

        // FormatMessageW will AV if you don't pass in enough format strings.  If you call TryFormatMessage we ensure insertionStrings
        // is long enough.  You don't want to call this directly unless you're sure insertionStrings is long enough!
        internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) {
            string msg = null;

            int msgLen = 0;
            StringBuilder buf = new StringBuilder(1024);
            int flags = NativeMethods.FORMAT_MESSAGE_FROM_HMODULE | NativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY;

            IntPtr[] addresses = new IntPtr[insertionStrings.Length];
            GCHandle[] handles = new GCHandle[insertionStrings.Length];
            GCHandle stringsRoot = GCHandle.Alloc(addresses, GCHandleType.Pinned);

            // Make sure that we don't try to pass in a zero length array of addresses.  If there are no insertion strings, 
            // we'll use the FORMAT_MESSAGE_IGNORE_INSERTS flag . 
            // If you change this behavior, make sure you look at TryFormatMessage which depends on this behavior!
            if (insertionStrings.Length == 0) {
                flags |= NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS;
            }
            
            try {
                for (int i=0; i<handles.Length; i++) {
                    handles[i] = GCHandle.Alloc(insertionStrings[i], GCHandleType.Pinned);
                    addresses[i] = handles[i].AddrOfPinnedObject();
                }
                int lastError = NativeMethods.ERROR_INSUFFICIENT_BUFFER;
                while (msgLen == 0 && lastError == NativeMethods.ERROR_INSUFFICIENT_BUFFER) {
                    msgLen = SafeNativeMethods.FormatMessage(
                        flags,
                        hModule,
                        messageNum,
                        0,
                        buf,
                        buf.Capacity,
                        addresses);

                    if (msgLen == 0) {
                        lastError = Marshal.GetLastWin32Error();
                        if (lastError == NativeMethods.ERROR_INSUFFICIENT_BUFFER)
                            buf.Capacity = buf.Capacity * 2;
                    }
                }
            }
            catch {
                msgLen = 0;              // return empty on failure
            }
            finally  {
                for (int i=0; i<handles.Length; i++) {
                    if (handles[i].IsAllocated) handles[i].Free();
                }
                stringsRoot.Free();
            }
            
            if (msgLen > 0) {
                msg = buf.ToString();
                // chop off a single CR/LF pair from the end if there is one. FormatMessage always appends one extra.
                if (msg.Length > 1 && msg[msg.Length-1] == '\n')
                    msg = msg.Substring(0, msg.Length-2);
            }

            return msg;
        }


        // CharIsPrintable used to be Char.IsPrintable, but Jay removed it and
        // is forcing people to use the Unicode categories themselves.  Copied
        // the code here.  
        private static bool CharIsPrintable(char c) {
            UnicodeCategory uc = Char.GetUnicodeCategory(c);
            return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) ||
                    (uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) ||
            (uc == UnicodeCategory.OtherNotAssigned));
        }

        // SECREVIEW: Make sure this method catches all the strange cases.
        internal static bool ValidLogName(string logName, bool ignoreEmpty) {
            // No need to trim here since the next check will verify that there are no spaces.
            // We need to ignore the empty string as an invalid log name sometimes because it can
            // be passed in from our default constructor.
            if (logName.Length == 0 && !ignoreEmpty)
                return false;

            //any space, backslash, asterisk, or question mark is bad
            //any non-printable characters are also bad
            foreach (char c in logName)
                if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?'))
                    return false;

            return true;
        }

        /// <devdoc>
        ///    <para>
        ///       Writes an information type entry with the given message text to the event log.
        ///    </para>
        /// </devdoc>
        public void WriteEntry(string message) {
            WriteEntry(message, EventLogEntryType.Information, (short) 0, 0, null);
        }

        /// <devdoc>
        /// </devdoc>
        public static void WriteEntry(string source, string message) {
            WriteEntry(source, message, EventLogEntryType.Information, (short) 0, 0, null);
        }

        /// <devdoc>
        ///    <para>
        ///       Writes an entry of the specified <see cref='System.Diagnostics.EventLogEntryType'/> to the event log. Valid types are
        ///    <see langword='Error'/>, <see langword='Warning'/>, <see langword='Information'/>,
        ///    <see langword='Success Audit'/>, and <see langword='Failure Audit'/>.
        ///    </para>
        /// </devdoc>
        public void WriteEntry(string message, EventLogEntryType type) {
            WriteEntry(message, type, (short) 0, 0, null);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void WriteEntry(string source, string message, EventLogEntryType type) {
            WriteEntry(source, message, type, (short) 0, 0, null);
        }

        /// <devdoc>
        ///    <para>
        ///       Writes an entry of the specified <see cref='System.Diagnostics.EventLogEntryType'/>
        ///       and with the
        ///       user-defined <paramref name="eventID"/>
        ///       to
        ///       the event log.
        ///    </para>
        /// </devdoc>
        public void WriteEntry(string message, EventLogEntryType type, int eventID) {
            WriteEntry(message, type, eventID, 0, null);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID) {
            WriteEntry(source, message, type, eventID, 0, null);
        }

        /// <devdoc>
        ///    <para>
        ///       Writes an entry of the specified type with the
        ///       user-defined <paramref name="eventID"/> and <paramref name="category"/>
        ///       to the event log. The <paramref name="category"/>
        ///       can be used by the event viewer to filter events in the log.
        ///    </para>
        /// </devdoc>
        public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) {
            WriteEntry(message, type, eventID, category, null);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category) {
            WriteEntry(source, message, type, eventID, category, null);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category,
                               byte[] rawData) {
            using (EventLogInternal log = new EventLogInternal("", ".", CheckAndNormalizeSourceName(source))) {
                log.WriteEntry(message, type, eventID, category, rawData);
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Writes an entry of the specified type with the
        ///       user-defined <paramref name="eventID"/> and <paramref name="category"/> to the event log, and appends binary data to
        ///       the message. The Event Viewer does not interpret this data; it
        ///       displays raw data only in a combined hexadecimal and text format.
        ///    </para>
        /// </devdoc>
        public void WriteEntry(string message, EventLogEntryType type, int eventID, short category,
                               byte[] rawData) {

            m_underlyingEventLog.WriteEntry(message, type, eventID, category, rawData);
        }

        [ComVisible(false)]
        public void WriteEvent(EventInstance instance, params Object[] values) {
            WriteEvent(instance, null, values);
        }

        [ComVisible(false)]
        public void WriteEvent(EventInstance instance, byte[] data, params Object[] values) {
            m_underlyingEventLog.WriteEvent(instance, data, values);
        }

        public static void WriteEvent(string source, EventInstance instance, params Object[] values) {
            using (EventLogInternal log = new EventLogInternal("", ".", CheckAndNormalizeSourceName(source))) {
                log.WriteEvent(instance, null, values);
            }
        }

        public static void WriteEvent(string source, EventInstance instance, byte[] data, params Object[] values) {
            using (EventLogInternal log = new EventLogInternal("", ".", CheckAndNormalizeSourceName(source))) {
                log.WriteEvent(instance, data, values);
            }
        }

        // The EventLog.set_Source used to do some normalization and throw some exceptions.  We mimic that behavior here.
        private static string CheckAndNormalizeSourceName(string source) {
            if (source == null)
                source = string.Empty;

            // this 254 limit is the max length of a registry key.
            if (source.Length + EventLogKey.Length > 254)
                throw new ArgumentException(SR.GetString(SR.ParameterTooLong, "source", 254 - EventLogKey.Length));

            return source;
        }
    }

}