SqlProfileProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. //
  2. // System.Web.UI.WebControls.SqlProfileProvider.cs
  3. //
  4. // Authors:
  5. // Chris Toshok ([email protected])
  6. // Vladimir Krasnov ([email protected])
  7. //
  8. // (C) 2006 Novell, Inc (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Data;
  31. using System.Data.Common;
  32. using System.Collections;
  33. using System.Globalization;
  34. using System.Configuration;
  35. using System.Configuration.Provider;
  36. using System.Web.Configuration;
  37. using System.Collections.Specialized;
  38. using System.IO;
  39. using System.Text;
  40. using System.Web.Security;
  41. using System.Web.Util;
  42. namespace System.Web.Profile
  43. {
  44. public class SqlProfileProvider : ProfileProvider
  45. {
  46. ConnectionStringSettings connectionString;
  47. DbProviderFactory factory;
  48. string applicationName;
  49. bool schemaIsOk = false;
  50. public override int DeleteInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
  51. {
  52. using (DbConnection connection = CreateConnection ()) {
  53. DbCommand command = factory.CreateCommand ();
  54. command.Connection = connection;
  55. command.CommandType = CommandType.StoredProcedure;
  56. command.CommandText = @"aspnet_Profile_DeleteInactiveProfiles";
  57. AddParameter (command, "ApplicationName", ApplicationName);
  58. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  59. AddParameter (command, "InactiveSinceDate", userInactiveSinceDate);
  60. DbParameter returnValue = AddParameter (command, null, ParameterDirection.ReturnValue, null);
  61. command.ExecuteNonQuery ();
  62. int retVal = GetReturnValue (returnValue);
  63. return retVal;
  64. }
  65. }
  66. public override int DeleteProfiles (ProfileInfoCollection profiles)
  67. {
  68. if (profiles == null)
  69. throw new ArgumentNullException ("prfoles");
  70. if (profiles.Count == 0)
  71. throw new ArgumentException ("prfoles");
  72. string [] usernames = new string [profiles.Count];
  73. int i = 0;
  74. foreach (ProfileInfo pi in profiles) {
  75. if (pi.UserName == null)
  76. throw new ArgumentNullException ("element in profiles collection is null");
  77. if (pi.UserName.Length == 0 || pi.UserName.Length > 256 || pi.UserName.IndexOf (',') != -1)
  78. throw new ArgumentException ("element in profiles collection in illegal format");
  79. usernames [i++] = pi.UserName;
  80. }
  81. return DeleteProfilesInternal (usernames);
  82. }
  83. public override int DeleteProfiles (string [] usernames)
  84. {
  85. if (usernames == null)
  86. throw new ArgumentNullException ("usernames");
  87. Hashtable users = new Hashtable ();
  88. foreach (string username in usernames) {
  89. if (username == null)
  90. throw new ArgumentNullException ("element in usernames array is null");
  91. if (username.Length == 0 || username.Length > 256 || username.IndexOf (',') != -1)
  92. throw new ArgumentException ("element in usernames array in illegal format");
  93. if (users.ContainsKey(username))
  94. throw new ArgumentException ("duplicate element in usernames array");
  95. users.Add (username, username);
  96. }
  97. return DeleteProfilesInternal (usernames);
  98. }
  99. int DeleteProfilesInternal (string [] usernames)
  100. {
  101. using (DbConnection connection = CreateConnection ()) {
  102. DbCommand command = factory.CreateCommand ();
  103. command.Connection = connection;
  104. command.CommandType = CommandType.StoredProcedure;
  105. command.CommandText = @"aspnet_Profile_DeleteProfiles";
  106. AddParameter (command, "ApplicationName", ApplicationName);
  107. AddParameter (command, "UserNames", string.Join (",", usernames));
  108. DbParameter returnValue = AddParameter (command, null, ParameterDirection.ReturnValue, null);
  109. command.ExecuteNonQuery ();
  110. int retVal = GetReturnValue (returnValue);
  111. return retVal;
  112. }
  113. }
  114. public override ProfileInfoCollection FindInactiveProfilesByUserName (ProfileAuthenticationOption authenticationOption,
  115. string usernameToMatch,
  116. DateTime userInactiveSinceDate,
  117. int pageIndex,
  118. int pageSize,
  119. out int totalRecords)
  120. {
  121. CheckParam ("usernameToMatch", usernameToMatch, 256);
  122. if (pageIndex < 0)
  123. throw new ArgumentException("pageIndex is less than zero");
  124. if (pageSize < 1)
  125. throw new ArgumentException ("pageIndex is less than one");
  126. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  127. throw new ArgumentException ("pageIndex and pageSize are too large");
  128. using (DbConnection connection = CreateConnection ()) {
  129. DbCommand command = factory.CreateCommand ();
  130. command.Connection = connection;
  131. command.CommandType = CommandType.StoredProcedure;
  132. command.CommandText = @"aspnet_Profile_GetProfiles";
  133. AddParameter (command, "ApplicationName", ApplicationName);
  134. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  135. AddParameter (command, "PageIndex", pageIndex);
  136. AddParameter (command, "PageSize", pageSize);
  137. AddParameter (command, "UserNameToMatch", usernameToMatch);
  138. AddParameter (command, "InactiveSinceDate", userInactiveSinceDate);
  139. using (DbDataReader reader = command.ExecuteReader ()) {
  140. return BuildProfileInfoCollection (reader, out totalRecords);
  141. }
  142. }
  143. }
  144. public override ProfileInfoCollection FindProfilesByUserName (ProfileAuthenticationOption authenticationOption,
  145. string usernameToMatch,
  146. int pageIndex,
  147. int pageSize,
  148. out int totalRecords)
  149. {
  150. CheckParam ("usernameToMatch", usernameToMatch, 256);
  151. if (pageIndex < 0)
  152. throw new ArgumentException ("pageIndex is less than zero");
  153. if (pageSize < 1)
  154. throw new ArgumentException ("pageIndex is less than one");
  155. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  156. throw new ArgumentException ("pageIndex and pageSize are too large");
  157. using (DbConnection connection = CreateConnection ()) {
  158. DbCommand command = factory.CreateCommand ();
  159. command.Connection = connection;
  160. command.CommandType = CommandType.StoredProcedure;
  161. command.CommandText = @"aspnet_Profile_GetProfiles";
  162. AddParameter (command, "ApplicationName", ApplicationName);
  163. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  164. AddParameter (command, "PageIndex", pageIndex);
  165. AddParameter (command, "PageSize", pageSize);
  166. AddParameter (command, "UserNameToMatch", usernameToMatch);
  167. AddParameter (command, "InactiveSinceDate", null);
  168. using (DbDataReader reader = command.ExecuteReader ()) {
  169. return BuildProfileInfoCollection (reader, out totalRecords);
  170. }
  171. }
  172. }
  173. public override ProfileInfoCollection GetAllInactiveProfiles (ProfileAuthenticationOption authenticationOption,
  174. DateTime userInactiveSinceDate,
  175. int pageIndex,
  176. int pageSize,
  177. out int totalRecords)
  178. {
  179. if (pageIndex < 0)
  180. throw new ArgumentException ("pageIndex is less than zero");
  181. if (pageSize < 1)
  182. throw new ArgumentException ("pageIndex is less than one");
  183. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  184. throw new ArgumentException ("pageIndex and pageSize are too large");
  185. using (DbConnection connection = CreateConnection ()) {
  186. DbCommand command = factory.CreateCommand ();
  187. command.Connection = connection;
  188. command.CommandType = CommandType.StoredProcedure;
  189. command.CommandText = @"aspnet_Profile_GetProfiles";
  190. AddParameter (command, "ApplicationName", ApplicationName);
  191. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  192. AddParameter (command, "PageIndex", pageIndex);
  193. AddParameter (command, "PageSize", pageSize);
  194. AddParameter (command, "UserNameToMatch", null);
  195. AddParameter (command, "InactiveSinceDate", null);
  196. using (DbDataReader reader = command.ExecuteReader ()) {
  197. return BuildProfileInfoCollection (reader, out totalRecords);
  198. }
  199. }
  200. }
  201. public override ProfileInfoCollection GetAllProfiles (ProfileAuthenticationOption authenticationOption,
  202. int pageIndex,
  203. int pageSize,
  204. out int totalRecords)
  205. {
  206. if (pageIndex < 0)
  207. throw new ArgumentException ("pageIndex is less than zero");
  208. if (pageSize < 1)
  209. throw new ArgumentException ("pageIndex is less than one");
  210. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  211. throw new ArgumentException ("pageIndex and pageSize are too large");
  212. using (DbConnection connection = CreateConnection ()) {
  213. DbCommand command = factory.CreateCommand ();
  214. command.Connection = connection;
  215. command.CommandType = CommandType.StoredProcedure;
  216. command.CommandText = @"aspnet_Profile_GetProfiles";
  217. AddParameter (command, "ApplicationName", ApplicationName);
  218. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  219. AddParameter (command, "PageIndex", pageIndex);
  220. AddParameter (command, "PageSize", pageSize);
  221. AddParameter (command, "UserNameToMatch", null);
  222. AddParameter (command, "InactiveSinceDate", null);
  223. using (DbDataReader reader = command.ExecuteReader ()) {
  224. return BuildProfileInfoCollection (reader, out totalRecords);
  225. }
  226. }
  227. }
  228. public override int GetNumberOfInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
  229. {
  230. using (DbConnection connection = CreateConnection ()) {
  231. DbCommand command = factory.CreateCommand ();
  232. command.Connection = connection;
  233. command.CommandType = CommandType.StoredProcedure;
  234. command.CommandText = @"aspnet_Profile_GetNumberOfInactiveProfiles";
  235. AddParameter (command, "ApplicationName", ApplicationName);
  236. AddParameter (command, "ProfileAuthOptions", authenticationOption);
  237. AddParameter (command, "InactiveSinceDate", userInactiveSinceDate);
  238. int returnValue = 0;
  239. using (DbDataReader reader = command.ExecuteReader ()) {
  240. if (reader.Read ())
  241. returnValue = reader.GetInt32 (0);
  242. }
  243. return returnValue;
  244. }
  245. }
  246. public override SettingsPropertyValueCollection GetPropertyValues (SettingsContext sc, SettingsPropertyCollection properties)
  247. {
  248. SettingsPropertyValueCollection settings = new SettingsPropertyValueCollection ();
  249. if (properties.Count == 0)
  250. return settings;
  251. foreach (SettingsProperty property in properties) {
  252. if (property.SerializeAs == SettingsSerializeAs.ProviderSpecific)
  253. if (property.PropertyType.IsPrimitive || property.PropertyType == typeof (String))
  254. property.SerializeAs = SettingsSerializeAs.String;
  255. else
  256. property.SerializeAs = SettingsSerializeAs.Xml;
  257. settings.Add (new SettingsPropertyValue (property));
  258. }
  259. string username = (string) sc ["UserName"];
  260. using (DbConnection connection = CreateConnection ()) {
  261. DbCommand command = factory.CreateCommand ();
  262. command.Connection = connection;
  263. command.CommandType = CommandType.StoredProcedure;
  264. command.CommandText = @"aspnet_Profile_GetProperties";
  265. AddParameter (command, "ApplicationName", ApplicationName);
  266. AddParameter (command, "UserName", username);
  267. AddParameter (command, "CurrentTimeUtc", DateTime.UtcNow);
  268. using (DbDataReader reader = command.ExecuteReader ()) {
  269. if (reader.Read ()) {
  270. string allnames = reader.GetString (0);
  271. string allvalues = reader.GetString (1);
  272. int binaryLen = (int) reader.GetBytes (2, 0, null, 0, 0);
  273. byte [] binaryvalues = new byte [binaryLen];
  274. reader.GetBytes (2, 0, binaryvalues, 0, binaryLen);
  275. DecodeProfileData (allnames, allvalues, binaryvalues, settings);
  276. }
  277. }
  278. }
  279. return settings;
  280. }
  281. public override void SetPropertyValues (SettingsContext sc, SettingsPropertyValueCollection properties)
  282. {
  283. string username = (string) sc ["UserName"];
  284. bool isAnonymous = !(bool) sc ["IsAuthenticated"];
  285. string names = String.Empty;
  286. string values = String.Empty;
  287. byte [] buf = null;
  288. EncodeProfileData (ref names, ref values, ref buf, properties, !isAnonymous);
  289. using (DbConnection connection = CreateConnection ()) {
  290. DbCommand command = factory.CreateCommand ();
  291. command.Connection = connection;
  292. command.CommandType = CommandType.StoredProcedure;
  293. command.CommandText = @"aspnet_Profile_SetProperties";
  294. AddParameter (command, "ApplicationName", ApplicationName);
  295. AddParameter (command, "PropertyNames", names);
  296. AddParameter (command, "PropertyValuesString", values);
  297. AddParameter (command, "PropertyValuesBinary", buf);
  298. AddParameter (command, "UserName", username);
  299. AddParameter (command, "IsUserAnonymous", isAnonymous);
  300. AddParameter (command, "CurrentTimeUtc", DateTime.UtcNow);
  301. // Return value
  302. AddParameter (command, null, ParameterDirection.ReturnValue, null);
  303. command.ExecuteNonQuery ();
  304. return;
  305. }
  306. }
  307. public override void Initialize (string name, NameValueCollection config)
  308. {
  309. if (config == null)
  310. throw new ArgumentNullException ("config");
  311. base.Initialize (name, config);
  312. applicationName = GetStringConfigValue (config, "applicationName", "/");
  313. string connectionStringName = config ["connectionStringName"];
  314. if (applicationName.Length > 256)
  315. throw new ProviderException ("The ApplicationName attribute must be 256 characters long or less.");
  316. if (connectionStringName == null || connectionStringName.Length == 0)
  317. throw new ProviderException ("The ConnectionStringName attribute must be present and non-zero length.");
  318. connectionString = WebConfigurationManager.ConnectionStrings [connectionStringName];
  319. factory = connectionString == null || String.IsNullOrEmpty (connectionString.ProviderName) ?
  320. System.Data.SqlClient.SqlClientFactory.Instance :
  321. ProvidersHelper.GetDbProviderFactory (connectionString.ProviderName);
  322. }
  323. public override string ApplicationName {
  324. get { return applicationName; }
  325. set { applicationName = value; }
  326. }
  327. DbConnection CreateConnection ()
  328. {
  329. if (!schemaIsOk && !(schemaIsOk = AspNetDBSchemaChecker.CheckMembershipSchemaVersion (factory, connectionString.ConnectionString, "profile", "1")))
  330. throw new ProviderException ("Incorrect ASP.NET DB Schema Version.");
  331. DbConnection connection = factory.CreateConnection ();
  332. connection.ConnectionString = connectionString.ConnectionString;
  333. connection.Open ();
  334. return connection;
  335. }
  336. DbParameter AddParameter (DbCommand command, string parameterName, object parameterValue)
  337. {
  338. return AddParameter (command, parameterName, ParameterDirection.Input, parameterValue);
  339. }
  340. DbParameter AddParameter (DbCommand command, string parameterName, ParameterDirection direction, object parameterValue)
  341. {
  342. DbParameter dbp = command.CreateParameter ();
  343. dbp.ParameterName = parameterName;
  344. dbp.Value = parameterValue;
  345. dbp.Direction = direction;
  346. command.Parameters.Add (dbp);
  347. return dbp;
  348. }
  349. void CheckParam (string pName, string p, int length)
  350. {
  351. if (p == null)
  352. throw new ArgumentNullException (pName);
  353. if (p.Length == 0 || p.Length > length || p.IndexOf (',') != -1)
  354. throw new ArgumentException (String.Concat ("invalid format for ", pName));
  355. }
  356. static int GetReturnValue (DbParameter returnValue)
  357. {
  358. object value = returnValue.Value;
  359. return value is int ? (int) value : -1;
  360. }
  361. ProfileInfo ReadProfileInfo (DbDataReader reader)
  362. {
  363. ProfileInfo pi = null;
  364. try {
  365. string username = reader.GetString (0);
  366. bool anonymous = reader.GetBoolean (1);
  367. DateTime lastUpdate = reader.GetDateTime (2);
  368. DateTime lastActivity = reader.GetDateTime (3);
  369. int size = reader.GetInt32 (4);
  370. pi = new ProfileInfo (username, anonymous, lastActivity, lastUpdate, size);
  371. }
  372. catch {
  373. }
  374. return pi;
  375. }
  376. ProfileInfoCollection BuildProfileInfoCollection (DbDataReader reader, out int totalRecords)
  377. {
  378. ProfileInfoCollection pic = new ProfileInfoCollection ();
  379. while (reader.Read ()) {
  380. ProfileInfo pi = ReadProfileInfo (reader);
  381. if (pi != null)
  382. pic.Add (pi);
  383. }
  384. totalRecords = 0;
  385. if (reader.NextResult ()) {
  386. if (reader.Read ())
  387. totalRecords = reader.GetInt32 (0);
  388. }
  389. return pic;
  390. }
  391. string GetStringConfigValue (NameValueCollection config, string name, string def)
  392. {
  393. string retVal = def;
  394. string val = config [name];
  395. if (val != null)
  396. retVal = val;
  397. return retVal;
  398. }
  399. // Helper methods
  400. void DecodeProfileData (string allnames, string values, byte [] buf, SettingsPropertyValueCollection properties)
  401. {
  402. if (allnames == null || values == null || buf == null || properties == null)
  403. return;
  404. string [] names = allnames.Split (':');
  405. for (int i = 0; i < names.Length; i += 4) {
  406. string name = names [i];
  407. SettingsPropertyValue pp = properties [name];
  408. if (pp == null)
  409. continue;
  410. int pos = Int32.Parse (names [i + 2], Helpers.InvariantCulture);
  411. int len = Int32.Parse (names [i + 3], Helpers.InvariantCulture);
  412. if (len == -1 && !pp.Property.PropertyType.IsValueType) {
  413. pp.PropertyValue = null;
  414. pp.IsDirty = false;
  415. pp.Deserialized = true;
  416. }
  417. else if (names [i + 1] == "S" && pos >= 0 && len > 0 && values.Length >= pos + len) {
  418. pp.SerializedValue = values.Substring (pos, len);
  419. }
  420. else if (names [i + 1] == "B" && pos >= 0 && len > 0 && buf.Length >= pos + len) {
  421. byte [] buf2 = new byte [len];
  422. Buffer.BlockCopy (buf, pos, buf2, 0, len);
  423. pp.SerializedValue = buf2;
  424. }
  425. }
  426. }
  427. void EncodeProfileData (ref string allNames, ref string allValues, ref byte [] buf, SettingsPropertyValueCollection properties, bool userIsAuthenticated)
  428. {
  429. StringBuilder names = new StringBuilder ();
  430. StringBuilder values = new StringBuilder ();
  431. MemoryStream stream = new MemoryStream ();
  432. try {
  433. foreach (SettingsPropertyValue pp in properties) {
  434. if (!userIsAuthenticated && !(bool) pp.Property.Attributes ["AllowAnonymous"])
  435. continue;
  436. if (!pp.IsDirty && pp.UsingDefaultValue)
  437. continue;
  438. int len = 0, pos = 0;
  439. string propValue = null;
  440. if (pp.Deserialized && pp.PropertyValue == null)
  441. len = -1;
  442. else {
  443. object sVal = pp.SerializedValue;
  444. if (sVal == null)
  445. len = -1;
  446. else if (sVal is string) {
  447. propValue = (string) sVal;
  448. len = propValue.Length;
  449. pos = values.Length;
  450. }
  451. else {
  452. byte [] b2 = (byte []) sVal;
  453. pos = (int) stream.Position;
  454. stream.Write (b2, 0, b2.Length);
  455. stream.Position = pos + b2.Length;
  456. len = b2.Length;
  457. }
  458. }
  459. names.Append (pp.Name + ":" + ((propValue != null) ? "S" : "B") + ":" + pos.ToString (Helpers.InvariantCulture) + ":" + len.ToString (Helpers.InvariantCulture) + ":");
  460. if (propValue != null)
  461. values.Append (propValue);
  462. }
  463. buf = stream.ToArray ();
  464. }
  465. finally {
  466. if (stream != null)
  467. stream.Close ();
  468. }
  469. allNames = names.ToString ();
  470. allValues = values.ToString ();
  471. }
  472. }
  473. }