File: OleDbConnectionInternal.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (768 lines) | stat: -rw-r--r-- 34,647 bytes parent folder | download | duplicates (6)
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
//------------------------------------------------------------------------------
// <copyright file="OleDbConnectionInternal.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------

namespace System.Data.OleDb {

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.ProviderBase;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading;
    using SysES = System.EnterpriseServices;
    using SysTx = System.Transactions;

    sealed internal class OleDbConnectionInternal : DbConnectionInternal, IDisposable {

        static private volatile OleDbServicesWrapper idataInitialize;
        static private object dataInitializeLock = new object();

        internal readonly OleDbConnectionString ConnectionString; // parsed connection string attributes

        // A SafeHandle is used instead of a RCW because we need to fake the CLR into not marshalling

        // OLE DB Services is marked apartment thread, but it actually supports/requires free-threading.
        // However the CLR doesn't know this and attempts to marshal the interfaces back to their original context.
        // But the OLE DB doesn't marshal very well if at all.  Our workaround is based on the fact
        // OLE DB is free-threaded and allows the workaround.

        // Creating DataSource/Session would requiring marshalling DataLins to its original context
        // and has a severe performance impact (when working with transactions), hence our workaround to not Marshal.

        // Creating a Command would requiring marshalling Session to its original context and
        // actually doesn't work correctly, without our workaround you must execute the command in
        // the same context of the connection open.  This doesn't work for pooled objects that contain
        // an open OleDbConnection.

        // We don't do extra work at this time to allow the DataReader to be used in a different context
        // from which the command was executed in.  See WebData 64320, IRowset.GetNextRows will throw InvalidCastException

        // In V1.0, we worked around the performance impact of creating a DataSource/Session using
        // WrapIUnknownWithComObject which creates a new RCW without searching for existing RCW
        // effectively faking out the CLR into thinking the call is in the correct context.
        // We also would use Marshal.ReleaseComObject to force the release of the 'temporary' RCW.

        // In V1.1, we worked around the CreateCommand issue with the same WrapIUnknownWithComObject trick.

        // In V2.0, the performance of using WrapIUnknownWithComObject & ReleaseComObject severly degraded.
        // Using a SafeHandle (for lifetime control) and a delegate to call the apporiate COM method
        // offered much better performance.

        // the "Data Source object".
        private readonly DataSourceWrapper _datasrcwrp;

        // the "Session object".
        private readonly SessionWrapper _sessionwrp;

        private WeakReference weakTransaction;

        // When set to true the current connection is enlisted in a transaction that must be
        // un-enlisted during Deactivate.
        private bool _unEnlistDuringDeactivate;

        internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection connection) : base () {
#if DEBUG
            try { // use this to help validate this object is only created after the following permission has been previously demanded in the current codepath
                if (null != connection) {
                    connection.UserConnectionOptions.DemandPermission();
                }
                else {
                    constr.DemandPermission();
                }
            }
            catch(System.Security.SecurityException) {
                System.Diagnostics.Debug.Assert(false, "unexpected SecurityException for current codepath");
                throw;
            }
#endif
            Debug.Assert((null != constr) && !constr.IsEmpty, "empty connectionstring");
            ConnectionString = constr;

            if (constr.PossiblePrompt && !System.Environment.UserInteractive) {
                throw ODB.PossiblePromptNotUserInteractive();
            }

            try {
                // this is the native DataLinks object which pools the native datasource/session
                OleDbServicesWrapper wrapper = OleDbConnectionInternal.GetObjectPool();
                _datasrcwrp = new DataSourceWrapper();

                // DataLinks wrapper will call IDataInitialize::GetDataSource to create the DataSource
                // uses constr.ActualConnectionString, no InfoMessageEvent checking
                wrapper.GetDataSource(constr, ref _datasrcwrp);
                Debug.Assert(!_datasrcwrp.IsInvalid, "bad DataSource");

                // initialization is delayed because of OleDbConnectionStringBuilder only wants
                // pre-Initialize IDBPropertyInfo & IDBProperties on the data source
                if (null != connection) {
                    _sessionwrp = new SessionWrapper();

                    // From the DataSource object, will call IDBInitialize.Initialize & IDBCreateSession.CreateSession
                    // We always need both called so we use a single call for a single DangerousAddRef/DangerousRelease pair.
                    OleDbHResult hr = _datasrcwrp.InitializeAndCreateSession(constr, ref _sessionwrp);

                    // process the HResult here instead of from the SafeHandle because the possibility
                    // of an InfoMessageEvent.
                    if ((0 <= hr) && !_sessionwrp.IsInvalid) { // process infonessage events
                        OleDbConnection.ProcessResults(hr, connection, connection);
                    }
                    else {
                        Exception e = OleDbConnection.ProcessResults(hr, null, null);
                        Debug.Assert(null != e, "CreateSessionError");
                        throw e;
                    }
                    Debug.Assert(!_sessionwrp.IsInvalid, "bad Session");
                }
            }
            catch {
                if (null != _sessionwrp) {
                    _sessionwrp.Dispose();
                    _sessionwrp = null;
                }
                if (null != _datasrcwrp) {
                    _datasrcwrp.Dispose();
                    _datasrcwrp = null;
                }
                throw;
            }
        }

        internal OleDbConnection Connection {
            get {
                return (OleDbConnection)Owner;
            }
        }

        internal bool HasSession {
            get {
                return (null != _sessionwrp);
            }
        }

        internal OleDbTransaction LocalTransaction {
            get {
                OleDbTransaction result = null;
                if (null != weakTransaction) {
                    result = ((OleDbTransaction)weakTransaction.Target);
                }
                return result;
            }
            set {
                weakTransaction = null;

                if (null != value) {
                    weakTransaction = new WeakReference((OleDbTransaction)value);
                }
            }
        }

        private string Provider {
            get { return ConnectionString.Provider; }
        }

        override public string ServerVersion { // MDAC 55481
            // consider making a method, not a property
            get {
                object value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSVER);
                return Convert.ToString(value, CultureInfo.InvariantCulture);
            }
        }

        // grouping the native OLE DB casts togther by required interfaces and optional interfaces, connection then session
        // want these to be methods, not properties otherwise they appear in VS7 managed debugger which attempts to evaluate them

        // required interface, safe cast
        internal IDBPropertiesWrapper IDBProperties() {
            Debug.Assert(null != _datasrcwrp, "IDBProperties: null datasource");
            return _datasrcwrp.IDBProperties(this);
        }

        // required interface, safe cast
        internal IOpenRowsetWrapper IOpenRowset() {
            Debug.Assert(null != _datasrcwrp, "IOpenRowset: null datasource");
            Debug.Assert(null != _sessionwrp, "IOpenRowset: null session");
            return _sessionwrp.IOpenRowset(this);
        }

        // optional interface, unsafe cast
        private IDBInfoWrapper IDBInfo() {
            Debug.Assert(null != _datasrcwrp, "IDBInfo: null datasource");
            return _datasrcwrp.IDBInfo(this);
        }

        // optional interface, unsafe cast
        internal IDBSchemaRowsetWrapper IDBSchemaRowset() {
            Debug.Assert(null != _datasrcwrp, "IDBSchemaRowset: null datasource");
            Debug.Assert(null != _sessionwrp, "IDBSchemaRowset: null session");
            return _sessionwrp.IDBSchemaRowset(this);
        }

        // optional interface, unsafe cast
        internal ITransactionJoinWrapper ITransactionJoin() {
            Debug.Assert(null != _datasrcwrp, "ITransactionJoin: null datasource");
            Debug.Assert(null != _sessionwrp, "ITransactionJoin: null session");
            return _sessionwrp.ITransactionJoin(this);
        }

        // optional interface, unsafe cast
        internal UnsafeNativeMethods.ICommandText ICommandText() {
            Debug.Assert(null != _datasrcwrp, "IDBCreateCommand: null datasource");
            Debug.Assert(null != _sessionwrp, "IDBCreateCommand: null session");

            object icommandText = null;
            OleDbHResult hr = _sessionwrp.CreateCommand(ref icommandText);

            Debug.Assert((0 <= hr) || (null == icommandText), "CreateICommandText: error with ICommandText");
            if (hr < 0) {
                if (OleDbHResult.E_NOINTERFACE != hr) { // MDAC 57856
                    ProcessResults(hr);
                }
                else {
                    SafeNativeMethods.Wrapper.ClearErrorInfo();
                }
            }
            return (UnsafeNativeMethods.ICommandText)icommandText;
        }

        override protected void Activate(SysTx.Transaction transaction) {
            throw ADP.NotSupported();
        }

        override public DbTransaction BeginTransaction(IsolationLevel isolationLevel) {
            OleDbConnection.ExecutePermission.Demand();

            OleDbConnection outerConnection = Connection;
            if (null != LocalTransaction) {
                throw ADP.ParallelTransactionsNotSupported(outerConnection);
            }

            object unknown = null;
            OleDbTransaction transaction;
            try {
                transaction = new OleDbTransaction(outerConnection, null, isolationLevel);

                Bid.Trace("<oledb.IUnknown.QueryInterface|API|OLEDB|session> %d#, ITransactionLocal\n", ObjectID);
                Debug.Assert(null != _datasrcwrp, "ITransactionLocal: null datasource");
                Debug.Assert(null != _sessionwrp, "ITransactionLocal: null session");
                unknown = _sessionwrp.ComWrapper();
                UnsafeNativeMethods.ITransactionLocal value = (unknown as UnsafeNativeMethods.ITransactionLocal);
                if (null == value) {
                    throw ODB.TransactionsNotSupported(Provider, (Exception)null);
                }
                transaction.BeginInternal(value);
            }
            finally {
                if (null != unknown) {
                    Marshal.ReleaseComObject(unknown);
                }
            }
            LocalTransaction = transaction;
            return transaction;
        }

        override protected DbReferenceCollection CreateReferenceCollection() {
            return new OleDbReferenceCollection();
        }

        override protected void Deactivate() { // used by both managed and native pooling
            NotifyWeakReference(OleDbReferenceCollection.Closing);

            if (_unEnlistDuringDeactivate) {
                // Un-enlist transaction as OLEDB connection pool is unaware of managed transactions.
                EnlistTransactionInternal(null);
            }
            OleDbTransaction transaction = LocalTransaction;
            if (null != transaction) {
                LocalTransaction = null;
                // required to rollback any transactions on this connection
                // before releasing the back to the oledb connection pool
                transaction.Dispose();
            }
        }

        public override void Dispose() { // MDAC 65459
            Debug.Assert(null == LocalTransaction, "why was Deactivate not called first");
            if (null != _sessionwrp) {
                _sessionwrp.Dispose();
            }
            if (null != _datasrcwrp) {
                _datasrcwrp.Dispose();
            }
            base.Dispose();
        }

        override public void EnlistTransaction(SysTx.Transaction transaction) { // MDAC 78997
            OleDbConnection.VerifyExecutePermission();

            OleDbConnection outerConnection = Connection;
            if (null != LocalTransaction) {
                throw ADP.LocalTransactionPresent();
            }
            EnlistTransactionInternal(transaction);
        }

        internal void EnlistTransactionInternal(SysTx.Transaction transaction) {
            OleDbConnection.VerifyExecutePermission();

            SysTx.IDtcTransaction oleTxTransaction = ADP.GetOletxTransaction(transaction);

            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<oledb.ITransactionJoin.JoinTransaction|API|OLEDB> %d#\n", ObjectID);
            try {
                using(ITransactionJoinWrapper transactionJoin = ITransactionJoin()) {
                    if (null == transactionJoin.Value) {
                        throw ODB.TransactionsNotSupported(Provider, (Exception)null);
                    }
                    transactionJoin.Value.JoinTransaction(oleTxTransaction, (int) IsolationLevel.Unspecified, 0, IntPtr.Zero);
                    _unEnlistDuringDeactivate = (null != transaction);
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
            EnlistedTransaction = transaction;
        }

        internal object GetDataSourceValue(Guid propertySet, int propertyID) {
            object value = GetDataSourcePropertyValue(propertySet, propertyID);
            if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) {
                value = null;
            }
            return value;
        }

        internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID) {
            OleDbHResult hr;
            tagDBPROP[] dbprops;
            using(IDBPropertiesWrapper idbProperties = IDBProperties()) {
                using(PropertyIDSet propidset = new PropertyIDSet(propertySet, propertyID)) {

                    using(DBPropSet propset = new DBPropSet(idbProperties.Value, propidset, out hr)) {
                        if (hr < 0) {
                            // VSDD 621427: OLEDB Data Reader masks provider specific errors by raising "Internal .Net Framework Data Provider error 30."
                            // DBPropSet c-tor will register the exception and it will be raised at GetPropertySet call in case of failure
                            SafeNativeMethods.Wrapper.ClearErrorInfo();
                        }
                        dbprops = propset.GetPropertySet(0, out propertySet);
                    }
                }
            }
            if (OleDbPropertyStatus.Ok == dbprops[0].dwStatus) {
                return dbprops[0].vValue;
            }
            return dbprops[0].dwStatus;
        }

        internal DataTable BuildInfoLiterals() {
            using(IDBInfoWrapper wrapper = IDBInfo()) {
                UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value;
                if (null == dbInfo) {
                    return null;
                }

                DataTable table = new DataTable("DbInfoLiterals");
                table.Locale = CultureInfo.InvariantCulture;
                DataColumn literalName  = new DataColumn("LiteralName", typeof(String));
                DataColumn literalValue = new DataColumn("LiteralValue", typeof(String));
                DataColumn invalidChars = new DataColumn("InvalidChars", typeof(String));
                DataColumn invalidStart = new DataColumn("InvalidStartingChars", typeof(String));
                DataColumn literal      = new DataColumn("Literal", typeof(Int32));
                DataColumn maxlen       = new DataColumn("Maxlen", typeof(Int32));

                table.Columns.Add(literalName);
                table.Columns.Add(literalValue);
                table.Columns.Add(invalidChars);
                table.Columns.Add(invalidStart);
                table.Columns.Add(literal);
                table.Columns.Add(maxlen);

                OleDbHResult hr;
                int literalCount = 0;
                IntPtr literalInfo = ADP.PtrZero;
                using(DualCoTaskMem handle = new DualCoTaskMem(dbInfo, null, out literalCount, out literalInfo, out hr)) {
                    // All literals were either invalid or unsupported. The provider allocates memory for *prgLiteralInfo and sets the value of the fSupported element in all of the structures to FALSE. The consumer frees this memory when it no longer needs the information.
                    if (OleDbHResult.DB_E_ERRORSOCCURRED != hr) {
                        long offset = literalInfo.ToInt64();
                        tagDBLITERALINFO tag = new tagDBLITERALINFO();
                        for (int i = 0; i < literalCount; ++i, offset += ODB.SizeOf_tagDBLITERALINFO) {
                            Marshal.PtrToStructure((IntPtr)offset, tag);

                            DataRow row = table.NewRow();
                            row[literalName ] = ((OleDbLiteral) tag.it).ToString();
                            row[literalValue] = tag.pwszLiteralValue;
                            row[invalidChars] = tag.pwszInvalidChars;
                            row[invalidStart] = tag.pwszInvalidStartingChars;
                            row[literal     ] = tag.it;
                            row[maxlen      ] = tag.cchMaxLen;

                            table.Rows.Add(row);
                            row.AcceptChanges();
                        }
                        if (hr < 0) { // ignore infomsg
                            ProcessResults(hr);
                        }
                    }
                    else {
                        SafeNativeMethods.Wrapper.ClearErrorInfo();
                    }
                }
                return table;
            }
        }


        internal DataTable BuildInfoKeywords() {

            DataTable table = new DataTable(ODB.DbInfoKeywords);
            table.Locale = CultureInfo.InvariantCulture;
            DataColumn keyword  = new DataColumn(ODB.Keyword, typeof(String));
            table.Columns.Add(keyword);

            if(!AddInfoKeywordsToTable(table,keyword)){
                table = null;
            }

            return table;
        }

        internal bool AddInfoKeywordsToTable(DataTable table, DataColumn keyword) {
            using(IDBInfoWrapper wrapper = IDBInfo()) {
                UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value;
                if (null == dbInfo) {
                    return false;
                }

                OleDbHResult hr;
                string keywords;

                Bid.Trace("<oledb.IDBInfo.GetKeywords|API|OLEDB> %d#\n", ObjectID);
                hr = dbInfo.GetKeywords(out keywords);
                Bid.Trace("<oledb.IDBInfo.GetKeywords|API|OLEDB|RET> %08X{HRESULT}\n", hr);

                if (hr < 0) { // ignore infomsg
                    ProcessResults(hr);
                }

                if (null != keywords) {
                    string[] values = keywords.Split(new char[1] { ',' });
                    for (int i = 0; i < values.Length; ++i) {
                        DataRow row = table.NewRow();
                        row[keyword] = values[i];

                        table.Rows.Add(row);
                        row.AcceptChanges();
                    }
                }
                return true;
            }
        }

        internal DataTable BuildSchemaGuids() {
            DataTable table = new DataTable(ODB.SchemaGuids);
            table.Locale = CultureInfo.InvariantCulture;

            DataColumn schemaGuid  = new DataColumn(ODB.Schema, typeof(Guid));
            DataColumn restrictionSupport = new DataColumn(ODB.RestrictionSupport, typeof(Int32));

            table.Columns.Add(schemaGuid);
            table.Columns.Add(restrictionSupport);

            SchemaSupport[] supportedSchemas = GetSchemaRowsetInformation();

            if (null != supportedSchemas) {
                object[] values = new object[2];
                table.BeginLoadData();
                for (int i = 0; i < supportedSchemas.Length; ++i) {
                    values[0] = supportedSchemas[i]._schemaRowset;
                    values[1] = supportedSchemas[i]._restrictions;
                    table.LoadDataRow(values, LoadOption.OverwriteChanges);
                }
                table.EndLoadData();
            }
            return table;
        }

        internal string GetLiteralInfo(int literal) {
            using(IDBInfoWrapper wrapper = IDBInfo()) {
                UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value;
                if (null == dbInfo) {
                    return null;
                }
                string literalValue = null;
                IntPtr literalInfo = ADP.PtrZero;
                int literalCount = 0;
                OleDbHResult hr;

                using(DualCoTaskMem handle = new DualCoTaskMem(dbInfo, new int[1] { literal }, out literalCount, out literalInfo, out hr)) {
                    // All literals were either invalid or unsupported. The provider allocates memory for *prgLiteralInfo and sets the value of the fSupported element in all of the structures to FALSE. The consumer frees this memory when it no longer needs the information.
                    if (OleDbHResult.DB_E_ERRORSOCCURRED != hr) {
                        if ((1 == literalCount) && Marshal.ReadInt32(literalInfo, ODB.OffsetOf_tagDBLITERALINFO_it) == literal) { // WebData 98612
                            literalValue = Marshal.PtrToStringUni(Marshal.ReadIntPtr(literalInfo, 0));
                        }
                        if (hr < 0) { // ignore infomsg
                            ProcessResults(hr);
                        }
                    }
                    else {
                        SafeNativeMethods.Wrapper.ClearErrorInfo();
                    }
                }
                return literalValue;
            }
        }

        internal SchemaSupport[] GetSchemaRowsetInformation() {
            OleDbConnectionString constr = ConnectionString;
            SchemaSupport[] supportedSchemas = constr.SchemaSupport;
            if (null != supportedSchemas) {
                return supportedSchemas;
            }
            using(IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) {
                UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value;
                if (null == dbSchemaRowset) {
                    return null; // IDBSchemaRowset not supported
                }

                OleDbHResult hr;
                int schemaCount = 0;
                IntPtr schemaGuids = ADP.PtrZero;
                IntPtr schemaRestrictions = ADP.PtrZero;

                using(DualCoTaskMem safehandle = new DualCoTaskMem(dbSchemaRowset, out schemaCount, out schemaGuids, out schemaRestrictions, out hr)) {
                    dbSchemaRowset = null;
                    if (hr < 0) { // ignore infomsg
                        ProcessResults(hr);
                    }

                    supportedSchemas = new SchemaSupport[schemaCount];
                    if (ADP.PtrZero != schemaGuids) {
                        for (int i = 0, offset = 0; i < supportedSchemas.Length; ++i, offset += ODB.SizeOf_Guid) {
                            IntPtr ptr = ADP.IntPtrOffset(schemaGuids, i * ODB.SizeOf_Guid);
                            supportedSchemas[i]._schemaRowset =  (Guid) Marshal.PtrToStructure(ptr, typeof(Guid));
                        }
                    }
                    if (ADP.PtrZero != schemaRestrictions) {
                        for (int i = 0; i < supportedSchemas.Length; ++i) {
                            supportedSchemas[i]._restrictions = Marshal.ReadInt32(schemaRestrictions, i * 4);
                        }
                    }
                }
                constr.SchemaSupport = supportedSchemas;
                return supportedSchemas;
            }
        }

        internal DataTable GetSchemaRowset(Guid schema, object[] restrictions) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<oledb.OleDbConnectionInternal.GetSchemaRowset|INFO> %d#, schema=%ls, restrictions\n", ObjectID, schema);
            try {
                if (null == restrictions) { // MDAC 62243
                    restrictions = new object[0];
                }
                DataTable dataTable = null;
                using(IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) {
                    UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value;
                    if (null == dbSchemaRowset) {
                        throw ODB.SchemaRowsetsNotSupported(Provider);
                    }

                    UnsafeNativeMethods.IRowset rowset = null;
                    OleDbHResult hr;

                    Bid.Trace("<oledb.IDBSchemaRowset.GetRowset|API|OLEDB> %d#\n", ObjectID);
                    hr = dbSchemaRowset.GetRowset(ADP.PtrZero, ref schema, restrictions.Length, restrictions, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset);
                    Bid.Trace("<oledb.IDBSchemaRowset.GetRowset|API|OLEDB|RET> %08X{HRESULT}\n", hr);

                    if (hr < 0) { // ignore infomsg
                        ProcessResults(hr);
                    }

                    if (null != rowset) {
                        using(OleDbDataReader dataReader = new OleDbDataReader(Connection, null, 0, CommandBehavior.Default)) {
                            dataReader.InitializeIRowset(rowset, ChapterHandle.DB_NULL_HCHAPTER, IntPtr.Zero);
                            dataReader.BuildMetaInfo();
                            dataReader.HasRowsRead();

                            dataTable = new DataTable();
                            dataTable.Locale = CultureInfo.InvariantCulture;
                            dataTable.TableName = OleDbSchemaGuid.GetTextFromValue(schema);
                            OleDbDataAdapter.FillDataTable(dataReader, dataTable);
                        }
                    }
                    return dataTable;
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        // returns true if there is an active data reader on the specified command
        internal bool HasLiveReader(OleDbCommand cmd)  {
            OleDbDataReader reader = null;

            if (null != ReferenceCollection) {
                reader = ReferenceCollection.FindItem<OleDbDataReader>(OleDbReferenceCollection.DataReaderTag, (dataReader) => cmd == dataReader.Command);
            }

            return (reader != null);
        }

        private void ProcessResults(OleDbHResult hr) {
            OleDbConnection connection = Connection; // get value from weakref only once
            Exception e = OleDbConnection.ProcessResults(hr, connection, connection);
            if (null != e) { throw e; }
        }

        internal bool SupportSchemaRowset(Guid schema) {
            SchemaSupport[] schemaSupport = GetSchemaRowsetInformation();
            if (null != schemaSupport) { // MDAC 68385
                for (int i = 0; i < schemaSupport.Length; ++i) {
                    if (schema == schemaSupport[i]._schemaRowset) {
                        return true;
                    }
                }
            }
            return false;
        }

        [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
        static private object CreateInstanceDataLinks() {
            Type datalink = Type.GetTypeFromCLSID(ODB.CLSID_DataLinks, true);
            return Activator.CreateInstance(datalink, System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null);
        }


        // @devnote: should be multithread safe access to OleDbConnection.idataInitialize,
        // though last one wins for setting variable.  It may be different objects, but
        // OLE DB will ensure I'll work with just the single pool
        static private OleDbServicesWrapper GetObjectPool() {
            OleDbServicesWrapper wrapper = OleDbConnectionInternal.idataInitialize;
            if (null == wrapper) {
                lock(dataInitializeLock) {
                    wrapper = OleDbConnectionInternal.idataInitialize;
                    if (null == wrapper) {
                        VersionCheck();

                        object datalinks;
                        try {
                            datalinks = CreateInstanceDataLinks();
                        }
                        catch (Exception e) {
                            // 
                            if (!ADP.IsCatchableExceptionType(e)) {
                                throw;
                            }

                            throw ODB.MDACNotAvailable(e);
                        }
                        if (null == datalinks) {
                            throw ODB.MDACNotAvailable(null);
                        }
                        wrapper = new OleDbServicesWrapper(datalinks);
                        OleDbConnectionInternal.idataInitialize = wrapper;
                    }
                }
            }
            Debug.Assert(null != wrapper, "GetObjectPool: null dataInitialize");
            return wrapper;
        }

        static private void VersionCheck() {
            // $

            if (ApartmentState.Unknown == Thread.CurrentThread.GetApartmentState()) {
                SetMTAApartmentState();
            }

            ADP.CheckVersionMDAC(false);
        }

        [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
        static private void SetMTAApartmentState() {
            // we are defaulting to a multithread apartment state
            Thread.CurrentThread.SetApartmentState(ApartmentState.MTA);
        }

        // @devnote: should be multithread safe
        static public void ReleaseObjectPool() {
            OleDbConnectionInternal.idataInitialize = null;
        }

        internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method) {
            if (null != this.weakTransaction) {

                OleDbTransaction head = (OleDbTransaction) this.weakTransaction.Target;
                if ((null != head) && this.weakTransaction.IsAlive) {
                    head = OleDbTransaction.TransactionUpdate(head);

                    // either we are wrong or finalize was called and object still alive
                    Debug.Assert(null != head, "unexcpted Transaction state");
                }
                // else transaction has finalized on user

                if (null != head) {
                    if (null == transaction) {
                        // valid transaction exists and cmd doesn't have it
                        throw ADP.TransactionRequired(method);
                    }
                    else {
                        OleDbTransaction tail = OleDbTransaction.TransactionLast(head);
                        if (tail != transaction) {
                            if (tail.Connection != transaction.Connection) {
                                throw ADP.TransactionConnectionMismatch();
                            }
                            // else cmd has incorrect transaction
                            throw ADP.TransactionCompleted();
                        }
                        // else cmd has correct transaction
                        return transaction;
                    }
                }
                else { // cleanup for Finalized transaction
                    this.weakTransaction = null;
                }
            }
            else if ((null != transaction) && (null != transaction.Connection)) { // MDAC 72706
                throw ADP.TransactionConnectionMismatch();
            }
            // else no transaction and cmd is correct

            // MDAC 61649
            // if transactionObject is from this connection but zombied
            // and no transactions currently exists - then ignore the bogus object
            return null;
        }

        internal Dictionary<string,OleDbPropertyInfo> GetPropertyInfo(Guid[] propertySets) {
            bool isopen = HasSession;
            OleDbConnectionString constr = ConnectionString;
            Dictionary<string,OleDbPropertyInfo> properties = null;

            if (null == propertySets) {
                propertySets = new Guid[0];
            }
            using(PropertyIDSet propidset = new PropertyIDSet(propertySets)) {
                using(IDBPropertiesWrapper idbProperties = IDBProperties()) {
                    using(PropertyInfoSet infoset = new PropertyInfoSet(idbProperties.Value, propidset)) {
                        properties = infoset.GetValues();
                    }
                }
            }
            return properties;
        }
    }
}