1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
|
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12
// The copyright was assigned and transferred under the terms of
// the MySQL Contributor License Agreement (CLA)
using System;
using System.Web.Profile;
using System.Configuration;
using System.Collections.Specialized;
using System.Web.Hosting;
using MySql.Data.MySqlClient;
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Globalization;
using System.Web.Security;
using MySql.Web.Common;
using MySql.Web.Properties;
using MySql.Web.General;
namespace MySql.Web.Profile
{
/// <summary>
///
/// </summary>
public class MySQLProfileProvider : ProfileProvider
{
private string connectionString;
private Application app;
#region Abstract Members
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception>
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "MySQLProfileProvider";
if (string.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "MySQL Profile provider");
}
base.Initialize(name, config);
try
{
string applicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);
connectionString = "";
ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[
config["connectionStringName"]];
if (ConnectionStringSettings != null)
connectionString = ConnectionStringSettings.ConnectionString.Trim();
if (String.IsNullOrEmpty(connectionString)) return;
// make sure our schema is up to date
SchemaManager.CheckSchema(connectionString, config);
app = new Application(applicationName, base.Description);
}
catch (Exception ex)
{
throw new ProviderException(Resources.ErrorInitProfileProvider, ex);
}
}
/// <summary>
/// When overridden in a derived class, deletes all user-profile data
/// for profiles in which the last activity date occurred before the
/// specified date.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/>
/// values, specifying whether anonymous, authenticated, or both
/// types of profiles are deleted.</param>
/// <param name="userInactiveSinceDate">A <see cref="T:System.DateTime"/>
/// that identifies which user profiles are considered inactive. If the
/// <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"/>
/// value of a user profile occurs on or before this date and time, the
/// profile is considered inactive.</param>
/// <returns>
/// The number of profiles deleted from the data source.
/// </returns>
public override int DeleteInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
using (MySqlConnection c = new MySqlConnection(connectionString))
{
c.Open();
MySqlCommand queryCmd = new MySqlCommand(
@"SELECT * FROM my_aspnet_Users
WHERE applicationId=@appId AND
lastActivityDate < @lastActivityDate",
c);
queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c));
queryCmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate);
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
queryCmd.CommandText += " AND isAnonymous = 1";
else if (authenticationOption == ProfileAuthenticationOption.Authenticated)
queryCmd.CommandText += " AND isAnonymous = 0";
MySqlCommand deleteCmd = new MySqlCommand(
"DELETE FROM my_aspnet_Profiles WHERE userId = @userId", c);
deleteCmd.Parameters.Add("@userId", MySqlDbType.UInt64);
List<ulong> uidList = new List<ulong>();
using (MySqlDataReader reader = queryCmd.ExecuteReader())
{
while (reader.Read())
uidList.Add(reader.GetUInt64("userId"));
}
int count = 0;
foreach (ulong uid in uidList)
{
deleteCmd.Parameters[0].Value = uid;
count += deleteCmd.ExecuteNonQuery();
}
return count;
}
}
/// <summary>
/// When overridden in a derived class, deletes profile properties
/// and information for profiles that match the supplied list of user names.
/// </summary>
/// <param name="usernames">A string array of user names for
/// profiles to be deleted.</param>
/// <returns>
/// The number of profiles deleted from the data source.
/// </returns>
public override int DeleteProfiles(string[] usernames)
{
using (MySqlConnection c = new MySqlConnection(connectionString))
{
c.Open();
MySqlCommand queryCmd = new MySqlCommand(
@"SELECT * FROM my_aspnet_Users
WHERE applicationId=@appId AND name = @name", c);
queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c));
queryCmd.Parameters.Add("@name", MySqlDbType.VarChar);
MySqlCommand deleteCmd = new MySqlCommand(
"DELETE FROM my_aspnet_Profiles WHERE userId = @userId", c);
deleteCmd.Parameters.Add("@userId", MySqlDbType.UInt64);
int count = 0;
foreach (string name in usernames)
{
queryCmd.Parameters[1].Value = name;
ulong uid = (ulong)queryCmd.ExecuteScalar();
deleteCmd.Parameters[0].Value = uid;
count += deleteCmd.ExecuteNonQuery();
}
return count;
}
}
/// <summary>
/// When overridden in a derived class, deletes profile properties
/// and information for the supplied list of profiles.
/// </summary>
/// <param name="profiles">A
/// <see cref="T:System.Web.Profile.ProfileInfoCollection"/> of
/// information about profiles that are to be deleted.</param>
/// <returns>
/// The number of profiles deleted from the data source.
/// </returns>
public override int DeleteProfiles(ProfileInfoCollection profiles)
{
string[] s = new string[profiles.Count];
int i = 0;
foreach (ProfileInfo p in profiles)
s[i++] = p.UserName;
return DeleteProfiles(s);
}
/// <summary>
/// When overridden in a derived class, retrieves profile information
/// for profiles in which the last activity date occurred on or before
/// the specified date and the user name matches the specified user name.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/> values,
/// specifying whether anonymous, authenticated, or both types of profiles
/// are returned.</param>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="userInactiveSinceDate">A <see cref="T:System.DateTime"/>
/// that identifies which user profiles are considered inactive. If the
/// <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"/> value
/// of a user profile occurs on or before this date and time, the profile
/// is considered inactive.</param>
/// <param name="pageIndex">The index of the page of results to return.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">When this method returns, contains the total
/// number of profiles.</param>
/// <returns>
/// A <see cref="T:System.Web.Profile.ProfileInfoCollection"/> containing
/// user profile information for inactive profiles where the user name
/// matches the supplied <paramref name="usernameToMatch"/> parameter.
/// </returns>
public override ProfileInfoCollection FindInactiveProfilesByUserName(
ProfileAuthenticationOption authenticationOption,
string usernameToMatch, DateTime userInactiveSinceDate,
int pageIndex, int pageSize, out int totalRecords)
{
return GetProfiles(authenticationOption, usernameToMatch,
userInactiveSinceDate, pageIndex, pageSize, out totalRecords);
}
/// <summary>
/// When overridden in a derived class, retrieves profile information
/// for profiles in which the user name matches the specified user names.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/> values,
/// specifying whether anonymous, authenticated, or both types of profiles
/// are returned.</param>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">When this method returns, contains the total
/// number of profiles.</param>
/// <returns>
/// A <see cref="T:System.Web.Profile.ProfileInfoCollection"/> containing
/// user-profile information for profiles where the user name matches the
/// supplied <paramref name="usernameToMatch"/> parameter.
/// </returns>
public override ProfileInfoCollection FindProfilesByUserName(
ProfileAuthenticationOption authenticationOption,
string usernameToMatch, int pageIndex, int pageSize,
out int totalRecords)
{
return GetProfiles(authenticationOption, usernameToMatch,
DateTime.MinValue, pageIndex, pageSize, out totalRecords);
}
/// <summary>
/// When overridden in a derived class, retrieves user-profile data
/// from the data source for profiles in which the last activity date
/// occurred on or before the specified date.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/> values,
/// specifying whether anonymous, authenticated, or both types of profiles
/// are returned.</param>
/// <param name="userInactiveSinceDate">A <see cref="T:System.DateTime"/>
/// that identifies which user profiles are considered inactive. If the
/// <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"/> of
/// a user profile occurs on or before this date and time, the profile is
/// considered inactive.</param>
/// <param name="pageIndex">The index of the page of results to return.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">When this method returns, contains the
/// total number of profiles.</param>
/// <returns>
/// A <see cref="T:System.Web.Profile.ProfileInfoCollection"/> containing user-profile information about the inactive profiles.
/// </returns>
public override ProfileInfoCollection GetAllInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate, int pageIndex, int pageSize,
out int totalRecords)
{
return GetProfiles(authenticationOption, null,
userInactiveSinceDate, pageIndex, pageSize, out totalRecords);
}
/// <summary>
/// When overridden in a derived class, retrieves user profile data for
/// all profiles in the data source.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/> values,
/// specifying whether anonymous, authenticated, or both types of profiles
/// are returned.</param>
/// <param name="pageIndex">The index of the page of results to return.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">When this method returns, contains the
/// total number of profiles.</param>
/// <returns>
/// A <see cref="T:System.Web.Profile.ProfileInfoCollection"/> containing
/// user-profile information for all profiles in the data source.
/// </returns>
public override ProfileInfoCollection GetAllProfiles(
ProfileAuthenticationOption authenticationOption, int pageIndex,
int pageSize, out int totalRecords)
{
return GetProfiles(authenticationOption, null,
DateTime.MinValue, pageIndex, pageSize, out totalRecords);
}
/// <summary>
/// When overridden in a derived class, returns the number of profiles
/// in which the last activity date occurred on or before the specified
/// date.
/// </summary>
/// <param name="authenticationOption">One of the
/// <see cref="T:System.Web.Profile.ProfileAuthenticationOption"/> values,
/// specifying whether anonymous, authenticated, or both types of profiles
/// are returned.</param>
/// <param name="userInactiveSinceDate">A <see cref="T:System.DateTime"/>
/// that identifies which user profiles are considered inactive. If the
/// <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"/> of
/// a user profile occurs on or before this date and time, the profile
/// is considered inactive.</param>
/// <returns>
/// The number of profiles in which the last activity date occurred on
/// or before the specified date.
/// </returns>
public override int GetNumberOfInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
using (MySqlConnection c = new MySqlConnection(connectionString))
{
c.Open();
MySqlCommand queryCmd = new MySqlCommand(
@"SELECT COUNT(*) FROM my_aspnet_Users
WHERE applicationId = @appId AND
lastActivityDate < @lastActivityDate",
c);
queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c));
queryCmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate);
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
queryCmd.CommandText += " AND isAnonymous = 1";
else if (authenticationOption == ProfileAuthenticationOption.Authenticated)
queryCmd.CommandText += " AND isAnonymous = 0";
return (int)queryCmd.ExecuteScalar();
}
}
/// <summary>
/// Gets or sets the name of the currently running application.
/// </summary>
/// <value></value>
/// <returns>A <see cref="T:System.String"/> that contains the application's shortened name, which does not contain a full path or extension, for example, SimpleAppSettings.</returns>
public override string ApplicationName
{
get { return app.Name; }
set { app.Name = value; }
}
/// <summary>
/// Returns the collection of settings property values for the specified application instance and settings property group.
/// </summary>
/// <param name="context">A <see cref="T:System.Configuration.SettingsContext"/> describing the current application use.</param>
/// <param name="collection">A <see cref="T:System.Configuration.SettingsPropertyCollection"/> containing the settings property group whose values are to be retrieved.</param>
/// <returns>
/// A <see cref="T:System.Configuration.SettingsPropertyValueCollection"/> containing the values for the specified settings property group.
/// </returns>
public override SettingsPropertyValueCollection GetPropertyValues(
SettingsContext context, SettingsPropertyCollection collection)
{
SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();
if (collection.Count < 1) return values;
string username = (string)context["UserName"];
foreach (SettingsProperty property in collection)
{
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
property.SerializeAs = SettingsSerializeAs.String;
else
property.SerializeAs = SettingsSerializeAs.Xml;
values.Add(new SettingsPropertyValue(property));
}
if (String.IsNullOrEmpty(username))
return values;
// retrieve encoded profile data from the database
try
{
using (MySqlConnection c = new MySqlConnection(connectionString))
{
c.Open();
MySqlCommand cmd = new MySqlCommand(
@"SELECT * FROM my_aspnet_Profiles p
JOIN my_aspnet_Users u ON u.id = p.userId
WHERE u.applicationId = @appId AND u.name = @name", c);
cmd.Parameters.AddWithValue("@appId", app.FetchId(c));
cmd.Parameters.AddWithValue("@name", username);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
DecodeProfileData(dt.Rows[0], values);
return values;
}
}
catch (Exception ex)
{
throw new ProviderException(Resources.UnableToRetrieveProfileData, ex);
}
}
/// <summary>
/// Sets the values of the specified group of property settings.
/// </summary>
/// <param name="context">A <see cref="T:System.Configuration.SettingsContext"/> describing the current application usage.</param>
/// <param name="collection">A <see cref="T:System.Configuration.SettingsPropertyValueCollection"/> representing the group of property settings to set.</param>
public override void SetPropertyValues(
SettingsContext context, SettingsPropertyValueCollection collection)
{
bool isAuthenticated = (bool)context["IsAuthenticated"];
string username = (string)context["UserName"];
if (String.IsNullOrEmpty(username)) return;
if (collection.Count < 1) return;
string index = String.Empty;
string stringData = String.Empty;
byte[] binaryData = null;
int count = EncodeProfileData(collection, isAuthenticated, ref index, ref stringData, ref binaryData);
if (count < 1) return;
MySqlTransaction txn = null;
// save the encoded profile data to the database
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
connection.Open();
txn = connection.BeginTransaction();
// either create a new user or fetch the existing user id
int userId = SchemaManager.CreateOrFetchUserId(connection, username,
app.EnsureId(connection), isAuthenticated);
MySqlCommand cmd = new MySqlCommand(
@"INSERT INTO my_aspnet_Profiles
VALUES (@userId, @index, @stringData, @binaryData, NULL) ON DUPLICATE KEY UPDATE
valueindex=VALUES(valueindex), stringdata=VALUES(stringdata),
binarydata=VALUES(binarydata)", connection);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@userId", userId);
cmd.Parameters.AddWithValue("@index", index);
cmd.Parameters.AddWithValue("@stringData", stringData);
cmd.Parameters.AddWithValue("@binaryData", binaryData);
count = cmd.ExecuteNonQuery();
if (count == 0)
throw new Exception(Resources.ProfileUpdateFailed);
txn.Commit();
}
catch (Exception ex)
{
if (txn != null)
txn.Rollback();
throw new ProviderException(Resources.ProfileUpdateFailed, ex);
}
}
}
#endregion
internal static void DeleteUserData(MySqlConnection connection, int userId)
{
MySqlCommand cmd = new MySqlCommand(
"DELETE FROM my_aspnet_Profiles WHERE userId=@userId", connection);
cmd.Parameters.AddWithValue("@userId", userId);
cmd.ExecuteNonQuery();
}
#region Private Methods
private void DecodeProfileData(DataRow profileRow, SettingsPropertyValueCollection values)
{
string indexData = (string)profileRow["valueindex"];
string stringData = (string)profileRow["stringData"];
byte[] binaryData = (byte[])profileRow["binaryData"];
if (indexData == null) return;
string[] indexes = indexData.Split(':');
foreach (string index in indexes)
{
string[] parts = index.Split('/');
SettingsPropertyValue value = values[parts[0]];
if (value == null) continue;
int pos = Int32.Parse(parts[2], CultureInfo.InvariantCulture);
int len = Int32.Parse(parts[3], CultureInfo.InvariantCulture);
if (len == -1)
{
value.PropertyValue = null;
value.IsDirty = false;
value.Deserialized = true;
}
else if (parts[1].Equals("0"))
value.SerializedValue = stringData.Substring(pos, len);
else
{
byte[] buf = new byte[len];
Buffer.BlockCopy(binaryData, pos, buf, 0, len);
value.SerializedValue = buf;
}
}
}
private int EncodeProfileData(SettingsPropertyValueCollection collection, bool isAuthenticated,
ref string index, ref string stringData, ref byte[] binaryData)
{
bool itemsToSave = false;
// first we need to determine if there are any items that need saving
// this is an optimization
foreach (SettingsPropertyValue value in collection)
{
if (!value.IsDirty) continue;
if (value.Property.Attributes["AllowAnonymous"].Equals(false) &&
!isAuthenticated) continue;
itemsToSave = true;
break;
}
if (!itemsToSave) return 0;
StringBuilder indexBuilder = new StringBuilder();
StringBuilder stringDataBuilder = new StringBuilder();
MemoryStream binaryBuilder = new MemoryStream();
int count = 0;
// ok, we have some values that need to be saved so we go back through
foreach (SettingsPropertyValue value in collection)
{
// if the value has not been written to and is still using the default value
// no need to save it
if (value.UsingDefaultValue && !value.IsDirty) continue;
// we don't save properties that require the user to be authenticated when the
// current user is not authenticated.
if (value.Property.Attributes["AllowAnonymous"].Equals(false) &&
!isAuthenticated) continue;
count++;
object propValue = value.SerializedValue;
if ((value.Deserialized && value.PropertyValue == null) ||
value.SerializedValue == null)
indexBuilder.AppendFormat("{0}//0/-1:", value.Name);
else if (propValue is string)
{
indexBuilder.AppendFormat("{0}/0/{1}/{2}:", value.Name,
stringDataBuilder.Length, (propValue as string).Length);
stringDataBuilder.Append(propValue);
}
else
{
byte[] binaryValue = (byte[])propValue;
indexBuilder.AppendFormat("{0}/1/{1}/{2}:", value.Name,
binaryBuilder.Position, binaryValue.Length);
binaryBuilder.Write(binaryValue, 0, binaryValue.Length);
}
}
index = indexBuilder.ToString();
stringData = stringDataBuilder.ToString();
binaryData = binaryBuilder.ToArray();
return count;
}
private ProfileInfoCollection GetProfiles(
ProfileAuthenticationOption authenticationOption,
string usernameToMatch, DateTime userInactiveSinceDate,
int pageIndex, int pageSize, out int totalRecords)
{
List<string> whereClauses = new List<string>();
using (MySqlConnection c = new MySqlConnection(connectionString))
{
c.Open();
MySqlCommand cmd = new MySqlCommand(
@"SELECT p.*, u.name, u.isAnonymous, u.lastActivityDate,
LENGTH(p.stringdata) + LENGTH(p.binarydata) AS profilesize
FROM my_aspnet_Profiles p
JOIN my_aspnet_Users u ON u.id = p.userId
WHERE u.applicationId = @appId", c);
cmd.Parameters.AddWithValue("@appId", app.FetchId(c));
if (usernameToMatch != null)
{
cmd.CommandText += " AND u.name LIKE @userName";
cmd.Parameters.AddWithValue("@userName", usernameToMatch);
}
if (userInactiveSinceDate != DateTime.MinValue)
{
cmd.CommandText += " AND u.lastActivityDate < @lastActivityDate";
cmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate);
}
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
cmd.CommandText += " AND u.isAnonymous = 1";
else if (authenticationOption == ProfileAuthenticationOption.Authenticated)
cmd.CommandText += " AND u.isAnonymous = 0";
cmd.CommandText += String.Format(" LIMIT {0},{1}", pageIndex * pageSize, pageSize);
ProfileInfoCollection pic = new ProfileInfoCollection();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ProfileInfo pi = new ProfileInfo(
reader.GetString("name"),
reader.GetBoolean("isAnonymous"),
reader.GetDateTime("lastActivityDate"),
reader.GetDateTime("lastUpdatedDate"),
reader.GetInt32("profilesize"));
pic.Add(pi);
}
}
cmd.CommandText = "SELECT FOUND_ROWS()";
totalRecords = Convert.ToInt32(cmd.ExecuteScalar());
return pic;
}
}
private static string GetConfigValue(string configValue, string defaultValue)
{
if (string.IsNullOrEmpty(configValue))
{
return defaultValue;
}
return configValue;
}
#endregion
}
}
|