/
OleDbConnectionStringBuilder.cs
735 lines (674 loc) · 30.2 KB
/
OleDbConnectionStringBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
namespace System.Data.OleDb
{
[DefaultProperty("Provider")]
[RefreshProperties(RefreshProperties.All)]
[TypeConverter(typeof(OleDbConnectionStringBuilder.OleDbConnectionStringBuilderConverter))]
public sealed class OleDbConnectionStringBuilder : DbConnectionStringBuilder
{
private enum Keywords
{
FileName,
Provider,
DataSource,
PersistSecurityInfo,
OleDbServices,
}
private static readonly string[] s_validKeywords = new string[5]
{
DbConnectionStringKeywords.FileName,
DbConnectionStringKeywords.Provider,
DbConnectionStringKeywords.DataSource,
DbConnectionStringKeywords.PersistSecurityInfo,
DbConnectionStringKeywords.OleDbServices
};
private static readonly Dictionary<string, Keywords> s_keywords = new Dictionary<string, Keywords>(5, StringComparer.OrdinalIgnoreCase)
{
{ DbConnectionStringKeywords.FileName, Keywords.FileName },
{ DbConnectionStringKeywords.Provider, Keywords.Provider },
{ DbConnectionStringKeywords.DataSource, Keywords.DataSource },
{ DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo },
{ DbConnectionStringKeywords.OleDbServices, Keywords.OleDbServices },
};
private string[]? _knownKeywords;
private Dictionary<string, OleDbPropertyInfo>? _propertyInfo;
private string _fileName = DbConnectionStringDefaults.FileName;
private string _dataSource = DbConnectionStringDefaults.DataSource;
private string _provider = DbConnectionStringDefaults.Provider;
private int _oleDbServices = DbConnectionStringDefaults.OleDbServices;
private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
public OleDbConnectionStringBuilder() : this(null)
{
_knownKeywords = s_validKeywords;
}
public OleDbConnectionStringBuilder(string? connectionString) : base()
{
if (!ADP.IsEmpty(connectionString))
{
ConnectionString = connectionString;
}
}
[AllowNull]
public override object this[string keyword]
{
get
{
ADP.CheckArgumentNull(keyword, "keyword");
object? value;
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
value = GetAt(index);
}
else if (!base.TryGetValue(keyword, out value))
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
OleDbPropertyInfo info = dynamic[keyword];
value = info._defaultValue!;
}
return value;
}
set
{
if (null != value)
{
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
switch (index)
{
case Keywords.DataSource:
DataSource = ConvertToString(value);
break;
case Keywords.FileName:
FileName = ConvertToString(value);
break;
case Keywords.Provider:
Provider = ConvertToString(value);
break;
case Keywords.OleDbServices:
OleDbServices = ConvertToInt32(value);
break;
case Keywords.PersistSecurityInfo:
PersistSecurityInfo = ConvertToBoolean(value);
break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
else
{
base[keyword] = value;
ClearPropertyDescriptors();
}
}
else
{
Remove(keyword);
}
}
}
[DisplayName(DbConnectionStringKeywords.DataSource)]
[RefreshProperties(RefreshProperties.All)]
// TODO: hand off to editor VS, if SQL - do database names, if Jet do file picker
public string DataSource
{
get { return _dataSource; }
set
{
SetValue(DbConnectionStringKeywords.DataSource, value);
_dataSource = value;
}
}
[DisplayName(DbConnectionStringKeywords.FileName)]
[Editor("System.Windows.Forms.Design.FileNameEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[RefreshProperties(RefreshProperties.All)]
// TODO: hand off to VS, they derive from FileNameEditor and set the OpenDialogFilter to *.UDL
public string FileName
{
get { return _fileName; }
set
{
SetValue(DbConnectionStringKeywords.FileName, value);
_fileName = value;
}
}
[DisplayName(DbConnectionStringKeywords.OleDbServices)]
[RefreshProperties(RefreshProperties.All)]
[TypeConverter(typeof(OleDbConnectionStringBuilder.OleDbServicesConverter))]
public int OleDbServices
{
get { return _oleDbServices; }
set
{
SetValue(DbConnectionStringKeywords.OleDbServices, value);
_oleDbServices = value;
}
}
[DisplayName(DbConnectionStringKeywords.PersistSecurityInfo)]
[RefreshProperties(RefreshProperties.All)]
public bool PersistSecurityInfo
{
get { return _persistSecurityInfo; }
set
{
SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
_persistSecurityInfo = value;
}
}
[DisplayName(DbConnectionStringKeywords.Provider)]
[RefreshProperties(RefreshProperties.All)]
[TypeConverter(typeof(OleDbConnectionStringBuilder.OleDbProviderConverter))]
public string Provider
{
get { return _provider; }
set
{
SetValue(DbConnectionStringKeywords.Provider, value);
_provider = value;
RestartProvider();
}
}
public override ICollection Keys
{
get
{
string[]? knownKeywords = _knownKeywords;
if (null == knownKeywords)
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
if (0 < dynamic.Count)
{
knownKeywords = new string[s_validKeywords.Length + dynamic.Count];
s_validKeywords.CopyTo(knownKeywords, 0);
dynamic.Keys.CopyTo(knownKeywords, s_validKeywords.Length);
}
else
{
knownKeywords = s_validKeywords;
}
int count = 0;
foreach (string keyword in base.Keys)
{
bool flag = true;
foreach (string s in knownKeywords)
{
if (StringComparer.OrdinalIgnoreCase.Equals(s, keyword))
{
flag = false;
break;
}
}
if (flag)
{
count++;
}
}
if (0 < count)
{
string[] tmp = new string[knownKeywords.Length + count];
knownKeywords.CopyTo(tmp, 0);
int index = knownKeywords.Length;
foreach (string keyword in base.Keys)
{
bool flag = true;
foreach (string s in knownKeywords)
{
if (StringComparer.OrdinalIgnoreCase.Equals(s, keyword))
{
flag = false;
break;
}
}
if (flag)
{
tmp[index++] = keyword;
}
}
knownKeywords = tmp;
}
_knownKeywords = knownKeywords;
}
return new System.Data.Common.ReadOnlyCollection<string>(knownKeywords);
}
}
public override bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
return s_keywords.ContainsKey(keyword) || base.ContainsKey(keyword);
}
private static bool ConvertToBoolean(object value)
{
return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
}
private static int ConvertToInt32(object value)
{
return DbConnectionStringBuilderUtil.ConvertToInt32(value);
}
private static string ConvertToString(object value)
{
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
public override void Clear()
{
base.Clear();
for (int i = 0; i < s_validKeywords.Length; ++i)
{
Reset((Keywords)i);
}
base.ClearPropertyDescriptors();
_knownKeywords = s_validKeywords;
}
private object GetAt(Keywords index)
{
switch (index)
{
case Keywords.DataSource:
return DataSource;
case Keywords.FileName:
return FileName;
case Keywords.OleDbServices:
return OleDbServices;
case Keywords.PersistSecurityInfo:
return PersistSecurityInfo;
case Keywords.Provider:
return Provider;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
public override bool Remove(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
bool value = base.Remove(keyword);
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
Reset(index);
}
else if (value)
{
ClearPropertyDescriptors();
}
return value;
}
private void Reset(Keywords index)
{
switch (index)
{
case Keywords.DataSource:
_dataSource = DbConnectionStringDefaults.DataSource;
break;
case Keywords.FileName:
_fileName = DbConnectionStringDefaults.FileName;
RestartProvider();
break;
case Keywords.OleDbServices:
_oleDbServices = DbConnectionStringDefaults.OleDbServices;
break;
case Keywords.PersistSecurityInfo:
_persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
break;
case Keywords.Provider:
_provider = DbConnectionStringDefaults.Provider;
RestartProvider();
break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
private new void ClearPropertyDescriptors()
{
base.ClearPropertyDescriptors();
_knownKeywords = null;
}
private void RestartProvider()
{
ClearPropertyDescriptors();
_propertyInfo = null;
}
private void SetValue(string keyword, bool value)
{
base[keyword] = value.ToString(null);
}
private void SetValue(string keyword, int value)
{
base[keyword] = value.ToString((System.IFormatProvider?)null);
}
private void SetValue(string keyword, string value)
{
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
public override bool TryGetValue(string keyword, [NotNullWhen(true)] out object? value)
{
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
value = GetAt(index);
return true;
}
else if (!base.TryGetValue(keyword, out value))
{
Dictionary<string, OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
OleDbPropertyInfo? info;
if (dynamic.TryGetValue(keyword, out info))
{
value = info._defaultValue!;
return true;
}
return false;
}
return true;
}
private Dictionary<string, OleDbPropertyInfo> GetProviderInfo(string provider)
{
Dictionary<string, OleDbPropertyInfo>? providerInfo = _propertyInfo;
if (null == providerInfo)
{
providerInfo = new Dictionary<string, OleDbPropertyInfo>(StringComparer.OrdinalIgnoreCase);
if (!ADP.IsEmpty(provider))
{
Dictionary<string, OleDbPropertyInfo>? hash = null;
try
{
StringBuilder builder = new StringBuilder();
AppendKeyValuePair(builder, DbConnectionStringKeywords.Provider, provider);
OleDbConnectionString constr = new OleDbConnectionString(builder.ToString(), true);
// load provider without calling Initialize or CreateDataSource
using (OleDbConnectionInternal connection = new OleDbConnectionInternal(constr, null))
{
// get all the init property information for the provider
hash = connection.GetPropertyInfo(new Guid[] { OleDbPropertySetGuid.DBInitAll })!;
foreach (KeyValuePair<string, OleDbPropertyInfo> entry in hash)
{
Keywords index;
OleDbPropertyInfo info = entry.Value;
if (!s_keywords.TryGetValue(info._description!, out index))
{
if ((OleDbPropertySetGuid.DBInit == info._propertySet) &&
((ODB.DBPROP_INIT_ASYNCH == info._propertyID) ||
(ODB.DBPROP_INIT_HWND == info._propertyID) ||
(ODB.DBPROP_INIT_PROMPT == info._propertyID)))
{
continue; // skip this keyword
}
providerInfo[info._description!] = info;
}
}
// what are the unique propertysets?
List<Guid> listPropertySets = new List<Guid>();
foreach (KeyValuePair<string, OleDbPropertyInfo> entry in hash)
{
OleDbPropertyInfo info = entry.Value;
if (!listPropertySets.Contains(info._propertySet))
{
listPropertySets.Add(info._propertySet);
}
}
Guid[] arrayPropertySets = new Guid[listPropertySets.Count];
listPropertySets.CopyTo(arrayPropertySets, 0);
// get all the init property values for the provider
using (PropertyIDSet propidset = new PropertyIDSet(arrayPropertySets))
{
using (IDBPropertiesWrapper idbProperties = connection.IDBProperties())
{
OleDbHResult hr;
using (DBPropSet propset = new DBPropSet(idbProperties.Value, propidset, out hr))
{
// OleDbConnectionStringBuilder is ignoring/hiding potential errors of OLEDB provider when reading its properties information
if (0 <= (int)hr)
{
int count = propset.PropertySetCount;
for (int i = 0; i < count; ++i)
{
Guid propertyset;
ItagDBPROP[] props = propset.GetPropertySet(i, out propertyset);
// attach the default property value to the property info
foreach (ItagDBPROP prop in props)
{
foreach (KeyValuePair<string, OleDbPropertyInfo> entry in hash)
{
OleDbPropertyInfo info = entry.Value;
if ((info._propertyID == prop.dwPropertyID) && (info._propertySet == propertyset))
{
info._defaultValue = prop.vValue;
if (null == info._defaultValue)
{
if (typeof(string) == info._type)
{
info._defaultValue = "";
}
else if (typeof(int) == info._type)
{
info._defaultValue = 0;
}
else if (typeof(bool) == info._type)
{
info._defaultValue = false;
}
}
}
}
}
}
}
}
}
}
}
}
catch (System.InvalidOperationException e)
{
ADP.TraceExceptionWithoutRethrow(e);
}
catch (System.Data.OleDb.OleDbException e)
{
ADP.TraceExceptionWithoutRethrow(e);
}
catch (System.Security.SecurityException e)
{
ADP.TraceExceptionWithoutRethrow(e);
}
}
_propertyInfo = providerInfo;
}
return providerInfo;
}
private sealed class OleDbProviderConverter : StringConverter
{
private const int DBSOURCETYPE_DATASOURCE_TDP = 1;
private const int DBSOURCETYPE_DATASOURCE_MDP = 3;
private StandardValuesCollection? _standardValues;
// converter classes should have public ctor
public OleDbProviderConverter()
{
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context)
{
return false;
}
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
StandardValuesCollection? dataSourceNames = _standardValues;
if (null == _standardValues)
{
// Get the sources rowset for the SQLOLEDB enumerator
DataTable table = (new OleDbEnumerator()).GetElements();
DataColumn column2 = table.Columns["SOURCES_NAME"]!;
DataColumn column5 = table.Columns["SOURCES_TYPE"]!;
//DataColumn column4 = table.Columns["SOURCES_DESCRIPTION"];
System.Collections.Generic.List<string> providerNames = new System.Collections.Generic.List<string>(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
int sourceType = (int)row[column5];
if (DBSOURCETYPE_DATASOURCE_TDP == sourceType || DBSOURCETYPE_DATASOURCE_MDP == sourceType)
{
string progid = (string)row[column2];
if (!OleDbConnectionString.IsMSDASQL(progid.ToLowerInvariant()))
{
if (0 > providerNames.IndexOf(progid))
{
providerNames.Add(progid);
}
}
}
}
// Create the standard values collection that contains the sources
dataSourceNames = new StandardValuesCollection(providerNames);
_standardValues = dataSourceNames;
}
return dataSourceNames;
}
}
[Flags]
internal enum OleDbServiceValues : int
{
DisableAll = unchecked((int)0x00000000),
ResourcePooling = unchecked((int)0x00000001),
TransactionEnlistment = unchecked((int)0x00000002),
ClientCursor = unchecked((int)0x00000004),
AggregationAfterSession = unchecked((int)0x00000008),
EnableAll = unchecked((int)0xffffffff),
Default = ~(ClientCursor | AggregationAfterSession),
};
internal sealed class OleDbServicesConverter : TypeConverter
{
private StandardValuesCollection? _standardValues;
// converter classes should have public ctor
public OleDbServicesConverter() : base()
{
}
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
// Only know how to convert from a string
return ((typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType));
}
public override object? ConvertFrom(ITypeDescriptorContext? context, System.Globalization.CultureInfo? culture, object value)
{
string? svalue = (value as string);
if (null != svalue)
{
int services;
if (int.TryParse(svalue, out services))
{
return services;
}
else
{
if (svalue.IndexOf(',') != -1)
{
int convertedValue = 0;
string[] values = svalue.Split(OleDbConnectionInternal.s_comma);
foreach (string v in values)
{
convertedValue |= (int)Enum.Parse<OleDbServiceValues>(v, true);
}
return convertedValue;
}
else
{
return (int)Enum.Parse<OleDbServiceValues>(svalue, true);
}
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType)
{
// Only know how to convert to the NetworkLibrary enumeration
return ((typeof(string) == destinationType) || base.CanConvertTo(context, destinationType));
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if ((typeof(string) == destinationType) && (null != value) && (typeof(int) == value.GetType()))
{
return ((OleDbServiceValues)(int)(value)).ToString("G");
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context)
{
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context)
{
StandardValuesCollection? standardValues = _standardValues;
if (null == standardValues)
{
OleDbServiceValues[] objValues = Enum.GetValues<OleDbServiceValues>();
Array.Sort(objValues, 0, objValues.Length);
standardValues = new StandardValuesCollection(objValues);
_standardValues = standardValues;
}
return standardValues;
}
public override bool IsValid(ITypeDescriptorContext? context, object? value)
{
return true;
//return Enum.IsDefined(type, value);
}
}
internal sealed class OleDbConnectionStringBuilderConverter : ExpandableObjectConverter
{
// converter classes should have public ctor
public OleDbConnectionStringBuilderConverter()
{
}
public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType)
{
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType)
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (destinationType == null)
{
throw ADP.ArgumentNull("destinationType");
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType)
{
OleDbConnectionStringBuilder? obj = (value as OleDbConnectionStringBuilder);
if (null != obj)
{
return ConvertToInstanceDescriptor(obj);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
private static System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbConnectionStringBuilder options)
{
Type[] ctorParams = new Type[] { typeof(string) };
object[] ctorValues = new object[] { options.ConnectionString };
System.Reflection.ConstructorInfo ctor = typeof(OleDbConnectionStringBuilder).GetConstructor(ctorParams)!;
return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues);
}
}
}
}