SessionSQLServerHandler.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //
  2. // System.Web.Compilation.SessionStateItemCollection
  3. //
  4. // Authors:
  5. // Marek Habersack <[email protected]>
  6. //
  7. // (C) 2009-2010 Novell, Inc (http://novell.com/)
  8. //
  9. // Code based on samples from MSDN
  10. //
  11. // Database schema found in ../ASPState.sql
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. #if NET_2_0
  33. using System;
  34. using System.Collections.Generic;
  35. using System.Collections.Specialized;
  36. using System.Configuration.Provider;
  37. using System.Data;
  38. using System.Data.Common;
  39. using System.IO;
  40. using System.IO.Compression;
  41. using System.Reflection;
  42. using System.Web;
  43. using System.Web.Configuration;
  44. using System.Web.Hosting;
  45. namespace System.Web.SessionState
  46. {
  47. sealed class SessionSQLServerHandler : SessionStateStoreProviderBase
  48. {
  49. static readonly string defaultDbFactoryTypeName = "Mono.Data.Sqlite.SqliteFactory, Mono.Data.Sqlite, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";
  50. SessionStateSection sessionConfig;
  51. string connectionString;
  52. Type providerFactoryType;
  53. DbProviderFactory providerFactory;
  54. int sqlCommandTimeout;
  55. DbProviderFactory ProviderFactory {
  56. get {
  57. if (providerFactory == null) {
  58. try {
  59. providerFactory = Activator.CreateInstance (providerFactoryType) as DbProviderFactory;
  60. } catch (Exception ex) {
  61. throw new ProviderException ("Failure to create database factory instance.", ex);
  62. }
  63. }
  64. return providerFactory;
  65. }
  66. }
  67. public string ApplicationName {
  68. get; private set;
  69. }
  70. public override void Initialize (string name, NameValueCollection config)
  71. {
  72. if (config == null)
  73. throw new ArgumentNullException ("config");
  74. if (String.IsNullOrEmpty (name))
  75. name = "SessionSQLServerHandler";
  76. if (String.IsNullOrEmpty (config["description"])) {
  77. config.Remove ("description");
  78. config.Add ("description", "Mono SQL Session Store Provider");
  79. }
  80. ApplicationName = HostingEnvironment.ApplicationVirtualPath;
  81. base.Initialize(name, config);
  82. sessionConfig = WebConfigurationManager.GetWebApplicationSection ("system.web/sessionState") as SessionStateSection;
  83. connectionString = sessionConfig.SqlConnectionString;
  84. string dbProviderName;
  85. if (String.IsNullOrEmpty (connectionString) || String.Compare (connectionString, SessionStateSection.DefaultSqlConnectionString, StringComparison.Ordinal) == 0) {
  86. connectionString = "Data Source=|DataDirectory|/ASPState.sqlite;Version=3";
  87. dbProviderName = defaultDbFactoryTypeName;
  88. } else {
  89. string[] parts = connectionString.Split (';');
  90. var newCS = new List <string> ();
  91. dbProviderName = null;
  92. bool allowDb = sessionConfig.AllowCustomSqlDatabase;
  93. foreach (string p in parts) {
  94. if (p.Trim ().Length == 0)
  95. continue;
  96. if (p.StartsWith ("DbProviderName", StringComparison.OrdinalIgnoreCase)) {
  97. int idx = p.IndexOf ('=');
  98. if (idx < 0)
  99. throw new ProviderException ("Invalid format for the 'DbProviderName' connection string parameter. Expected 'DbProviderName = value'.");
  100. dbProviderName = p.Substring (idx + 1);
  101. continue;
  102. }
  103. if (!allowDb) {
  104. string tmp = p.Trim ();
  105. if (tmp.StartsWith ("database", StringComparison.OrdinalIgnoreCase) ||
  106. tmp.StartsWith ("initial catalog", StringComparison.OrdinalIgnoreCase))
  107. throw new ProviderException ("Specifying a custom database is not allowed. Set the allowCustomSqlDatabase attribute of the <system.web/sessionState> section to 'true' in order to use a custom database name.");
  108. }
  109. newCS.Add (p);
  110. }
  111. connectionString = String.Join (";", newCS.ToArray ());
  112. if (String.IsNullOrEmpty (dbProviderName))
  113. dbProviderName = defaultDbFactoryTypeName;
  114. }
  115. Exception typeException = null;
  116. try {
  117. providerFactoryType = Type.GetType (dbProviderName, true);
  118. } catch (Exception ex) {
  119. typeException = ex;
  120. providerFactoryType = null;
  121. }
  122. if (providerFactoryType == null)
  123. throw new ProviderException ("Unable to find database provider factory type.", typeException);
  124. sqlCommandTimeout = (int)sessionConfig.SqlCommandTimeout.TotalSeconds;
  125. }
  126. public override void Dispose ()
  127. {
  128. }
  129. public override bool SetItemExpireCallback (SessionStateItemExpireCallback expireCallback)
  130. {
  131. return false;
  132. }
  133. public override void SetAndReleaseItemExclusive (HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
  134. {
  135. DbCommand cmd;
  136. DbCommand deleteCmd = null;
  137. string sessItems = Serialize((SessionStateItemCollection)item.Items);
  138. DbProviderFactory factory = ProviderFactory;
  139. string appName = ApplicationName;
  140. DbConnection conn = CreateConnection (factory);
  141. DateTime now = DateTime.Now;
  142. DbParameterCollection parameters;
  143. if (newItem) {
  144. deleteCmd = CreateCommand (factory, conn, "DELETE FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND Expires < @Expires");
  145. parameters = deleteCmd.Parameters;
  146. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  147. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  148. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", now));
  149. cmd = CreateCommand (factory, conn, "INSERT INTO Sessions (SessionId, ApplicationName, Created, Expires, LockDate, LockId, Timeout, Locked, SessionItems, Flags) Values (@SessionId, @ApplicationName, @Created, @Expires, @LockDate, @LockId , @Timeout, @Locked, @SessionItems, @Flags)");
  150. parameters = cmd.Parameters;
  151. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  152. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  153. parameters.Add (CreateParameter <DateTime> (factory, "@Created", now));
  154. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", now.AddMinutes ((double)item.Timeout)));
  155. parameters.Add (CreateParameter <DateTime> (factory, "@LockDate", now));
  156. parameters.Add (CreateParameter <int> (factory, "@LockId", 0));
  157. parameters.Add (CreateParameter <int> (factory, "@Timeout", item.Timeout));
  158. parameters.Add (CreateParameter <bool> (factory, "@Locked", false));
  159. parameters.Add (CreateParameter <string> (factory, "@SessionItems", sessItems));
  160. parameters.Add (CreateParameter <int> (factory, "@Flags", 0));
  161. } else {
  162. cmd = CreateCommand (factory, conn, "UPDATE Sessions SET Expires = @Expires, SessionItems = @SessionItems, Locked = @Locked WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND LockId = @LockId");
  163. parameters = cmd.Parameters;
  164. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", now.AddMinutes ((double)item.Timeout)));
  165. parameters.Add (CreateParameter <string> (factory, "@SessionItems", sessItems));
  166. parameters.Add (CreateParameter <bool> (factory, "@Locked", false));
  167. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  168. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  169. parameters.Add (CreateParameter <int> (factory, "@Lockid", (int)lockId));
  170. }
  171. try
  172. {
  173. conn.Open();
  174. if (deleteCmd != null)
  175. deleteCmd.ExecuteNonQuery();
  176. cmd.ExecuteNonQuery();
  177. } catch (Exception ex) {
  178. throw new ProviderException ("Failure storing session item in database.", ex);
  179. } finally {
  180. conn.Close();
  181. }
  182. }
  183. public override SessionStateStoreData GetItem (HttpContext context, string id, out bool locked, out TimeSpan lockAge,
  184. out object lockId, out SessionStateActions actionFlags)
  185. {
  186. return GetSessionStoreItem (false, context, id, out locked, out lockAge, out lockId, out actionFlags);
  187. }
  188. public override SessionStateStoreData GetItemExclusive (HttpContext context, string id, out bool locked,out TimeSpan lockAge,
  189. out object lockId, out SessionStateActions actionFlags)
  190. {
  191. return GetSessionStoreItem (true, context, id, out locked, out lockAge, out lockId, out actionFlags);
  192. }
  193. private SessionStateStoreData GetSessionStoreItem (bool lockRecord, HttpContext context, string id, out bool locked,
  194. out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
  195. {
  196. SessionStateStoreData item = null;
  197. lockAge = TimeSpan.Zero;
  198. lockId = null;
  199. locked = false;
  200. actionFlags = 0;
  201. DbProviderFactory factory = ProviderFactory;
  202. DbConnection conn = CreateConnection (factory);
  203. string appName = ApplicationName;
  204. DbCommand cmd = null;
  205. DbDataReader reader = null;
  206. DbParameterCollection parameters;
  207. DateTime expires;
  208. string serializedItems = String.Empty;
  209. bool foundRecord = false;
  210. bool deleteData = false;
  211. int timeout = 0;
  212. DateTime now = DateTime.Now;
  213. try {
  214. conn.Open();
  215. if (lockRecord) {
  216. cmd = CreateCommand (factory, conn, "UPDATE Sessions SET Locked = @Locked, LockDate = @LockDate WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND Expires > @Expires");
  217. parameters = cmd.Parameters;
  218. parameters.Add (CreateParameter <bool> (factory, "@Locked", true));
  219. parameters.Add (CreateParameter <DateTime> (factory, "@LockDate", now));
  220. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  221. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  222. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", now));
  223. if (cmd.ExecuteNonQuery() == 0)
  224. locked = true;
  225. else
  226. locked = false;
  227. }
  228. cmd = CreateCommand (factory, conn, "SELECT Expires, SessionItems, LockId, LockDate, Flags, Timeout FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
  229. parameters = cmd.Parameters;
  230. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  231. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  232. reader = cmd.ExecuteReader (CommandBehavior.SingleRow);
  233. while (reader.Read()) {
  234. expires = reader.GetDateTime (reader.GetOrdinal ("Expires"));
  235. if (expires < now) {
  236. locked = false;
  237. deleteData = true;
  238. } else
  239. foundRecord = true;
  240. serializedItems = reader.GetString (reader.GetOrdinal ("SessionItems"));
  241. lockId = reader.GetInt32 (reader.GetOrdinal ("LockId"));
  242. lockAge = now.Subtract (reader.GetDateTime (reader.GetOrdinal ("LockDate")));
  243. actionFlags = (SessionStateActions) reader.GetInt32 (reader.GetOrdinal ("Flags"));
  244. timeout = reader.GetInt32 (reader.GetOrdinal ("Timeout"));
  245. }
  246. reader.Close();
  247. if (deleteData) {
  248. cmd = CreateCommand (factory, conn, "DELETE FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
  249. parameters = cmd.Parameters;
  250. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  251. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  252. cmd.ExecuteNonQuery();
  253. }
  254. if (!foundRecord)
  255. locked = false;
  256. if (foundRecord && !locked) {
  257. lockId = (int)lockId + 1;
  258. cmd = CreateCommand (factory, conn, "UPDATE Sessions SET LockId = @LockId, Flags = 0 WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
  259. parameters = cmd.Parameters;
  260. parameters.Add (CreateParameter <int> (factory, "@LockId", (int)lockId));
  261. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  262. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", appName, 255));
  263. cmd.ExecuteNonQuery();
  264. if (actionFlags == SessionStateActions.InitializeItem)
  265. item = CreateNewStoreData (context, (int)sessionConfig.Timeout.TotalMinutes);
  266. else
  267. item = Deserialize (context, serializedItems, timeout);
  268. }
  269. } catch (Exception ex) {
  270. throw new ProviderException ("Unable to retrieve session item from database.", ex);
  271. } finally {
  272. if (reader != null)
  273. reader.Close ();
  274. conn.Close();
  275. }
  276. return item;
  277. }
  278. string Serialize (SessionStateItemCollection items)
  279. {
  280. #if NET_4_0
  281. GZipStream gzip = null;
  282. #endif
  283. Stream output;
  284. MemoryStream ms = null;
  285. BinaryWriter writer = null;
  286. try {
  287. ms = new MemoryStream ();
  288. #if NET_4_0
  289. if (sessionConfig.CompressionEnabled)
  290. output = gzip = new GZipStream (ms, CompressionMode.Compress, true);
  291. else
  292. #endif
  293. output = ms;
  294. writer = new BinaryWriter (output);
  295. if (items != null)
  296. items.Serialize (writer);
  297. #if NET_4_0
  298. if (gzip != null)
  299. gzip.Close ();
  300. #endif
  301. writer.Close ();
  302. return Convert.ToBase64String (ms.ToArray ());
  303. } finally {
  304. #if NET_4_0
  305. if (writer != null)
  306. writer.Dispose ();
  307. if (gzip != null)
  308. gzip.Dispose ();
  309. #else
  310. if (writer != null)
  311. ((IDisposable)writer).Dispose ();
  312. #endif
  313. if (ms != null)
  314. ms.Dispose ();
  315. }
  316. }
  317. SessionStateStoreData Deserialize (HttpContext context, string serializedItems, int timeout)
  318. {
  319. MemoryStream ms = null;
  320. Stream input;
  321. BinaryReader reader = null;
  322. #if NET_4_0
  323. GZipStream gzip = null;
  324. #endif
  325. try {
  326. ms = new MemoryStream (Convert.FromBase64String (serializedItems));
  327. var sessionItems = new SessionStateItemCollection ();
  328. if (ms.Length > 0) {
  329. #if NET_4_0
  330. if (sessionConfig.CompressionEnabled)
  331. input = gzip = new GZipStream (ms, CompressionMode.Decompress, true);
  332. else
  333. #endif
  334. input = ms;
  335. reader = new BinaryReader (input);
  336. sessionItems = SessionStateItemCollection.Deserialize (reader);
  337. #if NET_4_0
  338. if (gzip != null)
  339. gzip.Close ();
  340. #endif
  341. reader.Close ();
  342. }
  343. return new SessionStateStoreData (sessionItems, SessionStateUtility.GetSessionStaticObjects (context), timeout);
  344. } finally {
  345. #if NET_4_0
  346. if (reader != null)
  347. reader.Dispose ();
  348. if (gzip != null)
  349. gzip.Dispose ();
  350. #else
  351. if (reader != null)
  352. ((IDisposable)reader).Dispose ();
  353. #endif
  354. if (ms != null)
  355. ms.Dispose ();
  356. }
  357. }
  358. public override void ReleaseItemExclusive (HttpContext context, string id, object lockId)
  359. {
  360. DbProviderFactory factory = ProviderFactory;
  361. DbConnection conn = CreateConnection (factory);
  362. DbCommand cmd = CreateCommand (factory, conn,
  363. "UPDATE Sessions SET Locked = 0, Expires = @Expires WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND LockId = @LockId");
  364. DbParameterCollection parameters = cmd.Parameters;
  365. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", DateTime.Now.AddMinutes(sessionConfig.Timeout.TotalMinutes)));
  366. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  367. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", ApplicationName, 255));
  368. parameters.Add (CreateParameter <int> (factory, "@LockId", (int)lockId));
  369. try {
  370. conn.Open ();
  371. cmd.ExecuteNonQuery ();
  372. } catch (Exception ex) {
  373. throw new ProviderException ("Error releasing item in database.", ex);
  374. } finally {
  375. conn.Close();
  376. }
  377. }
  378. public override void RemoveItem (HttpContext context, string id, object lockId, SessionStateStoreData item)
  379. {
  380. DbProviderFactory factory = ProviderFactory;
  381. DbConnection conn = CreateConnection (factory);
  382. DbCommand cmd = CreateCommand (factory, conn,
  383. "DELETE * FROM Sessions WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName AND LockId = @LockId");
  384. DbParameterCollection parameters = cmd.Parameters;
  385. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  386. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", ApplicationName, 255));
  387. parameters.Add (CreateParameter <int> (factory, "@LockId", (int)lockId));
  388. try {
  389. conn.Open ();
  390. cmd.ExecuteNonQuery ();
  391. } catch (Exception ex) {
  392. throw new ProviderException ("Error removing item from database.", ex);
  393. } finally {
  394. conn.Close();
  395. }
  396. }
  397. public override void CreateUninitializedItem (HttpContext context, string id, int timeout)
  398. {
  399. DbProviderFactory factory = ProviderFactory;
  400. DbConnection conn = CreateConnection (factory);
  401. DbCommand cmd = CreateCommand (factory, conn,
  402. "INSERT INTO Sessions (SessionId, ApplicationName, Created, Expires, LockDate, LockId, Timeout, Locked, SessionItems, Flags) Values (@SessionId, @ApplicationName, @Created, @Expires, @LockDate, @LockId , @Timeout, @Locked, @SessionItems, @Flags)");
  403. DateTime now = DateTime.Now;
  404. DbParameterCollection parameters = cmd.Parameters;
  405. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  406. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", ApplicationName, 255));
  407. parameters.Add (CreateParameter <DateTime> (factory, "@Created", now));
  408. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", now.AddMinutes ((double)timeout)));
  409. parameters.Add (CreateParameter <DateTime> (factory, "@LockDate", now));
  410. parameters.Add (CreateParameter <int> (factory, "@LockId", 0));
  411. parameters.Add (CreateParameter <int> (factory, "@Timeout", timeout));
  412. parameters.Add (CreateParameter <bool> (factory, "@Locked", false));
  413. parameters.Add (CreateParameter <string> (factory, "@SessionItems", String.Empty));
  414. parameters.Add (CreateParameter <int> (factory, "@Flags", 1));
  415. try {
  416. conn.Open ();
  417. cmd.ExecuteNonQuery ();
  418. } catch (Exception ex) {
  419. throw new ProviderException ("Error creating uninitialized session item in the database.", ex);
  420. } finally {
  421. conn.Close();
  422. }
  423. }
  424. public override SessionStateStoreData CreateNewStoreData (HttpContext context, int timeout)
  425. {
  426. return new SessionStateStoreData (new SessionStateItemCollection (), SessionStateUtility.GetSessionStaticObjects (context), timeout);
  427. }
  428. public override void ResetItemTimeout (HttpContext context, string id)
  429. {
  430. DbProviderFactory factory = ProviderFactory;
  431. DbConnection conn = CreateConnection (factory);
  432. DbCommand cmd = CreateCommand (factory, conn,
  433. "UPDATE Sessions SET Expires = @Expires WHERE SessionId = @SessionId AND ApplicationName = @ApplicationName");
  434. DbParameterCollection parameters = cmd.Parameters;
  435. parameters.Add (CreateParameter <DateTime> (factory, "@Expires", DateTime.Now.AddMinutes (sessionConfig.Timeout.TotalMinutes)));
  436. parameters.Add (CreateParameter <string> (factory, "@SessionId", id, 80));
  437. parameters.Add (CreateParameter <string> (factory, "@ApplicationName", ApplicationName, 255));
  438. try {
  439. conn.Open ();
  440. cmd.ExecuteNonQuery ();
  441. } catch (Exception ex) {
  442. throw new ProviderException ("Error resetting session item timeout in the database.", ex);
  443. } finally {
  444. conn.Close();
  445. }
  446. }
  447. public override void InitializeRequest (HttpContext context)
  448. {
  449. }
  450. public override void EndRequest(HttpContext context)
  451. {
  452. }
  453. DbConnection CreateConnection (DbProviderFactory factory)
  454. {
  455. DbConnection conn = factory.CreateConnection ();
  456. conn.ConnectionString = connectionString;
  457. return conn;
  458. }
  459. DbCommand CreateCommand (DbProviderFactory factory, DbConnection conn, string commandText)
  460. {
  461. DbCommand cmd = factory.CreateCommand ();
  462. cmd.CommandTimeout = sqlCommandTimeout;
  463. cmd.Connection = conn;
  464. cmd.CommandText = commandText;
  465. return cmd;
  466. }
  467. DbParameter CreateParameter <ValueType> (DbProviderFactory factory, string name, ValueType value)
  468. {
  469. return CreateParameter <ValueType> (factory, name, value, -1);
  470. }
  471. DbParameter CreateParameter <ValueType> (DbProviderFactory factory, string name, ValueType value, int size)
  472. {
  473. DbParameter param = factory.CreateParameter ();
  474. param.ParameterName = name;
  475. Type vt = typeof (ValueType);
  476. if (vt == typeof (string))
  477. param.DbType = DbType.String;
  478. else if (vt == typeof (int))
  479. param.DbType = DbType.Int32;
  480. else if (vt == typeof (bool))
  481. param.DbType = DbType.Boolean;
  482. else if (vt == typeof (DateTime))
  483. param.DbType = DbType.DateTime;
  484. if (size > -1)
  485. param.Size = size;
  486. param.Value = value;
  487. return param;
  488. }
  489. }
  490. }
  491. #endif