SqlProfileProvider.cs 19 KB

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