SqliteProfileProvider.cs 20 KB

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