1 //------------------------------------------------------------------------------
2 // <copyright file="SqlConnectionFactory.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">[....]</owner>
6 // <owner current="true" primary="false">[....]</owner>
7 //------------------------------------------------------------------------------
9 namespace System.Data.SqlClient
12 using System.Data.Common;
13 using System.Data.ProviderBase;
14 using System.Collections.Specialized;
15 using System.Configuration;
16 using System.Diagnostics;
18 using System.Runtime.Versioning;
20 using Microsoft.SqlServer.Server;
23 sealed internal class SqlConnectionFactory : DbConnectionFactory {
24 private SqlConnectionFactory() : base(SqlPerformanceCounters.SingletonInstance) {}
26 public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory();
27 private const string _metaDataXml = "MetaDataXml";
29 override public DbProviderFactory ProviderFactory {
31 return SqlClientFactory.Instance;
35 override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) {
36 return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null);
39 override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) {
40 SqlConnectionString opt = (SqlConnectionString)options;
41 SqlConnectionPoolKey key = (SqlConnectionPoolKey) poolKey;
42 SqlInternalConnection result = null;
43 SessionData recoverySessionData = null;
45 SqlConnectionString userOpt = null;
46 if (userOptions != null) {
47 userOpt = (SqlConnectionString)userOptions;
49 else if (owningConnection != null) {
50 userOpt = (SqlConnectionString)(((SqlConnection)owningConnection).UserConnectionOptions);
53 if (owningConnection != null) {
54 recoverySessionData = ((SqlConnection)owningConnection)._recoverySessionData;
57 if (opt.ContextConnection) {
58 result = GetContextConnection(opt, poolGroupProviderInfo);
61 bool redirectedUserInstance = false;
62 DbConnectionPoolIdentity identity = null;
64 // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
65 // Used by notifications.
66 if (opt.IntegratedSecurity) {
68 identity = pool.Identity;
71 identity = DbConnectionPoolIdentity.GetCurrent();
75 // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
76 // If "user instance=true" is in the connection string, we're using SSE user instances
77 if (opt.UserInstance) {
78 // opt.DataSource is used to create the SSE connection
79 redirectedUserInstance = true;
82 if ( (null == pool) ||
83 (null != pool && pool.Count <= 0) ) { // Non-pooled or pooled and no connections in the pool.
85 SqlInternalConnectionTds sseConnection = null;
87 // What about a failure - throw? YES!
92 SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */, false /* set Enlist = false */);
93 sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false);
94 // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
95 instanceName = sseConnection.InstanceName;
97 if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal)) {
98 throw SQL.NonLocalSSEInstance();
101 if (null != pool) { // Pooled connection - cache result
102 SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo;
103 // No lock since we are already in creation mutex
104 providerInfo.InstanceName = instanceName;
108 if (null != sseConnection) {
109 sseConnection.Dispose();
113 else { // Cached info from pool.
114 SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo;
115 // No lock since we are already in creation mutex
116 instanceName = providerInfo.InstanceName;
119 // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
120 // retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
121 // options immutable - stored in global hash - don't modify
122 opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */, null /* do not modify the Enlist value */);
123 poolGroupProviderInfo = null; // null so we do not pass to constructor below...
125 result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData);
130 protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) {
131 Debug.Assert(!ADP.IsEmpty(connectionString), "empty connectionString");
132 SqlConnectionString result = new SqlConnectionString(connectionString);
136 override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions){
137 DbConnectionPoolProviderInfo providerInfo = null;
139 if (((SqlConnectionString) connectionOptions).UserInstance) {
140 providerInfo = new SqlConnectionPoolProviderInfo();
146 override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions( DbConnectionOptions connectionOptions ) {
147 SqlConnectionString opt = (SqlConnectionString)connectionOptions;
149 DbConnectionPoolGroupOptions poolingOptions = null;
151 if (!opt.ContextConnection && opt.Pooling) { // never pool context connections.
152 int connectionTimeout = opt.ConnectTimeout;
154 if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue/1000))
155 connectionTimeout *= 1000;
156 else if (connectionTimeout >= Int32.MaxValue/1000)
157 connectionTimeout = Int32.MaxValue;
159 poolingOptions = new DbConnectionPoolGroupOptions(
160 opt.IntegratedSecurity,
164 opt.LoadBalanceTimeout,
167 return poolingOptions;
170 // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
171 // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
172 // under the runtime folder.
173 [ResourceExposure(ResourceScope.None)]
174 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
175 override protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory){
176 Debug.Assert (internalConnection != null, "internalConnection may not be null.");
177 cacheMetaDataFactory = false;
179 if (internalConnection is SqlInternalConnectionSmi) {
180 throw SQL.NotAvailableOnContextConnection();
183 Stream XMLStream =null;
184 #if !NO_CONFIGURATION
185 NameValueCollection settings = (NameValueCollection)PrivilegedConfigurationManager.GetSection("system.data.sqlclient");
186 if (settings != null){
187 string [] values = settings.GetValues(_metaDataXml);
188 if (values != null) {
189 XMLStream = ADP.GetXmlStreamFromValues(values, _metaDataXml);
194 // if the xml was not obtained from machine.config use the embedded XML resource
195 if (XMLStream == null){
196 XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.SqlClient.SqlMetaData.xml");
197 cacheMetaDataFactory = true;
199 Debug.Assert (XMLStream != null,"XMLstream may not be null.");
201 return new SqlMetaDataFactory (XMLStream,
202 internalConnection.ServerVersion,
203 internalConnection.ServerVersion); //internalConnection.ServerVersionNormalized);
207 override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo (DbConnectionOptions connectionOptions) {
208 return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions);
212 internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) {
213 SqlConnectionString connectionOptions = (SqlConnectionString )SingletonInstance.FindConnectionOptions(key);
214 if (null == connectionOptions) {
215 connectionOptions = new SqlConnectionString(key.ConnectionString);
217 if (connectionOptions.IsEmpty) {
218 throw ADP.NoConnectionString();
220 return connectionOptions;
223 private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString options, object providerInfo) {
224 SmiContext smiContext = SmiContextFactory.Instance.GetCurrentContext();
226 SqlInternalConnectionSmi result = (SqlInternalConnectionSmi)smiContext.GetContextValue((int)SmiContextFactory.ContextKey.Connection);
228 // context connections are automatically re-useable if they exist unless they've been doomed.
229 if (null == result || result.IsConnectionDoomed) {
230 if (null != result) {
231 result.Dispose(); // A doomed connection is a messy thing. Dispose of it promptly in nearest receptacle.
234 result = new SqlInternalConnectionSmi(options, smiContext);
235 smiContext.SetContextValue((int)SmiContextFactory.ContextKey.Connection, result);
243 override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) {
244 SqlConnection c = (connection as SqlConnection);
251 override internal DbConnectionInternal GetInnerConnection(DbConnection connection) {
252 SqlConnection c = (connection as SqlConnection);
254 return c.InnerConnection;
259 override protected int GetObjectId(DbConnection connection) {
260 SqlConnection c = (connection as SqlConnection);
267 override internal void PermissionDemand(DbConnection outerConnection) {
268 SqlConnection c = (outerConnection as SqlConnection);
270 c.PermissionDemand();
274 override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) {
275 SqlConnection c = (outerConnection as SqlConnection);
277 c.PoolGroup = poolGroup;
281 override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) {
282 SqlConnection c = (owningObject as SqlConnection);
284 c.SetInnerConnectionEvent(to);
288 override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) {
289 SqlConnection c = (owningObject as SqlConnection);
291 return c.SetInnerConnectionFrom(to, from);
296 override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) {
297 SqlConnection c = (owningObject as SqlConnection);
299 c.SetInnerConnectionTo(to);
305 sealed internal class SqlPerformanceCounters : DbConnectionPoolCounters {
306 private const string CategoryName = ".NET Data Provider for SqlServer";
307 private const string CategoryHelp = "Counters for System.Data.SqlClient";
309 public static readonly SqlPerformanceCounters SingletonInstance = new SqlPerformanceCounters();
312 [System.Diagnostics.PerformanceCounterPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, PermissionAccess=PerformanceCounterPermissionAccess.Write, MachineName=".", CategoryName=CategoryName)]
313 private SqlPerformanceCounters() : base (CategoryName, CategoryHelp) {