ASP.NET Security Provider实现(二)Entity、Services

 接“ASP.NET Security Provider实现(一)

为了实现MembershipProvider、RoleProvider、ProfileProvider,需要定义存储相关的实体类和业务逻辑相关的存储类。由于使用了MVCQuick.Framework的存储和IoC容器,实现了业务逻辑与持久化分离。 

实体

继承MVCQuick.Framework.EntityBase

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

namespace MVCQuick.Framework.Security
{
///<summary>
/// 用户
///</summary>
[Serializable]
public class User : EntityBase
{
///<summary>
/// 登录名
///</summary>
public virtual string Username { get; set; }

///<summary>
/// 电子邮件地址
///</summary>
public virtual string Email { get; set; }

///<summary>
/// 密码
///</summary>
public virtual string Password { get; set; }

///<summary>
/// 密码格式
///</summary>
public virtual System.Web.Security.MembershipPasswordFormat PasswordFormat { get; set; }

///<summary>
/// 辅助密码验证
///</summary>
public virtual string PasswordSalt { get; set; }

///<summary>
/// 密码提示问题
///</summary>
public virtual string PasswordQuestion { get; set; }

///<summary>
/// 密码提示答案
///</summary>
public virtual string PasswordAnswer { get; set; }

///<summary>
/// 是否是匿名用户
///</summary>
public virtual bool IsAnonymous { get; set; }

///<summary>
/// 是否可以进行身份验证
///</summary>
public virtual bool IsApproved { get; set; }

///<summary>
/// 是否因被锁定而无法进行验证
///</summary>
public virtual bool IsLockedOut { get; set; }

///<summary>
/// 创建日期和时间
///</summary>
public virtual DateTime CreateDate { get; set; }

///<summary>
/// 最后一次进行身份验证或访问应用程序的日期和时间
///</summary>
public virtual DateTime LastActivityDate { get; set; }

///<summary>
/// 最后一次进行身份验证的日期和时间
///</summary>
public virtual DateTime LastLoginDate { get; set; }

///<summary>
/// 最后一次更新密码的日期和时间
///</summary>
public virtual DateTime LastPasswordChangedDate { get; set; }

///<summary>
/// 最后一次锁定的日期和时间
///</summary>
public virtual DateTime LastLockoutDate { get; set; }

///<summary>
/// 密码重试次数
///</summary>
public virtual int FailedPasswordAttemptCount { get; set; }

///<summary>
/// 密码失败尝试窗口打开的日期和时间
///</summary>
public virtual DateTime FailedPasswordAttemptWindowStart { get; set; }

///<summary>
/// 密码提示答案重试次数
///</summary>
public virtual int FailedPasswordAnswerAttemptCount { get; set; }

///<summary>
/// 密码提示答案失败尝试窗口打开的日期和时间
///</summary>
public virtual DateTime FailedPasswordAnswerAttemptWindowStart { get; set; }

///<summary>
/// 其它自定义信息
///</summary>
public virtual string Comment { get; set; }

///<summary>
/// 应用程序
///</summary>
public virtual Application Application { get; set; }

///<summary>
///
///</summary>
public virtual IEnumerable<Role> Roles { get; set; }

///<summary>
///
///</summary>
public User()
{
Roles = new List<Role>();
}

}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCQuick.Framework.Security
{
///<summary>
/// 角色
///</summary>
[Serializable]
public class Role : EntityBase
{
///<summary>
/// 名称
///</summary>
public virtual string Name { get; set; }

///<summary>
/// 说明
///</summary>
public virtual string Description { get; set; }

///<summary>
/// 应用程序
///</summary>
public virtual Application Application { get; set; }

///<summary>
///
///</summary>
public virtual IEnumerable<User> Users { get; set; }

///<summary>
///
///</summary>
public Role()
{
Users = new List<User>();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVCQuick.Framework.Security
{
///<summary>
/// 用户配置文件
///</summary>
public class Profile : EntityBase
{
///<summary>
/// 用户Id
///</summary>
public virtual int UserId { get; set; }

///<summary>
/// 属性名称
///</summary>
public virtual string PropertyNames { get; set; }

///<summary>
/// 字符串值
///</summary>
public virtual string PropertyValuesString { get; set; }

/// 二进制值
///</summary>
public virtual byte[] PropertyValuesBinary { get; set; }

///<summary>
/// 最后一次更新时间
///</summary>
public virtual DateTime LastUpdatedDate { get; set; }

}
}

 

服务

用户服务类

MVCQuick.Framework.Security.UserService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCQuick.Framework.Repository;

namespace MVCQuick.Framework.Security
{
public class UserService
{
IRepository repository;

public UserService(IRepository repository)
{
this.repository = repository;
}

public void CreateUser(User user)
{
repository.Save<User>(user);
}

public void UpdateUser(User user)
{
repository.Update<User>(user);
}

public void DeleteUser(User user)
{
repository.Delete<User>(user);
}

public User GetUser(int userID)
{
return repository.Get<int, User>(userID);
}

public User GetUserByName(string applicationName, string username)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

return user;
}


public User GetUserByName(string applicationName, string username, bool updateLastActivity, DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
if (updateLastActivity)
{
user.LastActivityDate = currentTimeUtc;

UpdateUser(user);
}

return user;
}

return null;

}

public IList<User> GetUsersByEmail(string applicationName, string email)
{

Application application =
new ApplicationService(repository).GetApplication(applicationName);

return repository.Find<User>("Application", application, "Email", email);

}

public int UpdatePassword(string applicationName, string username, string newPassword, string passwordSalt,
System.Web.Security.MembershipPasswordFormat passwordFormat, DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
user.Password = newPassword;
user.PasswordSalt = passwordSalt;
user.PasswordFormat = passwordFormat;
user.LastPasswordChangedDate = currentTimeUtc;

UpdateUser(user);

return 0;
}
else
{
return 1;
}

}

public int ResetPassword(string applicationName, string username, string newPassword,
int maxInvalidPasswordAttempts, int passwordAttemptWindow, string passwordSalt,
System.Web.Security.MembershipPasswordFormat passwordFormat, string passwordAnswer,
DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
if (!user.IsLockedOut)
{
if (passwordAnswer == null || passwordAnswer.ToLower().Equals(user.PasswordAnswer))
{
user.Password = newPassword;
user.PasswordFormat = passwordFormat;
user.PasswordSalt = passwordSalt;
user.LastPasswordChangedDate = currentTimeUtc;
user.FailedPasswordAnswerAttemptCount = 0;
user.FailedPasswordAnswerAttemptWindowStart = new DateTime(1754, 1, 1);

UpdateUser(user);

return 0;
}
else
{
if (currentTimeUtc > user.FailedPasswordAnswerAttemptWindowStart.AddMinutes(passwordAttemptWindow))
{
user.FailedPasswordAnswerAttemptCount = 1;
user.FailedPasswordAnswerAttemptWindowStart = currentTimeUtc;
}
else
{
user.FailedPasswordAnswerAttemptCount++;
user.FailedPasswordAnswerAttemptWindowStart = currentTimeUtc;
}

if (user.FailedPasswordAnswerAttemptCount > maxInvalidPasswordAttempts)
{
user.IsLockedOut = true;
user.LastLockoutDate = currentTimeUtc;
}

UpdateUser(user);

return 3;
}
}
else
{
return 99;
}
}
else
{
return 1;
}
}

public int ChangePasswordQuestionAndAnswer(string applicationName, string username, string newPasswordQuestion,
string newPasswordAnswer)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
user.PasswordQuestion = newPasswordQuestion;
user.PasswordAnswer = newPasswordAnswer;

UpdateUser(user);

return 0;
}
else
{
return 1;
}

}

public int DeleteUser(string applicationName, string username, bool deleteAllRelatedData)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
DeleteUser(user);

return 0;
}
else
{
return 1;
}
}


public IList<User> FindUsersByEmail(string applicationName, string emailToMatch,
int pageIndex, int pageSize, out int totalRecords)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application, "Email", "%"+emailToMatch+"%");

totalRecords = users.Count;

var result = users.Skip(pageIndex * pageSize).Take(pageSize);

return (IList<User>)result;
}

public IList<User> FindUsersByName(string applicationName, string usernameToMatch,
int pageIndex, int pageSize, out int totalRecords)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application, "Username", "%" + usernameToMatch + "%");

totalRecords = users.Count;

var result = users.Skip(pageIndex * pageSize).Take(pageSize);

return (IList<User>)result;
}


public IList<User> GetAllUsers(string applicationName,
int pageIndex, int pageSize, out int totalRecords)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application);

totalRecords = users.Count;

var result = users.Skip(pageIndex * pageSize).Take(pageSize);

return (IList<User>)result;
}


public long GetNumberOfUsersOnline(string applicationName, int minutesSinceLastInActive, DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application);

long count = 0;

DateTime activeDate = currentTimeUtc.AddMinutes(-minutesSinceLastInActive);

foreach (var user in users)
{
if (user.LastActivityDate > activeDate) count++;

}

return count;
}

public User GetUserByUserID(int userID, bool updateLastActivity, DateTime currentTimeUtc)
{
User user = repository.Get<int, User>(userID);

if (user != null)
{
if (updateLastActivity)
{
user.LastActivityDate = currentTimeUtc;

UpdateUser(user);
}

return user;
}
else
{
return null;
}
}



public int UnlockUser(string applicationName, string username)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
user.LastLockoutDate = new DateTime(1754, 1, 1);
user.FailedPasswordAttemptCount = 0;
user.FailedPasswordAttemptWindowStart = new DateTime(1754, 1, 1);
user.FailedPasswordAnswerAttemptCount = 0;
user.FailedPasswordAnswerAttemptWindowStart = new DateTime(1754, 1, 1);

UpdateUser(user);

return 0;
}
else
{
return 1;
}
}

public int UpdateUser(string applicationName, string username, string email, string comment, bool isApproved,
DateTime lastLoginDate, DateTime lastActivityDate, bool uniqueEmail)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
if (uniqueEmail)
{
IList<User> users2 = repository.Find<User>("Application", application, "Email", email);

if (users2.Count > 1)
{
return 7;
}

if (users2.Count == 1 && ((User)users2[0]).Id != user.Id)
{
return 7;
}
}

user.Email = email;
user.IsApproved = isApproved;
user.LastActivityDate = lastActivityDate;
user.LastLoginDate = lastLoginDate;
user.Comment = comment;

UpdateUser(user);
return 0;
}
else
{
return 1;
}
}

public int UpdateUserInfo(string applicationName, string username, bool isPasswordCorrect, int passwordAttemptWindow,
int maxInvalidPasswordAttempts, bool updateLastLoginActivityDate, DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
if (!user.IsLockedOut)
{
if (!isPasswordCorrect)
{
if (currentTimeUtc > user.FailedPasswordAttemptWindowStart.AddMinutes(passwordAttemptWindow))
{
user.FailedPasswordAttemptCount = 1;
user.FailedPasswordAttemptWindowStart = currentTimeUtc;
}
else
{
user.FailedPasswordAttemptCount++;
user.FailedPasswordAttemptWindowStart = currentTimeUtc;
}

if (user.FailedPasswordAttemptCount > maxInvalidPasswordAttempts)
{
user.IsLockedOut = true;
user.LastLockoutDate = currentTimeUtc;
}

UpdateUser(user);

return 2;
}
else
{
user.LastLockoutDate = new DateTime(1754, 1, 1);
user.FailedPasswordAttemptCount = 0;
user.FailedPasswordAttemptWindowStart = new DateTime(1754, 1, 1);
user.FailedPasswordAnswerAttemptCount = 0;
user.FailedPasswordAnswerAttemptWindowStart = new DateTime(1754, 1, 1);

if (updateLastLoginActivityDate)
{
user.LastActivityDate = DateTime.UtcNow;
user.LastLoginDate = DateTime.UtcNow;
}

UpdateUser(user);

return 0;
}
}
else
{
return 99;
}
}
else
{
return 1;
}
}


public string GetPassword(string applicationName, string username, string passwordAnswer,
bool requiresQuestionAndAnswer, int maxInvalidPasswordAttempts, int passwordAttemptWindow,
out System.Web.Security.MembershipPasswordFormat passwordFormat, out int status,
DateTime currentTimeUtc)
{

Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
if (!user.IsLockedOut)
{
if (requiresQuestionAndAnswer)
{
if (passwordAnswer == null || (!passwordAnswer.ToLower().Equals(user.PasswordAnswer)))
{
if (currentTimeUtc > user.FailedPasswordAnswerAttemptWindowStart.AddMinutes(passwordAttemptWindow))
{
user.FailedPasswordAnswerAttemptCount = 1;
user.FailedPasswordAnswerAttemptWindowStart = currentTimeUtc;
}
else
{
user.FailedPasswordAnswerAttemptCount++;
user.FailedPasswordAnswerAttemptWindowStart = currentTimeUtc;
}

if (user.FailedPasswordAnswerAttemptCount > maxInvalidPasswordAttempts)
{
user.IsLockedOut = true;
user.LastLockoutDate = currentTimeUtc;
}

status = 3;

UpdateUser(user);
}
else
{
user.FailedPasswordAnswerAttemptCount = 0;
user.FailedPasswordAnswerAttemptWindowStart = new DateTime(1754, 1, 1);

UpdateUser(user);

status = 0;
passwordFormat = user.PasswordFormat;
return user.Password;
}
}
else
{
status = 0;
passwordFormat = user.PasswordFormat;
return user.Password;
}
}
else
{
status = 99;
}
}
else
{
status = 1;
}

passwordFormat = System.Web.Security.MembershipPasswordFormat.Clear;

return null;
}
}
}

角色服务类

MVCQuick.Framework.Security.RoleService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCQuick.Framework.Repository;

namespace MVCQuick.Framework.Security
{
public class RoleService
{
IRepository repository;

public RoleService(IRepository repository)
{
this.repository = repository;
}


public int CreateRole(string applicationName, string roleName)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

if (RoleExists(applicationName, roleName))
{
return 5;
}

Role role = new Role();
role.Name = roleName;
role.Application = application;

repository.Save<Role>(role);

return 0;
}


public int DeleteRole(string applicationName, string roleName, bool deleteOnlyIfRoleIsEmpty)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return 2;
}

if (deleteOnlyIfRoleIsEmpty)
{
if (role.Users.Count<User>() > 0)
{
return 4;
}
}

repository.Delete<Role>(role);

return 0;
}

public bool RoleExists(string applicationName, string roleName)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role != null)
{
return true;
}
else
{
return false;
}
}


public string[] FindUsersInRole(string applicationName, string roleName, string usernameToMatch)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return null;
}

IList<User> userList = new List<User>();

foreach (var user in role.Users)
{
if (user.Username.IndexOf(usernameToMatch) >= 0)
{
userList.Add(user);
}
}

if (userList.Count == 0)
{
return null;
}

string[] usernames = new String[userList.Count];

int i = 0;
foreach (User user in userList)
{
usernames[i++] = user.Username;
}

return usernames;
}

public string[] GetAllRoles(string applicationName)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<Role> roles = repository.Find<Role>("Application", application);

if (roles.Count == 0)
{
return null;
}

string[] roleNames = new String[roles.Count];

int i = 0;
foreach (var role in roles)
{
roleNames[i++] = role.Name;
}

return roleNames;
}

public string[] GetRolesForUser(string applicationName, string username)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user == null )
{
return null;
}

string[] roleNames = new String[user.Roles.Count<Role>()];

int i = 0;
foreach (Role role in user.Roles)
{
roleNames[i++] = role.Name;
}

return roleNames;
}

public string[] GetUsersInRole(string applicationName, string roleName)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return null;
}

if (role.Users.Count<User>() == 0)
{
return null;
}

string[] usernames = new String[role.Users.Count<User>()];

int i = 0;
foreach (var user in role.Users)
{
usernames[i++] = user.Username;
}

return usernames;
}

public bool IsUserInRole(string applicationName, string username, string roleName)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user == null)
{
return false;
}

Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return false;
}

if (user.Roles.Contains(role))
{
return true;
}
else
{
return false;
}
}

public int AddUsersToRoles(string applicationName, string[] usernames, string[] roleNames)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = new List<User>();
IList<Role> roles = new List<Role>();

foreach (string username in usernames)
{
User user = repository.FindOne<User>("Application", application, "Username", username);

if (user == null)
{
return 1;
}

users.Add(user);
}


foreach (string roleName in roleNames)
{
Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return 2;
}

roles.Add(role);
}


foreach (User user in users)
{
foreach (Role role in roles)
{
if (!user.Roles.Contains(role))
{
((IList<Role>)user.Roles).Add(role);

repository.Save<User>(user);
}
}
}

return 0;
}


public int RemoveUsersFromRoles(string applicationName, string[] usernames, string[] roleNames)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = new List<User>();
IList<Role> roles = new List<Role>();

foreach (string username in usernames)
{
User user = repository.FindOne<User>("Application", application, "Username", username);

if (user == null)
{
return 1;
}

users.Add(user);
}


foreach (string roleName in roleNames)
{
Role role = repository.FindOne<Role>("Application", application, "Name", roleName);

if (role == null)
{
return 2;
}

roles.Add(role);
}


foreach (User user in users)
{
foreach (Role role in roles)
{
if (user.Roles.Contains(role))
{
((IList<Role>)user.Roles).Remove(role);

repository.Update<User>(user);
}
}
}

return 0;
}

public Role GetRole(int roleID)
{
return repository.Get<int, Role>(roleID);
}

}
}

配置文件服务类

MVCQuick.Framework.Security.ProfileService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MVCQuick.Framework.Repository;
using System.Web;
using System.IO;

namespace MVCQuick.Framework.Security
{
public class ProfileService
{
IRepository repository;

public ProfileService(IRepository repository)
{
this.repository = repository;
}

public int DeleteInactiveProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);


IList<User> users = repository.Find<User>("Application", application);

int result = 0;

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.LastActivityDate < userInactiveSinceDate && user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (user.LastActivityDate < userInactiveSinceDate && !user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{
if (user.LastActivityDate < userInactiveSinceDate)
{
profile = repository.FindOne<Profile>("UserId", user.Id);


}
}

if (profile != null)
{
repository.Delete(profile);
result++;
}
}

return result;

}

public int DeleteProfiles(string applicationName, string[] usernames)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

int result = 0;

foreach (var username in usernames)
{
User user = repository.FindOne<User>("Application", application, "Username", username);

if (user != null)
{
Profile profile = repository.FindOne<Profile>("UserId", user.Id);

if (profile != null)
{
repository.Delete(profile);
result++;
}
}
}

return result;
}

public IList<System.Web.Profile.ProfileInfo> FindProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
string usernameToMatch,
DateTime userInactiveSinceDate,
int pageIndex, int pageSize, out int totalRecords)
{
IList<System.Web.Profile.ProfileInfo> profileInfos =
new List<System.Web.Profile.ProfileInfo>();

Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application, "Username", "%" + usernameToMatch + "%");

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.LastActivityDate < userInactiveSinceDate && user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (user.LastActivityDate < userInactiveSinceDate && !user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{
if (user.LastActivityDate < userInactiveSinceDate)
{
profile = repository.FindOne<Profile>("UserId", user.Id);


}
}

if (profile != null)
{
profileInfos.Add(new System.Web.Profile.ProfileInfo(
user.Username, this.isAnonymous(), user.LastActivityDate,
profile.LastUpdatedDate,
profile.PropertyNames.Length + profile.PropertyValuesBinary.Length + profile.PropertyValuesString.Length));

}
}

totalRecords = profileInfos.Count;

return (IList<System.Web.Profile.ProfileInfo>)
(profileInfos.Skip(pageIndex * pageSize).Take(pageSize));
}

public IList<System.Web.Profile.ProfileInfo> FindProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
string usernameToMatch,
int pageIndex, int pageSize, out int totalRecords)
{
IList<System.Web.Profile.ProfileInfo> profileInfos =
new List<System.Web.Profile.ProfileInfo>();

Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application, "Username", "%" + usernameToMatch + "%");

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (!user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}

if (profile != null)
{
profileInfos.Add(new System.Web.Profile.ProfileInfo(
user.Username, this.isAnonymous(), user.LastActivityDate,
profile.LastUpdatedDate,
profile.PropertyNames.Length + profile.PropertyValuesBinary.Length + profile.PropertyValuesString.Length));

}
}

totalRecords = profileInfos.Count;

return (IList<System.Web.Profile.ProfileInfo>)
(profileInfos.Skip(pageIndex * pageSize).Take(pageSize));
}

public IList<System.Web.Profile.ProfileInfo> GetAllInactiveProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate,
int pageIndex, int pageSize, out int totalRecords)
{
IList<System.Web.Profile.ProfileInfo> profileInfos =
new List<System.Web.Profile.ProfileInfo>();

Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application);

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.LastActivityDate < userInactiveSinceDate && user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (user.LastActivityDate < userInactiveSinceDate && !user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{
if (user.LastActivityDate < userInactiveSinceDate)
{
profile = repository.FindOne<Profile>("UserId", user.Id);


}
}

if (profile != null)
{
profileInfos.Add(new System.Web.Profile.ProfileInfo(
user.Username, this.isAnonymous(), user.LastActivityDate,
profile.LastUpdatedDate,
profile.PropertyNames.Length + profile.PropertyValuesBinary.Length + profile.PropertyValuesString.Length));

}
}

totalRecords = profileInfos.Count;

return (IList<System.Web.Profile.ProfileInfo>)
(profileInfos.Skip(pageIndex * pageSize).Take(pageSize));
}

public IList<System.Web.Profile.ProfileInfo> GetAllProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
int pageIndex, int pageSize, out int totalRecords)
{
IList<System.Web.Profile.ProfileInfo> profileInfos =
new List<System.Web.Profile.ProfileInfo>();

Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application);

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (!user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{

profile = repository.FindOne<Profile>("UserId", user.Id);

}

if (profile != null)
{
profileInfos.Add(new System.Web.Profile.ProfileInfo(
user.Username, this.isAnonymous(), user.LastActivityDate,
profile.LastUpdatedDate,
profile.PropertyNames.Length + profile.PropertyValuesBinary.Length + profile.PropertyValuesString.Length));

}
}

totalRecords = profileInfos.Count;

return (IList<System.Web.Profile.ProfileInfo>)
(profileInfos.Skip(pageIndex * pageSize).Take(pageSize));
}

public int GetNumberOfInactiveProfiles(string applicationName,
System.Web.Profile.ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{

System.Web.Profile.ProfileInfoCollection profileInfos =
new System.Web.Profile.ProfileInfoCollection();

Application application =
new ApplicationService(repository).GetApplication(applicationName);

IList<User> users = repository.Find<User>("Application", application);

foreach (var user in users)
{
Profile profile = null;

if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Anonymous)
{
if (user.LastActivityDate < userInactiveSinceDate && user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else if (authenticationOption == System.Web.Profile.ProfileAuthenticationOption.Authenticated)
{
if (user.LastActivityDate < userInactiveSinceDate && !user.IsAnonymous)
{
profile = repository.FindOne<Profile>("UserId", user.Id);
}
}
else
{
if (user.LastActivityDate < userInactiveSinceDate)
{
profile = repository.FindOne<Profile>("UserId", user.Id);


}
}

if (profile != null)
{
profileInfos.Add(new System.Web.Profile.ProfileInfo(
user.Username, this.isAnonymous(), user.LastActivityDate,
profile.LastUpdatedDate,
profile.PropertyNames.Length + profile.PropertyValuesBinary.Length + profile.PropertyValuesString.Length));

}
}

return profileInfos.Count;
}

public int GetProperties(string applicationName, string username,
System.Configuration.SettingsPropertyValueCollection svc,
DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

Profile dbProperties = repository.FindOne<Profile>("UserId", user.Id);

if (user == null)
{
return 1;
}

if (dbProperties == null)
{
return 1;
}

string[] names = null;
string values = null;

names = dbProperties.PropertyNames.Split(':');
values = dbProperties.PropertyValuesString;

if (names != null && names.Length > 0)
{
ParseDataFromDB(names, values, dbProperties.PropertyValuesBinary, svc);
}


return 0;
}

public int SetProperties(string applicationName, string username,
System.Configuration.SettingsPropertyValueCollection properties,
bool isAuthenticated, DateTime currentTimeUtc)
{
Application application =
new ApplicationService(repository).GetApplication(applicationName);

User user = repository.FindOne<User>("Application", application, "Username", username);

if (user == null)
{
return 1;
}

string allNames = string.Empty;
string allValues = string.Empty;
byte[] buf = null;

PrepareDataForSaving(ref allNames, ref allValues, ref buf, true, properties, isAuthenticated);

if (allNames.Length == 0)
{
return 1;
}

Profile profile = new Profile();
profile.UserId = user.Id;
profile.PropertyNames = allNames;
profile.PropertyValuesBinary = buf;
profile.PropertyValuesString = allValues;
profile.LastUpdatedDate = currentTimeUtc;

Profile dbProperties = repository.FindOne<Profile>("UserId", user.Id);

if (dbProperties == null)
repository.Save(profile);
else
repository.Update(profile);


return 0;
}

private bool isAnonymous()
{
HttpContext current = HttpContext.Current;

if (current != null)
{
if (current.Request.IsAuthenticated)
{
return false;
}
}
return true;
}

private void ParseDataFromDB(string[] names, string values, byte[] buf,
System.Configuration.SettingsPropertyValueCollection properties)
{
if (((names != null) && (values != null)) && ((buf != null) && (properties != null)))
{
try
{
for (int i = 0; i < (names.Length / 4); i++)
{
string str = names[i * 4];
System.Configuration.SettingsPropertyValue value2 = properties[str];
if (value2 != null)
{
int startIndex = int.Parse(names[(i * 4) + 2], System.Globalization.CultureInfo.InvariantCulture);
int length = int.Parse(names[(i * 4) + 3], System.Globalization.CultureInfo.InvariantCulture);
if ((length == -1) && !value2.Property.PropertyType.IsValueType)
{
value2.PropertyValue = null;
value2.IsDirty = false;
value2.Deserialized = true;
}
if (((names[(i * 4) + 1] == "S") && (startIndex >= 0)) && ((length > 0) && (values.Length >= (startIndex + length))))
{
value2.SerializedValue = values.Substring(startIndex, length);
}
if (((names[(i * 4) + 1] == "B") && (startIndex >= 0)) && ((length > 0) && (buf.Length >= (startIndex + length))))
{
byte[] dst = new byte[length];
Buffer.BlockCopy(buf, startIndex, dst, 0, length);
value2.SerializedValue = dst;
}
}
}
}
catch
{
}
}
}

private void PrepareDataForSaving(ref string allNames, ref string allValues, ref byte[] buf,
bool binarySupported, System.Configuration.SettingsPropertyValueCollection properties,
bool userIsAuthenticated)
{
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
MemoryStream stream = binarySupported ? new MemoryStream() : null;
try
{
try
{
bool flag = false;
foreach (System.Configuration.SettingsPropertyValue value2 in properties)
{
if (value2.IsDirty && (userIsAuthenticated || ((bool)value2.Property.Attributes["AllowAnonymous"])))
{
flag = true;
break;
}
}
if (!flag)
{
return;
}
foreach (System.Configuration.SettingsPropertyValue value3 in properties)
{
if ((!userIsAuthenticated && !((bool)value3.Property.Attributes["AllowAnonymous"])) || (!value3.IsDirty && value3.UsingDefaultValue))
{
continue;
}
int length = 0;
int position = 0;
string str = null;
if (value3.Deserialized && (value3.PropertyValue == null))
{
length = -1;
}
else
{
object serializedValue = value3.SerializedValue;
if (serializedValue == null)
{
length = -1;
}
else
{
if (!(serializedValue is string) && !binarySupported)
{
serializedValue = Convert.ToBase64String((byte[])serializedValue);
}
if (serializedValue is string)
{
str = (string)serializedValue;
length = str.Length;
position = builder2.Length;
}
else
{
byte[] buffer = (byte[])serializedValue;
position = (int)stream.Position;
stream.Write(buffer, 0, buffer.Length);
stream.Position = position + buffer.Length;
length = buffer.Length;
}
}
}
builder.Append(value3.Name + ":" + ((str != null) ? "S" : "B") + ":" + position.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + length.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":");
if (str != null)
{
builder2.Append(str);
}
}
if (binarySupported)
{
buf = stream.ToArray();
}
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
catch
{
throw;
}
allNames = builder.ToString();
allValues = builder2.ToString();
}
}
}

 

源代码下载:http://mvcquick.codeplex.com/   

posted @ 2011-10-18 15:26  GuYoung  阅读(699)  评论(0编辑  收藏  举报