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

AbstractDBConnection.cs « System.Data.ProviderBase.jvm « System.Data « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f2c55510fbec729868dfa9070d1f43449610d163 (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
//
// System.Data.Common.AbstractDBConnection
//
// Authors:
//	Konstantin Triger <kostat@mainsoft.com>
//	Boris Kirzner <borisk@mainsoft.com>
//	
// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//


using System.Data;
using System.Data.ProviderBase;
using System.Data.Configuration;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;

using java.sql;
using javax.sql;
using javax.naming;
// can not use java.util here - it manes ArrayList an ambiguous reference

namespace System.Data.Common
{
	public abstract class AbstractDBConnection : DbConnection
	{
		#region ObjectNamesHelper

		private sealed class ObjectNamesHelper
		{
			//static readonly Regex NameOrder = new Regex(@"^\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			static readonly Regex NameOrder = new Regex(@"^((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

			//static readonly Regex SchemaNameOrder = new Regex(@"^\s*((\[(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			static readonly Regex SchemaNameOrder = new Regex(@"^((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			//static readonly Regex CatalogSchemaNameOrder = new Regex(@"^\s*((\[\s*(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			//static readonly Regex CatalogSchemaNameOrder = new Regex(@"^\s*((\[\s*(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<SCHEMA>(\s*[^\]\s])+)\s*\])|(?<SCHEMA>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			static readonly Regex CatalogSchemaNameOrder = new Regex(@"^((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

			//static readonly Regex CatalogNameOrder = new Regex(@"^\s*((\[(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			//static readonly Regex CatalogNameOrder = new Regex(@"^\s*((\[(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			static readonly Regex CatalogNameOrder = new Regex(@"^((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			//static readonly Regex SchemaCatalogNameOrder = new Regex(@"^\s*((\[\s*(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			//static readonly Regex SchemaCatalogNameOrder = new Regex(@"^\s*((\[\s*(?<SCHEMA>(\s*[^\]\s])+)\s*\])|(?<SCHEMA>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
			static readonly Regex SchemaCatalogNameOrder = new Regex(@"^((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

			internal static ObjectNameResolver[] GetSyntaxPatterns(AbstractDBConnection connection)
			{
				ArrayList collection = new ArrayList();
				collection.Add(new ObjectNameResolver(NameOrder));

				ObjectNameResolversCollection basic = (ObjectNameResolversCollection)ConfigurationSettings.GetConfig("system.data/objectnameresolution");
				
				DatabaseMetaData metaData = connection.JdbcConnection.getMetaData();
				string productName = metaData.getDatabaseProductName();

				foreach(ObjectNameResolver nameResolver in basic) {
					if (productName.IndexOf(nameResolver.DbName) != -1) {
						collection.Add(nameResolver);
					}
				}

				//defaults
				if (metaData.isCatalogAtStart()) {
					collection.Add(new ObjectNameResolver(SchemaNameOrder));
					collection.Add(new ObjectNameResolver(CatalogNameOrder));
					collection.Add(new ObjectNameResolver(CatalogSchemaNameOrder));
					collection.Add(new ObjectNameResolver(SchemaCatalogNameOrder));
				}
				else {
					collection.Add(new ObjectNameResolver(CatalogNameOrder));
					collection.Add(new ObjectNameResolver(SchemaNameOrder));
					collection.Add(new ObjectNameResolver(SchemaCatalogNameOrder));
					collection.Add(new ObjectNameResolver(CatalogSchemaNameOrder));
				}

				return (ObjectNameResolver[])collection.ToArray(typeof(ObjectNameResolver));				
			}
		}

		#endregion // ObjectNamesHelper

		#region ConnectionStringHelper

		internal sealed class ConnectionStringHelper
		{
			internal static string FindValue(NameValueCollection collection, string[] keys)
			{
				if (collection == null || keys == null || keys.Length == 0) {
					return String.Empty;
				}

				for(int i=0; i < keys.Length; i++) {
					string value = FindValue(collection,keys[i]);
					if (!String.Empty.Equals(value)) {
						return value;
					}
				}
				return String.Empty;
			}

			internal static string FindValue(NameValueCollection collection, string key)
			{
				if (collection == null) {
					return String.Empty;
				}

				string value = collection[key];
				return (value != null) ? value : String.Empty;
			}

			internal static void UpdateValue(NameValueCollection collection,string[] keys,string value)
			{
				for(int i=0; i < keys.Length; i++) {
					if (collection[keys[i]] != null) {
						collection[keys[i]] = value;
					}
				}
			}

			internal static void AddValue(NameValueCollection collection,string[] keys,string value)
			{
				for(int i=0; i < keys.Length; i++) {
					collection[keys[i]] = value;
				}
			}

			/**
			* Parses connection string and builds NameValueCollection 
			* for all keys.
			*/ 
			internal static NameValueCollection BuildUserParameters (string connectionString)
			{
				NameValueCollection userParameters = new NameValueCollection();

				if (connectionString == null || connectionString.Length == 0) {
					return userParameters;
				}
				connectionString += ";";

				bool inQuote = false;
				bool inDQuote = false;
				bool inName = true;

				string name = String.Empty;
				string value = String.Empty;
				StringBuilder sb = new StringBuilder ();

				for (int i = 0; i < connectionString.Length; i += 1) {
					char c = connectionString [i];
					char peek;
					if (i == connectionString.Length - 1)
						peek = '\0';
					else
						peek = connectionString [i + 1];

					switch (c) {
						case '\'':
							if (inDQuote)
								sb.Append (c);
							else if (peek.Equals(c)) {
								sb.Append(c);
								i += 1;
							}
							else
								inQuote = !inQuote;
							break;
						case '"':
							if (inQuote)
								sb.Append(c);
							else if (peek.Equals(c)) {
								sb.Append(c);
								i += 1;
							}
							else
								inDQuote = !inDQuote;
							break;
						case ';':
							if (inDQuote || inQuote)
								sb.Append(c);
							else {
								if (name != String.Empty && name != null) {
									value = sb.ToString();
									userParameters [name.Trim()] = value.Trim();
								}
								inName = true;
								name = String.Empty;
								value = String.Empty;
								sb = new StringBuilder();
							}
							break;
						case '=':
							if (inDQuote || inQuote || !inName)
								sb.Append (c);
							else if (peek.Equals(c)) {
								sb.Append (c);
								i += 1;
							}
							else {
								name = sb.ToString();
								sb = new StringBuilder();
								inName = false;
							}
							break;
						case ' ':
							if (inQuote || inDQuote)
								sb.Append(c);
							else if (sb.Length > 0 && !peek.Equals(';'))
								sb.Append(c);
							break;
						default:
							sb.Append(c);
							break;
					}
				}
				return userParameters;
			}
		}

		#endregion // ConnectionStringHelper

		#region DataSourceCache

		private sealed class DataSourceCache : AbstractDbMetaDataCache
		{
			internal DataSource GetDataSource(string dataSourceName,string namingProviderUrl,string namingFactoryInitial)
			{
				Hashtable cache = Cache;

				DataSource ds = cache[dataSourceName] as DataSource;

				if (ds != null) {
					return ds;
				}

				Context ctx = null;
				
				java.util.Properties properties = new java.util.Properties();

				if ((namingProviderUrl != null) && (namingProviderUrl.Length > 0)) {
					properties.put("java.naming.provider.url",namingProviderUrl);
				}
				
				if ((namingFactoryInitial != null) && (namingFactoryInitial.Length > 0)) {
					properties.put("java.naming.factory.initial",namingFactoryInitial);
				}

				ctx = new InitialContext(properties);
 
				try {
					ds = (DataSource)ctx.lookup(dataSourceName);
				}
				catch(javax.naming.NameNotFoundException e) {
					// possible that is a Tomcat bug,
					// so try to lookup for jndi datasource with "java:comp/env/" appended
					ds = (DataSource)ctx.lookup("java:comp/env/" + dataSourceName);
				}

				cache[dataSourceName] = ds;
				return ds;
			}
		}

		#endregion // DatasourceCache

		#region Declarations

		protected internal enum JDBC_MODE { NONE, DATA_SOURCE_MODE, JDBC_DRIVER_MODE, PROVIDER_MODE }
		protected internal enum PROVIDER_TYPE { NONE, SQLOLEDB, MSDAORA, IBMDADB2 }

		#endregion // Declarations
		
		#region Fields

		private static DataSourceCache _dataSourceCache = new DataSourceCache();
		private const int DEFAULT_TIMEOUT = 15;

		private Connection _jdbcConnnection;
		private ConnectionState _internalState;
		private object _internalStateSync = new object();

		private NameValueCollection _userParameters;

		protected string _connectionString = String.Empty;
		protected string _jdbcUrl;		

		private ArrayList _referencedObjects = new ArrayList();	
		private ObjectNameResolver[] _syntaxPatterns;

		#endregion // Fields

		#region Constructors

		public AbstractDBConnection(string connectionString)
		{
			_connectionString = connectionString;
			InitializeSkippedUserParameters();
		}

		#endregion // Constructors

		#region Properties

		public override String ConnectionString
		{
			get { return _connectionString; }
			set {
				if (IsOpened) {
					throw ExceptionHelper.NotAllowedWhileConnectionOpen("ConnectionString",_internalState);
				}					
				_connectionString = value;
				_userParameters = null;
				_jdbcUrl = null;
			}
		}

		public override int ConnectionTimeout
		{
			get {
				string timeoutStr = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_TIMEOUT"));
				if (!String.Empty.Equals(timeoutStr)) {
					try {
						return Convert.ToInt32(timeoutStr);
					}
					catch(FormatException e) {
						throw ExceptionHelper.InvalidValueForKey("connect timeout");
					}
					catch (OverflowException e) {
						throw ExceptionHelper.InvalidValueForKey("connect timeout");
					}
				}
				return DEFAULT_TIMEOUT;
			}
		}

		public override String Database
		{
			get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATABASE")); }
		}

		public override ConnectionState State
		{
			get {
				try {
					if ((JdbcConnection == null) || JdbcConnection.isClosed()) {
						// jdbc connection not initialized or closed
						if (_internalState == ConnectionState.Closed ) {
							return ConnectionState.Closed;
						}
					}
					else {
						// jdbc connection is opened
						if ((_internalState & ConnectionState.Open) != 0) {
							return ConnectionState.Open;
						}
					}
					return ConnectionState.Broken;										
				}	
				catch (SQLException) {
					return ConnectionState.Broken;
				}				
			}
		}

		internal bool IsExecuting
		{
			get { 
				return ((_internalState & ConnectionState.Executing) != 0);
			}

			set {
				lock(_internalStateSync) {
					// to switch to executing, the connection must be in opened
					if (value) {
						if (_internalState != ConnectionState.Open) {
							if (IsFetching) {
								throw ExceptionHelper.OpenedReaderExists();
							}
							throw ExceptionHelper.OpenConnectionRequired("",_internalState);
						}
						_internalState |= ConnectionState.Executing;
					}
					else { 
						if (!IsExecuting) {
							throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Executing.ToString() + " while in state " + _internalState.ToString());
						}
						_internalState &= ~ConnectionState.Executing;
					}
				}
			}
		}

		internal bool IsFetching
		{
			get {
				return ((_internalState & ConnectionState.Fetching) != 0);
			}

			set {
				lock(_internalStateSync) {
					if (value) {
						// to switch to fetching connection must be in opened, executing
						if (((_internalState & ConnectionState.Open) == 0) || ((_internalState & ConnectionState.Executing) == 0)) {
							throw ExceptionHelper.OpenConnectionRequired("",_internalState);
						}
						_internalState |= ConnectionState.Fetching;
					}
					else {
						if (!IsFetching) {
							throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Fetching.ToString() + " while in state " + _internalState.ToString());
						}
						_internalState &= ~ConnectionState.Fetching;
					}
				}
			}
		}

		internal bool IsOpened
		{
			get {
				return ((_internalState & ConnectionState.Open) != 0);
			}

			set {
				lock(_internalStateSync) {			
					if (value) {
						// only connecting connection can be opened
						if ((_internalState != ConnectionState.Connecting)) {
							throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
						}
						_internalState |= ConnectionState.Open;
					}
					else {
						if (!IsOpened) {
							throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Open.ToString() + " while in state " + _internalState.ToString());
						}
						_internalState &= ~ConnectionState.Open;
					}
				}
			}
		}

		internal bool IsConnecting
		{
			get {
				return ((_internalState & ConnectionState.Connecting) != 0);
			}

			set {
				lock(_internalStateSync) {			
					if (value) {
						// to switch to connecting conection must be in closed or in opened
						if ((_internalState != ConnectionState.Closed) && (_internalState != ConnectionState.Open)) {
							throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
						}
						_internalState |= ConnectionState.Connecting;
					}
					else {
						if (!IsConnecting) {
							throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Connecting.ToString() + " while in state " + _internalState.ToString());
						}
						_internalState &= ~ConnectionState.Connecting;
					}
				}
			}
		}

		protected virtual PROVIDER_TYPE ProviderType
		{
			get {
				if (JdbcMode != JDBC_MODE.PROVIDER_MODE) {
					return PROVIDER_TYPE.NONE;
				}
				
				string providerStr = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_PROVIDER")).ToUpper();
				if (providerStr.StartsWith("SQLOLEDB")) {
					return PROVIDER_TYPE.SQLOLEDB;
				}
				else if (providerStr.StartsWith("MSDAORA")) {
					return PROVIDER_TYPE.MSDAORA;
				}
				else if (providerStr.StartsWith("IBMDADB2")) {
					return PROVIDER_TYPE.IBMDADB2;
				}
				return PROVIDER_TYPE.NONE;
			}
		}

		protected internal virtual JDBC_MODE JdbcMode
		{
			get { 
				string[] conJndiNameStr = StringManager.GetStringArray("CON_JNDI_NAME");
				if ( !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,conJndiNameStr))) {
					return JDBC_MODE.DATA_SOURCE_MODE;
				}

				string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
				string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
				bool jdbcDriverSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr));
				bool jdbcUrlSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr));

				if (jdbcDriverSpecified && jdbcUrlSpecified) {
					return JDBC_MODE.JDBC_DRIVER_MODE;
				}

				string[] providerStr = StringManager.GetStringArray("CON_PROVIDER");
				if (!String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,providerStr))) {
					return JDBC_MODE.PROVIDER_MODE;
				}
				
				return JDBC_MODE.NONE;
			}
		}

		protected virtual string JdbcDriverName
		{
			get { return String.Empty; }
		}

		protected abstract DbStringManager StringManager
		{
			get;
		}

		protected virtual string ServerName
		{
			get { return DataSource; }
		}

		protected virtual string CatalogName
		{
			get { return Database; }
		}

		protected virtual string Port
		{
			get {
				string port = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_PORT"));
				switch (ProviderType) {
					case PROVIDER_TYPE.SQLOLEDB : 
						if (String.Empty.Equals(port)) {
							try {
								port = DbPortResolver.getMSSqlPort(this).ToString();
							}
							catch (SQLException e) {
								throw CreateException(e);
							}
						}

						ConnectionStringHelper.AddValue(UserParameters,StringManager.GetStringArray("CON_PORT"),port);
						break;
				}
				return port;
			}
		}

		public override string DataSource
		{
			get {
				string dataSource = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATA_SOURCE"));

				if (ProviderType == PROVIDER_TYPE.SQLOLEDB) {
					int instanceIdx;
					if ((instanceIdx = dataSource.IndexOf("\\")) != -1) {
						// throw out named instance name
						dataSource = dataSource.Substring(0,instanceIdx);
					}

					if (dataSource != null && dataSource.StartsWith("(") && dataSource.EndsWith(")")) {						
						dataSource = dataSource.Substring(1,dataSource.Length - 2);
					}

					if(String.Empty.Equals(dataSource) || (String.Compare("local",dataSource,true) == 0)) {
						dataSource = "localhost";
					}
				}
				return dataSource;
			}
		}

		internal string InstanceName
		{
			get {
				string dataSource = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATA_SOURCE"));
				string instanceName = String.Empty;
				if (ProviderType == PROVIDER_TYPE.SQLOLEDB) {
					int instanceIdx;
					if ((instanceIdx = dataSource.IndexOf("\\")) == -1) {
						// no named instance specified - use a default name
						instanceName = StringManager.GetString("SQL_DEFAULT_INSTANCE_NAME");
					}
					else {
						// get named instance name
						instanceName = dataSource.Substring(instanceIdx + 1);
					}
				}
				return instanceName;
			}
		}

		protected virtual string User
		{
			get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_USER_ID")); }
		}

		protected virtual string Password
		{
			get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_PASSWORD")); }
		}

		protected NameValueCollection UserParameters
		{
			get {
				if (_userParameters == null) {
					_userParameters = ConnectionStringHelper.BuildUserParameters(ConnectionString);
				}
				return _userParameters;
			}
		}

		internal String JdbcUrl 
		{
			get { 
				if ( UserParameters == null) {
					return String.Empty;
				}

				if (_jdbcUrl == null) {
					_jdbcUrl = BuildJdbcUrl();
				}
				return _jdbcUrl;
			}
		}

		internal ConnectionState InternalState
		{
			get	{ return _internalState; }
		}


		protected internal Connection JdbcConnection
		{
			get { return _jdbcConnnection; }
			set { _jdbcConnnection = value; }
		}

		protected virtual string[] ResourceIgnoredKeys
		{
			get { return new string[0]; }
		}

		protected virtual Hashtable SkippedUserParameters
		{
			get { return new Hashtable(new CaseInsensitiveHashCodeProvider(),new CaseInsensitiveComparer()); }
		}

		internal ObjectNameResolver[] SyntaxPatterns
		{
			get {
				if (_syntaxPatterns == null) {
					_syntaxPatterns = ObjectNamesHelper.GetSyntaxPatterns(this);
				}
				return _syntaxPatterns;
			}
		}

		#endregion // Properties

		#region Methods
			// since WS also does not permits dynamically change of login timeout and tomcat does no implements - do not do it at all
			//ds.setLoginTimeout(ConnectionTimeout);

		internal abstract void OnSqlWarning(SQLWarning warning);

		internal abstract void OnStateChanged(ConnectionState orig, ConnectionState current);

		protected abstract SystemException CreateException(SQLException e);

		protected abstract SystemException CreateException(string message);

		public override void Close()
		{
			try {
				ClearReferences();
				if (JdbcConnection != null && !JdbcConnection.isClosed()) {
					JdbcConnection.close();
				}
			}
			catch (SQLException e) {
				// suppress exception
				JdbcConnection = null;
#if DEBUG
				Console.WriteLine("Exception catched at Conection.Close() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
#endif
			}
			catch (Exception e) {
				// suppress exception
				JdbcConnection = null;
#if DEBUG
				Console.WriteLine("Exception catched at Conection.Close() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
#endif
			}
			finally {
				lock(_internalStateSync) {
					_internalState = ConnectionState.Closed;
				}
			}
		}

		protected internal virtual void CopyTo(AbstractDBConnection target)
		{
			target._connectionString = _connectionString;
		}

		internal protected virtual void OnSqlException(SQLException exp)
		{
			throw CreateException(exp);
		}

		internal void AddReference(object referencedObject)
		{	lock(_referencedObjects.SyncRoot) {
				_referencedObjects.Add(new WeakReference(referencedObject));
			}
		}

		internal void RemoveReference(object referencedObject)
		{
			lock(_referencedObjects.SyncRoot) {
				for(int i = 0; i < _referencedObjects.Count; i++) {
					WeakReference wr = (WeakReference) _referencedObjects[i];
					if (wr.IsAlive && (wr.Target == referencedObject)) {
						_referencedObjects.RemoveAt(i);
					}
				}
			}
		}

		private void ClearReferences()
		{
			ArrayList oldList = _referencedObjects;
			_referencedObjects = new ArrayList();

			for(int i = 0; i < oldList.Count; i++) {
				WeakReference wr = (WeakReference) oldList[i];
				if (wr.IsAlive) {
					ClearReference(wr.Target);
				}
			}
		}

		private void ClearReference(object referencedObject)
		{
			try {
				if (referencedObject is AbstractDbCommand) {
					((AbstractDbCommand)referencedObject).CloseInternal();
				}
				else if (referencedObject is AbstractDataReader) {
					((AbstractDataReader)referencedObject).CloseInternal();
				}
			}
			catch (SQLException) {
				// suppress exception since it's possible that command or reader are in inconsistent state
			}
		}

		public override void Open()
		{
			if (_connectionString == null || _connectionString.Length == 0) {
				throw ExceptionHelper.ConnectionStringNotInitialized();
			}

			IsConnecting = true;
			try {			
				if (JdbcConnection != null && !JdbcConnection.isClosed()) {
					throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
				}
	
				switch(JdbcMode) {
					case JDBC_MODE.DATA_SOURCE_MODE :
						JdbcConnection = GetConnectionFromDataSource();
						break;

					case JDBC_MODE.JDBC_DRIVER_MODE:
						JdbcConnection = GetConnectionFromJdbcDriver();
						break;

					case JDBC_MODE.PROVIDER_MODE : 					
						JdbcConnection = GetConnectionFromProvider();
						break;
				}
				IsOpened = true;

				OnStateChanged(ConnectionState.Closed, ConnectionState.Open);
			}
			catch (SQLWarning warning) {
				OnSqlWarning(warning);
			}
			catch (SQLException exp) {
				OnSqlException(exp);
			}
			finally {
				IsConnecting = false;
			}
		}

		public override void ChangeDatabase(String database)
		{
			IsConnecting = true;
			try {
				ClearReferences();
				Connection con = JdbcConnection;				
				con.setCatalog(database);
				ConnectionStringHelper.UpdateValue(UserParameters,StringManager.GetStringArray("CON_DATABASE"),database);
			}
			catch (SQLWarning warning) {
				OnSqlWarning(warning);
			}
			catch (SQLException exp) {
				throw CreateException(exp);
			}
			finally {
				IsConnecting = false;
			}
		}

		public override string ServerVersion {
			get {
				// only if the driver support this methods
				try {
					if (JdbcConnection == null)
						return String.Empty;

					DatabaseMetaData metaData = JdbcConnection.getMetaData();
					return metaData.getDatabaseProductVersion();
				}
				catch (SQLException exp) {
					throw CreateException(exp);
				}
			}
		}

		internal string JdbcProvider {
			get {
				// only if the driver support this methods
				try {
					if (JdbcConnection == null)
						return String.Empty;

					DatabaseMetaData metaData = JdbcConnection.getMetaData();
					return metaData.getDriverName() + " " + metaData.getDriverVersion();
				}
				catch (SQLException exp) {
					return String.Empty; //suppress
				}
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				try {
					if (JdbcConnection != null && !JdbcConnection.isClosed()) {
						JdbcConnection.close();
					}	                
					JdbcConnection = null;
				}
				catch (java.sql.SQLException exp) {
					throw CreateException(exp);
				}
			}
			base.Dispose(disposing);
		}

		protected internal virtual void ValidateConnectionString(string connectionString)
		{
			JDBC_MODE currentJdbcMode = JdbcMode;
			
			if (currentJdbcMode == JDBC_MODE.NONE) {
				string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
				string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
				bool jdbcDriverSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr));
				bool jdbcUrlSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr));

				if (jdbcDriverSpecified ^ jdbcUrlSpecified) {
					throw new ArgumentException("Invalid format of connection string. If you want to use third-party JDBC driver, the format is: \"JdbcDriverClassName=<jdbc driver class name>;JdbcURL=<jdbc url>\"");
				}				
			}
		}

		protected virtual string BuildJdbcUrl()
		{
			switch (JdbcMode) {
				case JDBC_MODE.JDBC_DRIVER_MODE :
					return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("JDBC_URL"));
				default :
					return String.Empty;
			}
		}

		protected java.util.Properties BuildProperties()
		{
			java.util.Properties properties = new java.util.Properties();

			string user = User;
			if (user != null && user.Length > 0)
				properties.put("user", user);
			string password = Password;
			if (user != null && user.Length > 0)
				properties.put("password", password);

			string[] userKeys = UserParameters.AllKeys;

			for(int i=0; i < userKeys.Length; i++) {
				string userKey = userKeys[i];
				string userParameter = UserParameters[userKey];
				if (!SkipUserParameter(userKey)) {
					properties.put(userKey,userParameter);
				}
			}
			return properties;
		}

		protected virtual bool SkipUserParameter(string parameterName)
		{
			if (SkippedUserParameters.Count == 0) {
				// skipped parameters not initialized - skip all
				return true;
			}

			return SkippedUserParameters.Contains(parameterName);
		}

		protected virtual void InitializeSkippedUserParameters()
		{
			if (SkippedUserParameters.Count > 0) {
				return;
			}

			for(int i=0; i < ResourceIgnoredKeys.Length; i++) {
				string[] userKeys = StringManager.GetStringArray(ResourceIgnoredKeys[i]);
				for(int j=0; j < userKeys.Length; j++) {
					SkippedUserParameters.Add(userKeys[j],userKeys[j]);
				}
			}
		}
 
		internal void ValidateBeginTransaction()
		{
			if (State != ConnectionState.Open) {
				throw new InvalidOperationException(String.Format("{0} requires an open and available Connection. The connection's current state is {1}.", new object[] {"BeginTransaction", State}));
			}

			if (!JdbcConnection.getAutoCommit()) {
				throw new System.InvalidOperationException("Parallel transactions are not supported.");
			}
		}

		internal virtual Connection GetConnectionFromProvider()
		{
			ActivateJdbcDriver(JdbcDriverName);
			DriverManager.setLoginTimeout(ConnectionTimeout);
			java.util.Properties properties = BuildProperties();
			return DriverManager.getConnection (JdbcUrl, properties);
		}

		internal Connection GetConnectionFromDataSource()
		{
			string dataSourceJndi = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_NAME"));
			string namingProviderUrl = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_PROVIDER"));
			string namingFactoryInitial = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_FACTORY"));
			DataSource ds = _dataSourceCache.GetDataSource(dataSourceJndi,namingProviderUrl,namingFactoryInitial);
			try {
				ds.setLoginTimeout(ConnectionTimeout);
			}
			catch (java.lang.Exception) {
				// WebSphere does not allows dynamicall change of login timeout
				// setLoginTimeout is not supported yet
				// in Tomcat data source.
				// In this case we work wthout timeout.
			}
			return ds.getConnection();
		}

		internal virtual Connection GetConnectionFromJdbcDriver()
		{
			string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
			string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
		
			string jdbcDriverName = ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr);
			string jdbcUrl = ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr);

			ActivateJdbcDriver(jdbcDriverName);
			DriverManager.setLoginTimeout(ConnectionTimeout);

			java.util.Properties properties = BuildProperties();

			return DriverManager.getConnection(jdbcUrl,properties);
		}

		internal ArrayList GetProcedureColumns(String procedureString, AbstractDbCommand command)
		{
			ArrayList col = new ArrayList();
			try {
				ObjectNameResolver[] nameResolvers = SyntaxPatterns;
				ResultSet res = null;
				string catalog = null;
				string schema = null;
				string spname = null;
						
				DatabaseMetaData metadata = JdbcConnection.getMetaData();	
				bool storesUpperCaseIdentifiers = false;
				bool storesLowerCaseIdentifiers = false;
				try {
					storesUpperCaseIdentifiers = metadata.storesUpperCaseIdentifiers();
					storesLowerCaseIdentifiers = metadata.storesLowerCaseIdentifiers();
				}
				catch (SQLException e) {
					// suppress
				}

				for(int i=0; i < nameResolvers.Length; i++) {
					ObjectNameResolver nameResolver = nameResolvers[i];
					Match match = nameResolver.Match(procedureString);

					if (match.Success) {
						spname = ObjectNameResolver.GetName(match);				
						schema = ObjectNameResolver.GetSchema(match);						
						catalog = ObjectNameResolver.GetCatalog(match);						

						// make all identifiers uppercase or lowercase according to database metadata
						if (storesUpperCaseIdentifiers) {
							spname = (spname.Length > 0) ? spname.ToUpper() : null;
							schema = (schema.Length > 0) ? schema.ToUpper() : null;
							catalog = (catalog.Length > 0) ? catalog.ToUpper() : null;
						}
						else if (storesLowerCaseIdentifiers) {
							spname = (spname.Length > 0) ? spname.ToLower() : null;
							schema = (schema.Length > 0) ? schema.ToLower() : null;
							catalog = (catalog.Length > 0) ? catalog.ToLower() : null;
						}
						else {
							spname = (spname.Length > 0) ? spname : null;
							schema = (schema.Length > 0) ? schema : null;
							catalog = (catalog.Length > 0) ? catalog : null;
						}

						// catalog from db is always in correct caps
						if (catalog == null) {
							catalog = JdbcConnection.getCatalog();
						}

						try {
							// always get the first procedure that db returns
							res = metadata.getProcedures(catalog, schema, spname);												
							if (res.next()) {
								catalog = res.getString(1);
								schema = res.getString(2);
								spname = res.getString(3);
								break;
							}

							spname = null;
						}
						catch { // suppress exception
							return null;
						}
						finally {
							if (res != null) {
								res.close();
							}
						}
					}
				}	
		
				if (spname == null || spname.Length == 0) {
					return null;
				}
				
				try {
					// get procedure columns based o  procedure metadata
					res = metadata.getProcedureColumns(catalog, schema, spname, null);				
					while (res.next()) {
						// since there is still a possibility that some of the parameters to getProcedureColumn were nulls, 
						// we need to filter the results with strict matching
						if ((res.getString(1) != catalog ) || (res.getString(2) != schema) || (res.getString(3) != spname)) {
							continue;
						}

						AbstractDbParameter parameter = (AbstractDbParameter)command.CreateParameter();
						
						parameter.SetParameterName(res);
						parameter.SetParameterDbType(res);
						parameter.SetSpecialFeatures(res);

						//get parameter direction
						short direction = res.getShort("COLUMN_TYPE");
						if(direction == 1) //DatabaseMetaData.procedureColumnIn
							parameter.Direction = ParameterDirection.Input;
						else if(direction == 2) //DatabaseMetaData.procedureColumnInOut
							parameter.Direction = ParameterDirection.InputOutput;
						else if(direction == 4) //DatabaseMetaData.procedureColumnOut
							parameter.Direction = ParameterDirection.Output;
						else if(direction == 5) //DatabaseMetaData.procedureColumnReturn
							parameter.Direction = ParameterDirection.ReturnValue;
					
						//get parameter precision and scale
						parameter.SetParameterPrecisionAndScale(res);

						parameter.SetParameterSize(res);
						parameter.SetParameterIsNullable(res);

						col.Add(parameter);
					}
				}
				finally {
					if (res != null) {
						res.close();
					}
				}				
			}
			catch(Exception e) {
				//supress
#if DEBUG
				Console.WriteLine("Exception catched at AbstractDBConnection.GetProcedureColumns() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
#endif
			}
			return col;
		}

		protected static void ActivateJdbcDriver(string driver)
		{
			if(driver != null) {
				try {
					java.lang.Class.forName(driver).newInstance();
				}
				catch (java.lang.ClassNotFoundException e) {
					throw new TypeLoadException(e.Message);
				}
				catch (java.lang.InstantiationException e) {
					throw new MemberAccessException(e.Message);
				}
                catch (java.lang.IllegalAccessException e) {
					throw new MissingMethodException(e.Message);
				}
			}
		}

		protected String BuildMsSqlUrl()
		{
			return StringManager.GetString("SQL_JDBC_URL") //"jdbc:microsoft:sqlserver://"
				+ ServerName + ":" + Port + ";DatabaseName=" + CatalogName;
		}

		#endregion // Methods	
	}
}