SqliteProfileProvider.cs 19 KB

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