jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more 
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. 
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with 
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
 
// SSCLI 1.0 has no support for ADO.NET
#if !SSCLI
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
 
using log4net.Util;
using log4net.Layout;
using log4net.Core;
 
namespace log4net.Appender
{
    /// <summary>
    /// Appender that logs to a database.
    /// </summary>
    /// <remarks>
    /// <para>
    /// <see cref="AdoNetAppender"/> appends logging events to a table within a
    /// database. The appender can be configured to specify the connection 
    /// string by setting the <see cref="ConnectionString"/> property. 
    /// The connection type (provider) can be specified by setting the <see cref="ConnectionType"/>
    /// property. For more information on database connection strings for
    /// your specific database see <a href="http://www.connectionstrings.com/">http://www.connectionstrings.com/</a>.
    /// </para>
    /// <para>
    /// Records are written into the database either using a prepared
    /// statement or a stored procedure. The <see cref="CommandType"/> property
    /// is set to <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify a prepared statement
    /// or to <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify a stored
    /// procedure.
    /// </para>
    /// <para>
    /// The prepared statement text or the name of the stored procedure
    /// must be set in the <see cref="CommandText"/> property.
    /// </para>
    /// <para>
    /// The prepared statement or stored procedure can take a number
    /// of parameters. Parameters are added using the <see cref="AddParameter"/>
    /// method. This adds a single <see cref="AdoNetAppenderParameter"/> to the
    /// ordered list of parameters. The <see cref="AdoNetAppenderParameter"/>
    /// type may be subclassed if required to provide database specific
    /// functionality. The <see cref="AdoNetAppenderParameter"/> specifies
    /// the parameter name, database type, size, and how the value should
    /// be generated using a <see cref="ILayout"/>.
    /// </para>
    /// </remarks>
    /// <example>
    /// An example of a SQL Server table that could be logged to:
    /// <code lang="SQL">
    /// CREATE TABLE [dbo].[Log] ( 
    ///   [ID] [int] IDENTITY (1, 1) NOT NULL ,
    ///   [Date] [datetime] NOT NULL ,
    ///   [Thread] [varchar] (255) NOT NULL ,
    ///   [Level] [varchar] (20) NOT NULL ,
    ///   [Logger] [varchar] (255) NOT NULL ,
    ///   [Message] [varchar] (4000) NOT NULL 
    /// ) ON [PRIMARY]
    /// </code>
    /// </example>
    /// <example>
    /// An example configuration to log to the above table:
    /// <code lang="XML" escaped="true">
    /// <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender" >
    ///   <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    ///   <connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" />
    ///   <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
    ///   <parameter>
    ///     <parameterName value="@log_date" />
    ///     <dbType value="DateTime" />
    ///     <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
    ///   </parameter>
    ///   <parameter>
    ///     <parameterName value="@thread" />
    ///     <dbType value="String" />
    ///     <size value="255" />
    ///     <layout type="log4net.Layout.PatternLayout" value="%thread" />
    ///   </parameter>
    ///   <parameter>
    ///     <parameterName value="@log_level" />
    ///     <dbType value="String" />
    ///     <size value="50" />
    ///     <layout type="log4net.Layout.PatternLayout" value="%level" />
    ///   </parameter>
    ///   <parameter>
    ///     <parameterName value="@logger" />
    ///     <dbType value="String" />
    ///     <size value="255" />
    ///     <layout type="log4net.Layout.PatternLayout" value="%logger" />
    ///   </parameter>
    ///   <parameter>
    ///     <parameterName value="@message" />
    ///     <dbType value="String" />
    ///     <size value="4000" />
    ///     <layout type="log4net.Layout.PatternLayout" value="%message" />
    ///   </parameter>
    /// </appender>
    /// </code>
    /// </example>
    /// <author>Julian Biddle</author>
    /// <author>Nicko Cadell</author>
    /// <author>Gert Driesen</author>
    /// <author>Lance Nehring</author>
    public class AdoNetAppender : BufferingAppenderSkeleton
    {
        #region Public Instance Constructors
 
        /// <summary> 
        /// Initializes a new instance of the <see cref="AdoNetAppender" /> class.
        /// </summary>
        /// <remarks>
        /// Public default constructor to initialize a new instance of this class.
        /// </remarks>
        public AdoNetAppender()
        {
            m_connectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
            m_useTransactions = true;
            m_commandType = System.Data.CommandType.Text;
            m_parameters = new ArrayList();
            m_reconnectOnError = false;
        }
 
        #endregion // Public Instance Constructors
 
        #region Public Instance Properties
 
        /// <summary>
        /// Gets or sets the database connection string that is used to connect to 
        /// the database.
        /// </summary>
        /// <value>
        /// The database connection string used to connect to the database.
        /// </value>
        /// <remarks>
        /// <para>
        /// The connections string is specific to the connection type.
        /// See <see cref="ConnectionType"/> for more information.
        /// </para>
        /// </remarks>
        /// <example>Connection string for MS Access via ODBC:
        /// <code>"DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb"</code>
        /// </example>
        /// <example>Another connection string for MS Access via ODBC:
        /// <code>"Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;"</code>
        /// </example>
        /// <example>Connection string for MS Access via OLE DB:
        /// <code>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;"</code>
        /// </example>
        public string ConnectionString
        {
            get { return m_connectionString; }
            set { m_connectionString = value; }
        }
 
        /// <summary>
        /// The appSettings key from App.Config that contains the connection string.
        /// </summary>
        public string AppSettingsKey
        {
            get { return m_appSettingsKey; }
            set { m_appSettingsKey = value; }
        }
 
#if NET_2_0
        /// <summary>
        /// The connectionStrings key from App.Config that contains the connection string.
        /// </summary>
        /// <remarks>
        /// This property requires at least .NET 2.0.
        /// </remarks>
        public string ConnectionStringName
        {
            get { return m_connectionStringName; }
            set { m_connectionStringName = value; }
        }
#endif
 
        /// <summary>
        /// Gets or sets the type name of the <see cref="IDbConnection"/> connection
        /// that should be created.
        /// </summary>
        /// <value>
        /// The type name of the <see cref="IDbConnection"/> connection.
        /// </value>
        /// <remarks>
        /// <para>
        /// The type name of the ADO.NET provider to use.
        /// </para>
        /// <para>
        /// The default is to use the OLE DB provider.
        /// </para>
        /// </remarks>
        /// <example>Use the OLE DB Provider. This is the default value.
        /// <code>System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
        /// </example>
        /// <example>Use the MS SQL Server Provider. 
        /// <code>System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
        /// </example>
        /// <example>Use the ODBC Provider. 
        /// <code>Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral</code>
        /// This is an optional package that you can download from 
        /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> 
        /// search for <b>ODBC .NET Data Provider</b>.
        /// </example>
        /// <example>Use the Oracle Provider. 
        /// <code>System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
        /// This is an optional package that you can download from 
        /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> 
        /// search for <b>.NET Managed Provider for Oracle</b>.
        /// </example>
        public string ConnectionType
        {
            get { return m_connectionType; }
            set { m_connectionType = value; }
        }
 
        /// <summary>
        /// Gets or sets the command text that is used to insert logging events
        /// into the database.
        /// </summary>
        /// <value>
        /// The command text used to insert logging events into the database.
        /// </value>
        /// <remarks>
        /// <para>
        /// Either the text of the prepared statement or the
        /// name of the stored procedure to execute to write into
        /// the database.
        /// </para>
        /// <para>
        /// The <see cref="CommandType"/> property determines if
        /// this text is a prepared statement or a stored procedure.
        /// </para>
        /// </remarks>
        public string CommandText
        {
            get { return m_commandText; }
            set { m_commandText = value; }
        }
 
        /// <summary>
        /// Gets or sets the command type to execute.
        /// </summary>
        /// <value>
        /// The command type to execute.
        /// </value>
        /// <remarks>
        /// <para>
        /// This value may be either <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify
        /// that the <see cref="CommandText"/> is a prepared statement to execute, 
        /// or <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify that the
        /// <see cref="CommandText"/> property is the name of a stored procedure
        /// to execute.
        /// </para>
        /// <para>
        /// The default value is <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>).
        /// </para>
        /// </remarks>
        public CommandType CommandType
        {
            get { return m_commandType; }
            set { m_commandType = value; }
        }
 
        /// <summary>
        /// Should transactions be used to insert logging events in the database.
        /// </summary>
        /// <value>
        /// <c>true</c> if transactions should be used to insert logging events in
        /// the database, otherwise <c>false</c>. The default value is <c>true</c>.
        /// </value>
        /// <remarks>
        /// <para>
        /// Gets or sets a value that indicates whether transactions should be used
        /// to insert logging events in the database.
        /// </para>
        /// <para>
        /// When set a single transaction will be used to insert the buffered events
        /// into the database. Otherwise each event will be inserted without using
        /// an explicit transaction.
        /// </para>
        /// </remarks>
        public bool UseTransactions
        {
            get { return m_useTransactions; }
            set { m_useTransactions = value; }
        }
 
        /// <summary>
        /// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method.
        /// </summary>
        /// <value>
        /// The <see cref="SecurityContext"/> used to call the NetSend method.
        /// </value>
        /// <remarks>
        /// <para>
        /// Unless a <see cref="SecurityContext"/> specified here for this appender
        /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
        /// security context to use. The default behavior is to use the security context
        /// of the current thread.
        /// </para>
        /// </remarks>
        public SecurityContext SecurityContext 
        {
            get { return m_securityContext; }
            set { m_securityContext = value; }
        }
 
        /// <summary>
        /// Should this appender try to reconnect to the database on error.
        /// </summary>
        /// <value>
        /// <c>true</c> if the appender should try to reconnect to the database after an
        /// error has occurred, otherwise <c>false</c>. The default value is <c>false</c>, 
        /// i.e. not to try to reconnect.
        /// </value>
        /// <remarks>
        /// <para>
        /// The default behaviour is for the appender not to try to reconnect to the
        /// database if an error occurs. Subsequent logging events are discarded.
        /// </para>
        /// <para>
        /// To force the appender to attempt to reconnect to the database set this
        /// property to <c>true</c>.
        /// </para>
        /// <note>
        /// When the appender attempts to connect to the database there may be a
        /// delay of up to the connection timeout specified in the connection string.
        /// This delay will block the calling application's thread. 
        /// Until the connection can be reestablished this potential delay may occur multiple times.
        /// </note>
        /// </remarks>
        public bool ReconnectOnError
        {
            get { return m_reconnectOnError; }
            set { m_reconnectOnError = value; }
        }
 
        #endregion // Public Instance Properties
 
        #region Protected Instance Properties
 
        /// <summary>
        /// Gets or sets the underlying <see cref="IDbConnection" />.
        /// </summary>
        /// <value>
        /// The underlying <see cref="IDbConnection" />.
        /// </value>
        /// <remarks>
        /// <see cref="AdoNetAppender" /> creates a <see cref="IDbConnection" /> to insert 
        /// logging events into a database.  Classes deriving from <see cref="AdoNetAppender" /> 
        /// can use this property to get or set this <see cref="IDbConnection" />.  Use the 
        /// underlying <see cref="IDbConnection" /> returned from <see cref="Connection" /> if 
        /// you require access beyond that which <see cref="AdoNetAppender" /> provides.
        /// </remarks>
        protected IDbConnection Connection 
        {
            get { return m_dbConnection; }
            set { m_dbConnection = value; }
        }
 
        #endregion // Protected Instance Properties
 
        #region Implementation of IOptionHandler
 
        /// <summary>
        /// Initialize the appender based on the options set
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is part of the <see cref="IOptionHandler"/> delayed object
        /// activation scheme. The <see cref="ActivateOptions"/> method must 
        /// be called on this object after the configuration properties have
        /// been set. Until <see cref="ActivateOptions"/> is called this
        /// object is in an undefined state and must not be used. 
        /// </para>
        /// <para>
        /// If any of the configuration properties are modified then 
        /// <see cref="ActivateOptions"/> must be called again.
        /// </para>
        /// </remarks>
        override public void ActivateOptions() 
        {
            base.ActivateOptions();
 
            // Are we using a command object
            m_usePreparedCommand = (m_commandText != null && m_commandText.Length > 0);
 
            if (m_securityContext == null)
            {
                m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
            }
 
            InitializeDatabaseConnection();
            InitializeDatabaseCommand();
        }
 
        #endregion
 
        #region Override implementation of AppenderSkeleton
 
        /// <summary>
        /// Override the parent method to close the database
        /// </summary>
        /// <remarks>
        /// <para>
        /// Closes the database command and database connection.
        /// </para>
        /// </remarks>
        override protected void OnClose() 
        {
            base.OnClose();
            DisposeCommand(false);
            DiposeConnection();
        }
 
        #endregion
 
        #region Override implementation of BufferingAppenderSkeleton
 
        /// <summary>
        /// Inserts the events into the database.
        /// </summary>
        /// <param name="events">The events to insert into the database.</param>
        /// <remarks>
        /// <para>
        /// Insert all the events specified in the <paramref name="events"/>
        /// array into the database.
        /// </para>
        /// </remarks>
        override protected void SendBuffer(LoggingEvent[] events)
        {
            if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open))
            {
                LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection==null)?SystemInfo.NullText:m_dbConnection.State.ToString()) );
 
                InitializeDatabaseConnection();
                InitializeDatabaseCommand();
            }
 
            // Check that the connection exists and is open
            if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open)
            {
                if (m_useTransactions)
                {
                    // Create transaction
                    // NJC - Do this on 2 lines because it can confuse the debugger
                    IDbTransaction dbTran = null;
                    try
                    {
                        dbTran = m_dbConnection.BeginTransaction();
 
                        SendBuffer(dbTran, events);
 
                        // commit transaction
                        dbTran.Commit();
                    }
                    catch(Exception ex)
                    {
                        // rollback the transaction
                        if (dbTran != null)
                        {
                            try
                            {
                                dbTran.Rollback();
                            }
                            catch(Exception)
                            {
                                // Ignore exception
                            }
                        }
 
                        // Can't insert into the database. That's a bad thing
                        ErrorHandler.Error("Exception while writing to database", ex);
                    }
                }
                else
                {
                    // Send without transaction
                    SendBuffer(null, events);
                }
            }
        }
 
        #endregion // Override implementation of BufferingAppenderSkeleton
 
        #region Public Instance Methods
 
        /// <summary>
        /// Adds a parameter to the command.
        /// </summary>
        /// <param name="parameter">The parameter to add to the command.</param>
        /// <remarks>
        /// <para>
        /// Adds a parameter to the ordered list of command parameters.
        /// </para>
        /// </remarks>
        public void AddParameter(AdoNetAppenderParameter parameter)
        {
            m_parameters.Add(parameter);
        }
 
 
        #endregion // Public Instance Methods
 
        #region Protected Instance Methods
 
        /// <summary>
        /// Writes the events to the database using the transaction specified.
        /// </summary>
        /// <param name="dbTran">The transaction that the events will be executed under.</param>
        /// <param name="events">The array of events to insert into the database.</param>
        /// <remarks>
        /// <para>
        /// The transaction argument can be <c>null</c> if the appender has been
        /// configured not to use transactions. See <see cref="UseTransactions"/>
        /// property for more information.
        /// </para>
        /// </remarks>
        virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
        {
            if (m_usePreparedCommand) 
            {
                // Send buffer using the prepared command object
 
                if (m_dbCommand != null)
                {
                    if (dbTran != null)
                    {
                        m_dbCommand.Transaction = dbTran;
                    }
 
                    // run for all events
                    foreach(LoggingEvent e in events)
                    {
                        // Set the parameter values
                        foreach(AdoNetAppenderParameter param in m_parameters)
                        {
                            param.FormatValue(m_dbCommand, e);
                        }
 
                        // Execute the query
                        m_dbCommand.ExecuteNonQuery();
                    }
                }
            }
            else
            {
                // create a new command
                using(IDbCommand dbCmd = m_dbConnection.CreateCommand())
                {
                    if (dbTran != null)
                    {
                        dbCmd.Transaction = dbTran;
                    }
 
                    // run for all events
                    foreach(LoggingEvent e in events)
                    {
                        // Get the command text from the Layout
                        string logStatement = GetLogStatement(e);
 
                        LogLog.Debug(declaringType, "LogStatement ["+logStatement+"]");
 
                        dbCmd.CommandText = logStatement;
                        dbCmd.ExecuteNonQuery();
                    }
                }
            }
        }
 
        /// <summary>
        /// Formats the log message into database statement text.
        /// </summary>
        /// <param name="logEvent">The event being logged.</param>
        /// <remarks>
        /// This method can be overridden by subclasses to provide 
        /// more control over the format of the database statement.
        /// </remarks>
        /// <returns>
        /// Text that can be passed to a <see cref="System.Data.IDbCommand"/>.
        /// </returns>
        virtual protected string GetLogStatement(LoggingEvent logEvent)
        {
            if (Layout == null)
            {
                ErrorHandler.Error("AdoNetAppender: No Layout specified.");
                return "";
            }
            else
            {
                StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
                Layout.Format(writer, logEvent);
                return writer.ToString();
            }
        }
 
        /// <summary>
        /// Creates an <see cref="IDbConnection"/> instance used to connect to the database.
        /// </summary>
        /// <remarks>
        /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary).
        /// </remarks>
        /// <param name="connectionType">The <see cref="Type"/> of the <see cref="IDbConnection"/> object.</param>
        /// <param name="connectionString">The connectionString output from the ResolveConnectionString method.</param>
        /// <returns>An <see cref="IDbConnection"/> instance with a valid connection string.</returns>
        virtual protected IDbConnection CreateConnection(Type connectionType, string connectionString)
        {
            IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType);
            connection.ConnectionString = connectionString;
            return connection;
        }
 
        /// <summary>
        /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey
        /// property.
        /// </summary>
        /// <remarks>
        /// ConnectiongStringName is only supported on .NET 2.0 and higher.
        /// </remarks>
        /// <param name="connectionStringContext">Additional information describing the connection string.</param>
        /// <returns>A connection string used to connect to the database.</returns>
        virtual protected string ResolveConnectionString(out string connectionStringContext)
        {
            if (m_connectionString != null && m_connectionString.Length > 0)
            {
                connectionStringContext = "ConnectionString";
                return m_connectionString;
            }
 
#if NET_2_0
            if (!String.IsNullOrEmpty(m_connectionStringName))
            {
                ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[m_connectionStringName];
                if (settings != null)
                {
                    connectionStringContext = "ConnectionStringName";
                    return settings.ConnectionString;
                }
                else
                {
                    throw new LogException("Unable to find [" + m_connectionStringName + "] ConfigurationManager.ConnectionStrings item");
                }
            }
#endif
 
            if (m_appSettingsKey != null && m_appSettingsKey.Length > 0)
            {
                connectionStringContext = "AppSettingsKey";
                string appSettingsConnectionString = SystemInfo.GetAppSetting(m_appSettingsKey);
                if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0)
                {
                    throw new LogException("Unable to find [" + m_appSettingsKey + "] AppSettings key.");
                }
                return appSettingsConnectionString;
            }
 
            connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings.";
            return string.Empty;
        }
 
        /// <summary>
        /// Retrieves the class type of the ADO.NET provider.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Gets the Type of the ADO.NET provider to use to connect to the
        /// database. This method resolves the type specified in the 
        /// <see cref="ConnectionType"/> property.
        /// </para>
        /// <para>
        /// Subclasses can override this method to return a different type
        /// if necessary.
        /// </para>
        /// </remarks>
        /// <returns>The <see cref="Type"/> of the ADO.NET provider</returns>
        virtual protected Type ResolveConnectionType()
        {
            try
            {
                return SystemInfo.GetTypeFromString(m_connectionType, true, false);
            }
            catch(Exception ex)
            {
                ErrorHandler.Error("Failed to load connection type ["+m_connectionType+"]", ex);
                throw;
            }
        }
 
        #endregion // Protected Instance Methods
 
        #region Private Instance Methods
 
        /// <summary>
        /// Prepares the database command and initialize the parameters.
        /// </summary>
        private void InitializeDatabaseCommand()
        {
            if (m_dbConnection != null && m_usePreparedCommand)
            {
                try
                {
                    DisposeCommand(false);
 
                    // Create the command object
                    m_dbCommand = m_dbConnection.CreateCommand();
 
                    // Set the command string
                    m_dbCommand.CommandText = m_commandText;
 
                    // Set the command type
                    m_dbCommand.CommandType = m_commandType;
                }
                catch (Exception e)
                {
                    ErrorHandler.Error("Could not create database command [" + m_commandText + "]", e);
 
                    DisposeCommand(true);
                }
 
                if (m_dbCommand != null)
                {
                    try
                    {
                        foreach (AdoNetAppenderParameter param in m_parameters)
                        {
                            try
                            {
                                param.Prepare(m_dbCommand);
                            }
                            catch (Exception e)
                            {
                                ErrorHandler.Error("Could not add database command parameter [" + param.ParameterName + "]", e);
                                throw;
                            }
                        }
                    }
                    catch
                    {
                        DisposeCommand(true);
                    }
                }
 
                if (m_dbCommand != null)
                {
                    try
                    {
                        // Prepare the command statement.
                        m_dbCommand.Prepare();
                    }
                    catch (Exception e)
                    {
                        ErrorHandler.Error("Could not prepare database command [" + m_commandText + "]", e);
 
                        DisposeCommand(true);
                    }
                }
            }
        }
 
        /// <summary>
        /// Connects to the database.
        /// </summary>        
        private void InitializeDatabaseConnection()
        {
            string connectionStringContext = "Unable to determine connection string context.";
            string resolvedConnectionString = string.Empty;
 
            try
            {
                DisposeCommand(true);
                DiposeConnection();
 
                // Set the connection string
                resolvedConnectionString = ResolveConnectionString(out connectionStringContext);
 
                m_dbConnection = CreateConnection(ResolveConnectionType(), resolvedConnectionString);
 
                using (SecurityContext.Impersonate(this))
                {
                    // Open the database connection
                    m_dbConnection.Open();
                }
            }
            catch (Exception e)
            {
                // Sadly, your connection string is bad.
                ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e);
 
                m_dbConnection = null;
            }
        }
 
        /// <summary>
        /// Cleanup the existing command.
        /// </summary>
        /// <param name="ignoreException">
        /// If true, a message will be written using LogLog.Warn if an exception is encountered when calling Dispose.
        /// </param>
        private void DisposeCommand(bool ignoreException)
        {
            // Cleanup any existing command or connection
            if (m_dbCommand != null)
            {
                try
                {
                    m_dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    if (!ignoreException)
                    {
                        LogLog.Warn(declaringType, "Exception while disposing cached command object", ex);
                    }
                }
                m_dbCommand = null;
            }
        }
 
        /// <summary>
        /// Cleanup the existing connection.
        /// </summary>
        /// <remarks>
        /// Calls the IDbConnection's <see cref="IDbConnection.Close"/> method.
        /// </remarks>
        private void DiposeConnection()
        {
            if (m_dbConnection != null)
            {
                try
                {
                    m_dbConnection.Close();
                }
                catch (Exception ex)
                {
                    LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex);
                }
                m_dbConnection = null;
            }
        }
 
        #endregion // Private Instance Methods
 
        #region Protected Instance Fields
 
        /// <summary>
        /// Flag to indicate if we are using a command object
        /// </summary>
        /// <remarks>
        /// <para>
        /// Set to <c>true</c> when the appender is to use a prepared
        /// statement or stored procedure to insert into the database.
        /// </para>
        /// </remarks>
        protected bool m_usePreparedCommand;
 
        /// <summary>
        /// The list of <see cref="AdoNetAppenderParameter"/> objects.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The list of <see cref="AdoNetAppenderParameter"/> objects.
        /// </para>
        /// </remarks>
        protected ArrayList m_parameters;
 
        #endregion // Protected Instance Fields
 
        #region Private Instance Fields
 
        /// <summary>
        /// The security context to use for privileged calls
        /// </summary>
        private SecurityContext m_securityContext;
 
        /// <summary>
        /// The <see cref="IDbConnection" /> that will be used
        /// to insert logging events into a database.
        /// </summary>
        private IDbConnection m_dbConnection;
 
        /// <summary>
        /// The database command.
        /// </summary>
        private IDbCommand m_dbCommand;
 
        /// <summary>
        /// Database connection string.
        /// </summary>
        private string m_connectionString;
 
        /// <summary>
        /// The appSettings key from App.Config that contains the connection string.
        /// </summary>
        private string m_appSettingsKey;
 
#if NET_2_0
        /// <summary>
        /// The connectionStrings key from App.Config that contains the connection string.
        /// </summary>
        private string m_connectionStringName;
#endif
 
        /// <summary>
        /// String type name of the <see cref="IDbConnection"/> type name.
        /// </summary>
        private string m_connectionType;
 
        /// <summary>
        /// The text of the command.
        /// </summary>
        private string m_commandText;
 
        /// <summary>
        /// The command type.
        /// </summary>
        private CommandType m_commandType;
 
        /// <summary>
        /// Indicates whether to use transactions when writing to the database.
        /// </summary>
        private bool m_useTransactions;
 
        /// <summary>
        /// Indicates whether to use transactions when writing to the database.
        /// </summary>
        private bool m_reconnectOnError;
 
        #endregion // Private Instance Fields
 
        #region Private Static Fields
 
        /// <summary>
        /// The fully qualified type of the AdoNetAppender class.
        /// </summary>
        /// <remarks>
        /// Used by the internal logger to record the Type of the
        /// log message.
        /// </remarks>
        private readonly static Type declaringType = typeof(AdoNetAppender);
 
        #endregion Private Static Fields
    }
 
    /// <summary>
    /// Parameter type used by the <see cref="AdoNetAppender"/>.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This class provides the basic database parameter properties
    /// as defined by the <see cref="System.Data.IDbDataParameter"/> interface.
    /// </para>
    /// <para>This type can be subclassed to provide database specific
    /// functionality. The two methods that are called externally are
    /// <see cref="Prepare"/> and <see cref="FormatValue"/>.
    /// </para>
    /// </remarks>
    public class AdoNetAppenderParameter
    {
        #region Public Instance Constructors
 
        /// <summary>
        /// Initializes a new instance of the <see cref="AdoNetAppenderParameter" /> class.
        /// </summary>
        /// <remarks>
        /// Default constructor for the AdoNetAppenderParameter class.
        /// </remarks>
        public AdoNetAppenderParameter()
        {
            m_precision = 0;
            m_scale = 0;
            m_size = 0;
        }
 
        #endregion // Public Instance Constructors
 
        #region Public Instance Properties
 
        /// <summary>
        /// Gets or sets the name of this parameter.
        /// </summary>
        /// <value>
        /// The name of this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The name of this parameter. The parameter name
        /// must match up to a named parameter to the SQL stored procedure
        /// or prepared statement.
        /// </para>
        /// </remarks>
        public string ParameterName
        {
            get { return m_parameterName; }
            set { m_parameterName = value; }
        }
 
        /// <summary>
        /// Gets or sets the database type for this parameter.
        /// </summary>
        /// <value>
        /// The database type for this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The database type for this parameter. This property should
        /// be set to the database type from the <see cref="DbType"/>
        /// enumeration. See <see cref="IDataParameter.DbType"/>.
        /// </para>
        /// <para>
        /// This property is optional. If not specified the ADO.NET provider 
        /// will attempt to infer the type from the value.
        /// </para>
        /// </remarks>
        /// <seealso cref="IDataParameter.DbType" />
        public DbType DbType
        {
            get { return m_dbType; }
            set 
            { 
                m_dbType = value; 
                m_inferType = false;
            }
        }
 
        /// <summary>
        /// Gets or sets the precision for this parameter.
        /// </summary>
        /// <value>
        /// The precision for this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The maximum number of digits used to represent the Value.
        /// </para>
        /// <para>
        /// This property is optional. If not specified the ADO.NET provider 
        /// will attempt to infer the precision from the value.
        /// </para>
        /// </remarks>
        /// <seealso cref="IDbDataParameter.Precision" />
        public byte Precision 
        {
            get { return m_precision; } 
            set { m_precision = value; }
        }
 
        /// <summary>
        /// Gets or sets the scale for this parameter.
        /// </summary>
        /// <value>
        /// The scale for this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The number of decimal places to which Value is resolved.
        /// </para>
        /// <para>
        /// This property is optional. If not specified the ADO.NET provider 
        /// will attempt to infer the scale from the value.
        /// </para>
        /// </remarks>
        /// <seealso cref="IDbDataParameter.Scale" />
        public byte Scale 
        {
            get { return m_scale; }
            set { m_scale = value; }
        }
 
        /// <summary>
        /// Gets or sets the size for this parameter.
        /// </summary>
        /// <value>
        /// The size for this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The maximum size, in bytes, of the data within the column.
        /// </para>
        /// <para>
        /// This property is optional. If not specified the ADO.NET provider 
        /// will attempt to infer the size from the value.
        /// </para>
        /// </remarks>
        /// <seealso cref="IDbDataParameter.Size" />
        public int Size 
        {
            get { return m_size; }
            set { m_size = value; }
        }
 
        /// <summary>
        /// Gets or sets the <see cref="IRawLayout"/> to use to 
        /// render the logging event into an object for this 
        /// parameter.
        /// </summary>
        /// <value>
        /// The <see cref="IRawLayout"/> used to render the
        /// logging event into an object for this parameter.
        /// </value>
        /// <remarks>
        /// <para>
        /// The <see cref="IRawLayout"/> that renders the value for this
        /// parameter.
        /// </para>
        /// <para>
        /// The <see cref="RawLayoutConverter"/> can be used to adapt
        /// any <see cref="ILayout"/> into a <see cref="IRawLayout"/>
        /// for use in the property.
        /// </para>
        /// </remarks>
        public IRawLayout Layout
        {
            get { return m_layout; }
            set { m_layout = value; }
        }
 
        #endregion // Public Instance Properties
 
        #region Public Instance Methods
 
        /// <summary>
        /// Prepare the specified database command object.
        /// </summary>
        /// <param name="command">The command to prepare.</param>
        /// <remarks>
        /// <para>
        /// Prepares the database command object by adding
        /// this parameter to its collection of parameters.
        /// </para>
        /// </remarks>
        virtual public void Prepare(IDbCommand command)
        {
            // Create a new parameter
            IDbDataParameter param = command.CreateParameter();
 
            // Set the parameter properties
            param.ParameterName = m_parameterName;
 
            if (!m_inferType)
            {
                param.DbType = m_dbType;
            }
            if (m_precision != 0)
            {
                param.Precision = m_precision;
            }
            if (m_scale != 0)
            {
                param.Scale = m_scale;
            }
            if (m_size != 0)
            {
                param.Size = m_size;
            }
 
            // Add the parameter to the collection of params
            command.Parameters.Add(param);
        }
 
        /// <summary>
        /// Renders the logging event and set the parameter value in the command.
        /// </summary>
        /// <param name="command">The command containing the parameter.</param>
        /// <param name="loggingEvent">The event to be rendered.</param>
        /// <remarks>
        /// <para>
        /// Renders the logging event using this parameters layout
        /// object. Sets the value of the parameter on the command object.
        /// </para>
        /// </remarks>
        virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent)
        {
            // Lookup the parameter
            IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName];
 
            // Format the value
            object formattedValue = Layout.Format(loggingEvent);
 
            // If the value is null then convert to a DBNull
            if (formattedValue == null)
            {
                formattedValue = DBNull.Value;
            }
 
            param.Value = formattedValue;
        }
 
        #endregion // Public Instance Methods
 
        #region Private Instance Fields
 
        /// <summary>
        /// The name of this parameter.
        /// </summary>
        private string m_parameterName;
 
        /// <summary>
        /// The database type for this parameter.
        /// </summary>
        private DbType m_dbType;
 
        /// <summary>
        /// Flag to infer type rather than use the DbType
        /// </summary>
        private bool m_inferType = true;
 
        /// <summary>
        /// The precision for this parameter.
        /// </summary>
        private byte m_precision;
 
        /// <summary>
        /// The scale for this parameter.
        /// </summary>
        private byte m_scale;
 
        /// <summary>
        /// The size for this parameter.
        /// </summary>
        private int m_size;
 
        /// <summary>
        /// The <see cref="IRawLayout"/> to use to render the
        /// logging event into an object for this parameter.
        /// </summary>
        private IRawLayout m_layout;
 
        #endregion // Private Instance Fields
    }
}
 
#endif // !SSCLI