SqliteProfileProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. //
  2. // $Id: PgProfileProvider.cs 36 2007-11-24 09:44:42Z dna $
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. // Copyright © 2006, 2007 Nauck IT KG http://www.nauck-it.de
  24. //
  25. // Author:
  26. // Daniel Nauck <d.nauck(at)nauck-it.de>
  27. //
  28. // Adapted to Sqlite by Marek Habersack <[email protected]>
  29. //
  30. #if NET_2_0
  31. using System;
  32. using System.Data;
  33. using System.Data.Common;
  34. using System.Configuration;
  35. using System.Configuration.Provider;
  36. using System.Collections.Generic;
  37. using System.Collections.Specialized;
  38. using System.Diagnostics;
  39. using System.Text;
  40. using System.Web.Hosting;
  41. using System.Web.Util;
  42. using Mono.Data.Sqlite;
  43. namespace System.Web.Profile
  44. {
  45. internal class SqliteProfileProvider : ProfileProvider
  46. {
  47. const string m_ProfilesTableName = "Profiles";
  48. const string m_ProfileDataTableName = "ProfileData";
  49. string m_ConnectionString = string.Empty;
  50. SerializationHelper m_serializationHelper = new SerializationHelper();
  51. DbParameter AddParameter (DbCommand command, string parameterName)
  52. {
  53. return AddParameter (command, parameterName, null);
  54. }
  55. DbParameter AddParameter (DbCommand command, string parameterName, object parameterValue)
  56. {
  57. return AddParameter (command, parameterName, ParameterDirection.Input, parameterValue);
  58. }
  59. DbParameter AddParameter (DbCommand command, string parameterName, ParameterDirection direction, object parameterValue)
  60. {
  61. DbParameter dbp = command.CreateParameter ();
  62. dbp.ParameterName = parameterName;
  63. dbp.Value = parameterValue;
  64. dbp.Direction = direction;
  65. command.Parameters.Add (dbp);
  66. return dbp;
  67. }
  68. /// <summary>
  69. /// System.Configuration.Provider.ProviderBase.Initialize Method
  70. /// </summary>
  71. public override void Initialize(string name, NameValueCollection config)
  72. {
  73. // Initialize values from web.config.
  74. if (config == null)
  75. throw new ArgumentNullException("Config", Properties.Resources.ErrArgumentNull);
  76. if (string.IsNullOrEmpty(name))
  77. name = Properties.Resources.ProfileProviderDefaultName;
  78. if (string.IsNullOrEmpty(config["description"]))
  79. {
  80. config.Remove("description");
  81. config.Add("description", Properties.Resources.ProfileProviderDefaultDescription);
  82. }
  83. // Initialize the abstract base class.
  84. base.Initialize(name, config);
  85. m_ApplicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);
  86. // Get connection string.
  87. string connStrName = config["connectionStringName"];
  88. if (string.IsNullOrEmpty(connStrName))
  89. {
  90. throw new ArgumentOutOfRangeException("ConnectionStringName", Properties.Resources.ErrArgumentNullOrEmpty);
  91. }
  92. else
  93. {
  94. ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[connStrName];
  95. if (ConnectionStringSettings == null || string.IsNullOrEmpty(ConnectionStringSettings.ConnectionString.Trim()))
  96. {
  97. throw new ProviderException(Properties.Resources.ErrConnectionStringNullOrEmpty);
  98. }
  99. m_ConnectionString = ConnectionStringSettings.ConnectionString;
  100. }
  101. }
  102. /// <summary>
  103. /// System.Web.Profile.ProfileProvider properties.
  104. /// </summary>
  105. #region System.Web.Security.ProfileProvider properties
  106. string m_ApplicationName = string.Empty;
  107. public override string ApplicationName
  108. {
  109. get { return m_ApplicationName; }
  110. set { m_ApplicationName = value; }
  111. }
  112. #endregion
  113. /// <summary>
  114. /// System.Web.Profile.ProfileProvider methods.
  115. /// </summary>
  116. #region System.Web.Security.ProfileProvider methods
  117. /// <summary>
  118. /// ProfileProvider.DeleteInactiveProfiles
  119. /// </summary>
  120. public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
  121. {
  122. throw new Exception("DeleteInactiveProfiles: The method or operation is not implemented.");
  123. }
  124. public override int DeleteProfiles(string[] usernames)
  125. {
  126. throw new Exception("DeleteProfiles1: The method or operation is not implemented.");
  127. }
  128. public override int DeleteProfiles(ProfileInfoCollection profiles)
  129. {
  130. throw new Exception("DeleteProfiles2: The method or operation is not implemented.");
  131. }
  132. public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
  133. {
  134. throw new Exception("FindInactiveProfilesByUserName: The method or operation is not implemented.");
  135. }
  136. public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
  137. {
  138. throw new Exception("FindProfilesByUserName: The method or operation is not implemented.");
  139. }
  140. public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
  141. {
  142. throw new Exception("GetAllInactiveProfiles: The method or operation is not implemented.");
  143. }
  144. public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords)
  145. {
  146. throw new Exception("GetAllProfiles: The method or operation is not implemented.");
  147. }
  148. public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
  149. {
  150. throw new Exception("GetNumberOfInactiveProfiles: The method or operation is not implemented.");
  151. }
  152. #endregion
  153. /// <summary>
  154. /// System.Configuration.SettingsProvider methods.
  155. /// </summary>
  156. #region System.Web.Security.SettingsProvider methods
  157. /// <summary>
  158. ///
  159. /// </summary>
  160. public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
  161. {
  162. SettingsPropertyValueCollection result = new SettingsPropertyValueCollection();
  163. string username = (string)context["UserName"];
  164. bool isAuthenticated = (bool)context["IsAuthenticated"];
  165. Dictionary<string, object> databaseResult = new Dictionary<string, object>();
  166. using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
  167. {
  168. using (SqliteCommand dbCommand = dbConn.CreateCommand())
  169. {
  170. dbCommand.CommandText = string.Format("SELECT \"Name\", \"ValueString\", \"ValueBinary\" FROM \"{0}\" WHERE \"Profile\" = (SELECT \"pId\" FROM \"{1}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsAnonymous\" = @IsAuthenticated)", m_ProfileDataTableName, m_ProfilesTableName);
  171. AddParameter (dbCommand, "@Username", username);
  172. AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
  173. AddParameter (dbCommand, "@IsAuthenticated", !isAuthenticated);
  174. try
  175. {
  176. dbConn.Open();
  177. dbCommand.Prepare();
  178. using (SqliteDataReader reader = dbCommand.ExecuteReader())
  179. {
  180. while (reader.Read())
  181. {
  182. object resultData = null;
  183. if(!reader.IsDBNull(1))
  184. resultData = reader.GetValue(1);
  185. else if(!reader.IsDBNull(2))
  186. resultData = reader.GetValue(2);
  187. databaseResult.Add(reader.GetString(0), resultData);
  188. }
  189. }
  190. }
  191. catch (SqliteException e)
  192. {
  193. Trace.WriteLine(e.ToString());
  194. throw new ProviderException(Properties.Resources.ErrOperationAborted);
  195. }
  196. finally
  197. {
  198. if (dbConn != null)
  199. dbConn.Close();
  200. }
  201. }
  202. }
  203. foreach (SettingsProperty item in collection)
  204. {
  205. if (item.SerializeAs == SettingsSerializeAs.ProviderSpecific)
  206. {
  207. if (item.PropertyType.IsPrimitive || item.PropertyType.Equals(typeof(string)))
  208. item.SerializeAs = SettingsSerializeAs.String;
  209. else
  210. item.SerializeAs = SettingsSerializeAs.Xml;
  211. }
  212. SettingsPropertyValue itemValue = new SettingsPropertyValue(item);
  213. if ((databaseResult.ContainsKey(item.Name)) && (databaseResult[item.Name] != null))
  214. {
  215. if(item.SerializeAs == SettingsSerializeAs.String)
  216. itemValue.PropertyValue = m_serializationHelper.DeserializeFromBase64((string)databaseResult[item.Name]);
  217. else if (item.SerializeAs == SettingsSerializeAs.Xml)
  218. itemValue.PropertyValue = m_serializationHelper.DeserializeFromXml((string)databaseResult[item.Name]);
  219. else if (item.SerializeAs == SettingsSerializeAs.Binary)
  220. itemValue.PropertyValue = m_serializationHelper.DeserializeFromBinary((byte[])databaseResult[item.Name]);
  221. }
  222. itemValue.IsDirty = false;
  223. result.Add(itemValue);
  224. }
  225. UpdateActivityDates(username, isAuthenticated, true);
  226. return result;
  227. }
  228. public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
  229. {
  230. string username = (string)context["UserName"];
  231. bool isAuthenticated = (bool)context["IsAuthenticated"];
  232. if (collection.Count < 1)
  233. return;
  234. if (!ProfileExists(username))
  235. CreateProfileForUser(username, isAuthenticated);
  236. using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
  237. {
  238. using (SqliteCommand deleteCommand = dbConn.CreateCommand(),
  239. insertCommand = dbConn.CreateCommand())
  240. {
  241. deleteCommand.CommandText = string.Format("DELETE FROM \"{0}\" WHERE \"Name\" = @Name AND \"Profile\" = (SELECT \"pId\" FROM \"{1}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsAnonymous\" = @IsAuthenticated)", m_ProfileDataTableName, m_ProfilesTableName);
  242. AddParameter (deleteCommand, "@Name");
  243. AddParameter (deleteCommand, "@Username", username);
  244. AddParameter (deleteCommand, "@ApplicationName", m_ApplicationName);
  245. AddParameter (deleteCommand, "@IsAuthenticated", !isAuthenticated);
  246. insertCommand.CommandText = string.Format("INSERT INTO \"{0}\" (\"pId\", \"Profile\", \"Name\", \"ValueString\", \"ValueBinary\") VALUES (@pId, (SELECT \"pId\" FROM \"{1}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsAnonymous\" = @IsAuthenticated), @Name, @ValueString, @ValueBinary)", m_ProfileDataTableName, m_ProfilesTableName);
  247. AddParameter (insertCommand, "@pId");
  248. AddParameter (insertCommand, "@Name");
  249. AddParameter (insertCommand, "@ValueString");
  250. insertCommand.Parameters["@ValueString"].IsNullable = true;
  251. AddParameter (insertCommand, "@ValueBinary");
  252. insertCommand.Parameters["@ValueBinary"].IsNullable = true;
  253. AddParameter (insertCommand, "@Username", username);
  254. AddParameter (insertCommand, "@ApplicationName", m_ApplicationName);
  255. AddParameter (insertCommand, "@IsAuthenticated", !isAuthenticated);
  256. SqliteTransaction dbTrans = null;
  257. try
  258. {
  259. dbConn.Open();
  260. deleteCommand.Prepare();
  261. insertCommand.Prepare();
  262. using (dbTrans = dbConn.BeginTransaction())
  263. {
  264. foreach (SettingsPropertyValue item in collection)
  265. {
  266. if (!item.IsDirty)
  267. continue;
  268. deleteCommand.Parameters["@Name"].Value = item.Name;
  269. insertCommand.Parameters["@pId"].Value = Guid.NewGuid().ToString();
  270. insertCommand.Parameters["@Name"].Value = item.Name;
  271. if (item.Property.SerializeAs == SettingsSerializeAs.String)
  272. {
  273. insertCommand.Parameters["@ValueString"].Value = m_serializationHelper.SerializeToBase64(item.PropertyValue);
  274. insertCommand.Parameters["@ValueBinary"].Value = DBNull.Value; //new byte[0];//DBNull.Value;
  275. }
  276. else if (item.Property.SerializeAs == SettingsSerializeAs.Xml)
  277. {
  278. item.SerializedValue = m_serializationHelper.SerializeToXml(item.PropertyValue);
  279. insertCommand.Parameters["@ValueString"].Value = item.SerializedValue;
  280. insertCommand.Parameters["@ValueBinary"].Value = DBNull.Value; //new byte[0];//DBNull.Value;
  281. }
  282. else if (item.Property.SerializeAs == SettingsSerializeAs.Binary)
  283. {
  284. item.SerializedValue = m_serializationHelper.SerializeToBinary(item.PropertyValue);
  285. insertCommand.Parameters["@ValueString"].Value = DBNull.Value; //string.Empty;//DBNull.Value;
  286. insertCommand.Parameters["@ValueBinary"].Value = item.SerializedValue;
  287. }
  288. deleteCommand.ExecuteNonQuery();
  289. insertCommand.ExecuteNonQuery();
  290. }
  291. UpdateActivityDates(username, isAuthenticated, false);
  292. // Attempt to commit the transaction
  293. dbTrans.Commit();
  294. }
  295. }
  296. catch (SqliteException e)
  297. {
  298. Trace.WriteLine(e.ToString());
  299. try
  300. {
  301. // Attempt to roll back the transaction
  302. Trace.WriteLine(Properties.Resources.LogRollbackAttempt);
  303. dbTrans.Rollback();
  304. }
  305. catch (SqliteException re)
  306. {
  307. // Rollback failed
  308. Trace.WriteLine(Properties.Resources.ErrRollbackFailed);
  309. Trace.WriteLine(re.ToString());
  310. }
  311. throw new ProviderException(Properties.Resources.ErrOperationAborted);
  312. }
  313. finally
  314. {
  315. if (dbConn != null)
  316. dbConn.Close();
  317. }
  318. }
  319. }
  320. }
  321. #endregion
  322. #region private methods
  323. /// <summary>
  324. /// Create a empty user profile
  325. /// </summary>
  326. /// <param name="username"></param>
  327. /// <param name="isAuthenticated"></param>
  328. void CreateProfileForUser(string username, bool isAuthenticated)
  329. {
  330. if (ProfileExists(username))
  331. {
  332. throw new ProviderException(string.Format(Properties.Resources.ErrProfileAlreadyExist, username));
  333. }
  334. using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
  335. {
  336. using (SqliteCommand dbCommand = dbConn.CreateCommand())
  337. {
  338. dbCommand.CommandText = string.Format("INSERT INTO \"{0}\" (\"pId\", \"Username\", \"ApplicationName\", \"IsAnonymous\", \"LastActivityDate\", \"LastUpdatedDate\") Values (@pId, @Username, @ApplicationName, @IsAuthenticated, @LastActivityDate, @LastUpdatedDate)", m_ProfilesTableName);
  339. AddParameter (dbCommand, "@pId", Guid.NewGuid().ToString());
  340. AddParameter (dbCommand, "@Username", username);
  341. AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
  342. AddParameter (dbCommand, "@IsAuthenticated", !isAuthenticated);
  343. AddParameter (dbCommand, "@LastActivityDate", DateTime.Now);
  344. AddParameter (dbCommand, "@LastUpdatedDate", DateTime.Now);
  345. try
  346. {
  347. dbConn.Open();
  348. dbCommand.Prepare();
  349. dbCommand.ExecuteNonQuery();
  350. }
  351. catch (SqliteException e)
  352. {
  353. Trace.WriteLine(e.ToString());
  354. throw new ProviderException(Properties.Resources.ErrOperationAborted);
  355. }
  356. finally
  357. {
  358. if (dbConn != null)
  359. dbConn.Close();
  360. }
  361. }
  362. }
  363. }
  364. bool ProfileExists(string username)
  365. {
  366. using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
  367. {
  368. using (SqliteCommand dbCommand = dbConn.CreateCommand())
  369. {
  370. dbCommand.CommandText = string.Format("SELECT COUNT(*) FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_ProfilesTableName);
  371. AddParameter (dbCommand, "@Username", username);
  372. AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
  373. try
  374. {
  375. dbConn.Open();
  376. dbCommand.Prepare();
  377. int numRecs = 0;
  378. Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out numRecs);
  379. if (numRecs > 0)
  380. return true;
  381. }
  382. catch (SqliteException e)
  383. {
  384. Trace.WriteLine(e.ToString());
  385. throw new ProviderException(Properties.Resources.ErrOperationAborted);
  386. }
  387. finally
  388. {
  389. if (dbConn != null)
  390. dbConn.Close();
  391. }
  392. }
  393. }
  394. return false;
  395. }
  396. /// <summary>
  397. /// Updates the LastActivityDate and LastUpdatedDate values when profile properties are accessed by the
  398. /// GetPropertyValues and SetPropertyValues methods.
  399. /// Passing true as the activityOnly parameter will update only the LastActivityDate.
  400. /// </summary>
  401. /// <param name="username"></param>
  402. /// <param name="isAuthenticated"></param>
  403. /// <param name="activityOnly"></param>
  404. void UpdateActivityDates(string username, bool isAuthenticated, bool activityOnly)
  405. {
  406. using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
  407. {
  408. using (SqliteCommand dbCommand = dbConn.CreateCommand())
  409. {
  410. if (activityOnly)
  411. {
  412. dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"LastActivityDate\" = @LastActivityDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsAnonymous\" = @IsAuthenticated", m_ProfilesTableName);
  413. AddParameter (dbCommand, "@LastActivityDate", DateTime.Now);
  414. }
  415. else
  416. {
  417. dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"LastActivityDate\" = @LastActivityDate, \"LastUpdatedDate\" = @LastUpdatedDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsAnonymous\" = @IsAuthenticated", m_ProfilesTableName);
  418. AddParameter (dbCommand, "@LastActivityDate", DateTime.Now);
  419. AddParameter (dbCommand, "@LastUpdatedDate", DateTime.Now);
  420. }
  421. AddParameter (dbCommand, "@Username", username);
  422. AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
  423. AddParameter (dbCommand, "@IsAuthenticated", !isAuthenticated);
  424. try
  425. {
  426. dbConn.Open();
  427. dbCommand.Prepare();
  428. dbCommand.ExecuteNonQuery();
  429. }
  430. catch (SqliteException e)
  431. {
  432. Trace.WriteLine(e.ToString());
  433. throw new ProviderException(Properties.Resources.ErrOperationAborted);
  434. }
  435. finally
  436. {
  437. if (dbConn != null)
  438. dbConn.Close();
  439. }
  440. }
  441. }
  442. }
  443. /// <summary>
  444. /// A helper function to retrieve config values from the configuration file.
  445. /// </summary>
  446. /// <param name="configValue"></param>
  447. /// <param name="defaultValue"></param>
  448. /// <returns></returns>
  449. string GetConfigValue(string configValue, string defaultValue)
  450. {
  451. if (string.IsNullOrEmpty(configValue))
  452. return defaultValue;
  453. return configValue;
  454. }
  455. #endregion
  456. }
  457. }
  458. #endif