SqlConnectionFactory.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlConnectionFactory.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient
  9. {
  10. using System;
  11. using System.Data.Common;
  12. using System.Data.ProviderBase;
  13. using System.Collections.Specialized;
  14. using System.Configuration;
  15. using System.Diagnostics;
  16. using System.IO;
  17. using System.Runtime.Versioning;
  18. using Microsoft.SqlServer.Server;
  19. sealed internal class SqlConnectionFactory : DbConnectionFactory {
  20. private SqlConnectionFactory() : base(SqlPerformanceCounters.SingletonInstance) {}
  21. public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory();
  22. private const string _metaDataXml = "MetaDataXml";
  23. override public DbProviderFactory ProviderFactory {
  24. get {
  25. return SqlClientFactory.Instance;
  26. }
  27. }
  28. override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) {
  29. return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null);
  30. }
  31. override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) {
  32. SqlConnectionString opt = (SqlConnectionString)options;
  33. SqlConnectionPoolKey key = (SqlConnectionPoolKey) poolKey;
  34. SqlInternalConnection result = null;
  35. SessionData recoverySessionData = null;
  36. SqlConnection sqlOwningConnection = owningConnection as SqlConnection;
  37. bool applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false;
  38. SqlConnectionString userOpt = null;
  39. if (userOptions != null) {
  40. userOpt = (SqlConnectionString)userOptions;
  41. }
  42. else if (sqlOwningConnection != null) {
  43. userOpt = (SqlConnectionString)(sqlOwningConnection.UserConnectionOptions);
  44. }
  45. if (sqlOwningConnection != null) {
  46. recoverySessionData = sqlOwningConnection._recoverySessionData;
  47. }
  48. if (opt.ContextConnection) {
  49. result = GetContextConnection(opt, poolGroupProviderInfo);
  50. }
  51. else {
  52. bool redirectedUserInstance = false;
  53. DbConnectionPoolIdentity identity = null;
  54. // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
  55. // Used by notifications.
  56. if (opt.IntegratedSecurity || opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated) {
  57. if (pool != null) {
  58. identity = pool.Identity;
  59. }
  60. else {
  61. identity = DbConnectionPoolIdentity.GetCurrent();
  62. }
  63. }
  64. // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
  65. // If "user instance=true" is in the connection string, we're using SSE user instances
  66. if (opt.UserInstance) {
  67. // opt.DataSource is used to create the SSE connection
  68. redirectedUserInstance = true;
  69. string instanceName;
  70. if ( (null == pool) ||
  71. (null != pool && pool.Count <= 0) ) { // Non-pooled or pooled and no connections in the pool.
  72. SqlInternalConnectionTds sseConnection = null;
  73. try {
  74. // What about a failure - throw? YES!
  75. //
  76. SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */, false /* set Enlist = false */);
  77. sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false, applyTransientFaultHandling: applyTransientFaultHandling);
  78. // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
  79. instanceName = sseConnection.InstanceName;
  80. if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal)) {
  81. throw SQL.NonLocalSSEInstance();
  82. }
  83. if (null != pool) { // Pooled connection - cache result
  84. SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo;
  85. // No lock since we are already in creation mutex
  86. providerInfo.InstanceName = instanceName;
  87. }
  88. }
  89. finally {
  90. if (null != sseConnection) {
  91. sseConnection.Dispose();
  92. }
  93. }
  94. }
  95. else { // Cached info from pool.
  96. SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo;
  97. // No lock since we are already in creation mutex
  98. instanceName = providerInfo.InstanceName;
  99. }
  100. // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
  101. // retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
  102. // options immutable - stored in global hash - don't modify
  103. opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */, null /* do not modify the Enlist value */);
  104. poolGroupProviderInfo = null; // null so we do not pass to constructor below...
  105. }
  106. result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData, pool, key.AccessToken, applyTransientFaultHandling: applyTransientFaultHandling);
  107. }
  108. return result;
  109. }
  110. protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) {
  111. Debug.Assert(!ADP.IsEmpty(connectionString), "empty connectionString");
  112. SqlConnectionString result = new SqlConnectionString(connectionString);
  113. return result;
  114. }
  115. override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions){
  116. DbConnectionPoolProviderInfo providerInfo = null;
  117. if (((SqlConnectionString) connectionOptions).UserInstance) {
  118. providerInfo = new SqlConnectionPoolProviderInfo();
  119. }
  120. return providerInfo;
  121. }
  122. override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions( DbConnectionOptions connectionOptions ) {
  123. SqlConnectionString opt = (SqlConnectionString)connectionOptions;
  124. DbConnectionPoolGroupOptions poolingOptions = null;
  125. if (!opt.ContextConnection && opt.Pooling) { // never pool context connections.
  126. int connectionTimeout = opt.ConnectTimeout;
  127. if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue/1000))
  128. connectionTimeout *= 1000;
  129. else if (connectionTimeout >= Int32.MaxValue/1000)
  130. connectionTimeout = Int32.MaxValue;
  131. poolingOptions = new DbConnectionPoolGroupOptions(
  132. opt.IntegratedSecurity || opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated,
  133. opt.MinPoolSize,
  134. opt.MaxPoolSize,
  135. connectionTimeout,
  136. opt.LoadBalanceTimeout,
  137. opt.Enlist);
  138. }
  139. return poolingOptions;
  140. }
  141. // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
  142. // 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
  143. // under the runtime folder.
  144. [ResourceExposure(ResourceScope.None)]
  145. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  146. override protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory){
  147. Debug.Assert (internalConnection != null, "internalConnection may not be null.");
  148. cacheMetaDataFactory = false;
  149. if (internalConnection is SqlInternalConnectionSmi) {
  150. throw SQL.NotAvailableOnContextConnection();
  151. }
  152. Stream XMLStream =null;
  153. #if !NO_CONFIGURATION
  154. NameValueCollection settings = (NameValueCollection)PrivilegedConfigurationManager.GetSection("system.data.sqlclient");
  155. if (settings != null){
  156. string [] values = settings.GetValues(_metaDataXml);
  157. if (values != null) {
  158. XMLStream = ADP.GetXmlStreamFromValues(values, _metaDataXml);
  159. }
  160. }
  161. #endif
  162. // if the xml was not obtained from machine.config use the embedded XML resource
  163. if (XMLStream == null){
  164. XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.SqlClient.SqlMetaData.xml");
  165. cacheMetaDataFactory = true;
  166. }
  167. Debug.Assert (XMLStream != null,"XMLstream may not be null.");
  168. return new SqlMetaDataFactory (XMLStream,
  169. internalConnection.ServerVersion,
  170. internalConnection.ServerVersion); //internalConnection.ServerVersionNormalized);
  171. }
  172. override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo (DbConnectionOptions connectionOptions) {
  173. return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions);
  174. }
  175. internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) {
  176. SqlConnectionString connectionOptions = (SqlConnectionString )SingletonInstance.FindConnectionOptions(key);
  177. if (null == connectionOptions) {
  178. connectionOptions = new SqlConnectionString(key.ConnectionString);
  179. }
  180. if (connectionOptions.IsEmpty) {
  181. throw ADP.NoConnectionString();
  182. }
  183. return connectionOptions;
  184. }
  185. private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString options, object providerInfo) {
  186. SmiContext smiContext = SmiContextFactory.Instance.GetCurrentContext();
  187. SqlInternalConnectionSmi result = (SqlInternalConnectionSmi)smiContext.GetContextValue((int)SmiContextFactory.ContextKey.Connection);
  188. // context connections are automatically re-useable if they exist unless they've been doomed.
  189. if (null == result || result.IsConnectionDoomed) {
  190. if (null != result) {
  191. result.Dispose(); // A doomed connection is a messy thing. Dispose of it promptly in nearest receptacle.
  192. }
  193. result = new SqlInternalConnectionSmi(options, smiContext);
  194. smiContext.SetContextValue((int)SmiContextFactory.ContextKey.Connection, result);
  195. }
  196. result.Activate();
  197. return result;
  198. }
  199. override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) {
  200. SqlConnection c = (connection as SqlConnection);
  201. if (null != c) {
  202. return c.PoolGroup;
  203. }
  204. return null;
  205. }
  206. override internal DbConnectionInternal GetInnerConnection(DbConnection connection) {
  207. SqlConnection c = (connection as SqlConnection);
  208. if (null != c) {
  209. return c.InnerConnection;
  210. }
  211. return null;
  212. }
  213. override protected int GetObjectId(DbConnection connection) {
  214. SqlConnection c = (connection as SqlConnection);
  215. if (null != c) {
  216. return c.ObjectID;
  217. }
  218. return 0;
  219. }
  220. override internal void PermissionDemand(DbConnection outerConnection) {
  221. SqlConnection c = (outerConnection as SqlConnection);
  222. if (null != c) {
  223. c.PermissionDemand();
  224. }
  225. }
  226. override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) {
  227. SqlConnection c = (outerConnection as SqlConnection);
  228. if (null != c) {
  229. c.PoolGroup = poolGroup;
  230. }
  231. }
  232. override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) {
  233. SqlConnection c = (owningObject as SqlConnection);
  234. if (null != c) {
  235. c.SetInnerConnectionEvent(to);
  236. }
  237. }
  238. override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) {
  239. SqlConnection c = (owningObject as SqlConnection);
  240. if (null != c) {
  241. return c.SetInnerConnectionFrom(to, from);
  242. }
  243. return false;
  244. }
  245. override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) {
  246. SqlConnection c = (owningObject as SqlConnection);
  247. if (null != c) {
  248. c.SetInnerConnectionTo(to);
  249. }
  250. }
  251. }
  252. sealed internal class SqlPerformanceCounters : DbConnectionPoolCounters {
  253. private const string CategoryName = ".NET Data Provider for SqlServer";
  254. private const string CategoryHelp = "Counters for System.Data.SqlClient";
  255. public static readonly SqlPerformanceCounters SingletonInstance = new SqlPerformanceCounters();
  256. #if !MOBILE
  257. [System.Diagnostics.PerformanceCounterPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, PermissionAccess=PerformanceCounterPermissionAccess.Write, MachineName=".", CategoryName=CategoryName)]
  258. private SqlPerformanceCounters() : base (CategoryName, CategoryHelp) {
  259. }
  260. #endif
  261. }
  262. }