Building a MVC2 Template, Part 17, Adding Provider Repository Specifications
Oct 18
.Net, Development Asp.Net Mvc, Fluent NHibernate, Nehemiah Project, NHibernate 2 Comments
In the next three series of posts we will be adding NHibernate, Fluent NHibernate, and NHibernate.Linq to our template. This specific installment on building a MVC2 template we will update the Nehemiah.Specs project. This project contains all of the specifications for the template. We’ll add the specifications for the provider repository. The provider repository is the data layer that supports our membership, role, and profile providers. The specifications are not unique to any data layer implementation. As such you could easily switch out the NHibernate provider repository to a LinqToSQL repository (which I have already done) without changing the specifications.
Part 18 of this series will address the changes to the Nehemiah.Data project, where the actual implementation of NHibernate occurs. Part 19 will cover the changes to the main web project. There is a lot of new and updated code to show. So lets get started by downloading the NHibernate binaries and putting them into our code vault.
In your _CodeVault folder create a folder named Fluent NHibernate and a subfolder named 1.1. Version 1.1 of Fluent NHibernate is built against version 2.1.2GA of NHibernate. Download Fluent NHibernate from this link and place the contents of the archive file into the folder you just created.
The archive file you just downloaded does not include NHibernate.Linq. So create a folder named NHibernate.Linq in your _CodeVault folder. Then create a subfolder named 2.1.2GA. Download version 2.1.2GA of NHibernate.Linq from here and place the contents into the folder you just created.
If you choose you can also download NHibernate and add it to your _CodeVault folder. There’s really no need to do so, since you already have a copy of NHibernate in the Fluent NHibernate folder.
Provider Repository Specifications
In the Nehemiah.Specs project add a reference to the Service.Logging project and a reference to the NHibernate.ByteCode.Castle dll. Below is the entire provider repository specification source code. You will notice a few lines of code have been commented out that reference the UserInRole object. Trying to load this table in a list causes all kinds of errors in the specifications.
using System;
using Machine.Specifications;
using Machine.Specifications.Model;
using Nehemiah.Data;
using Nehemiah.Data.Models;
using Nehemiah.Data.NHibernate;
using Service.Logging;
using Service.Logging.Log4Net;
using Service.Logging.NLog;
using System.Collections.Generic;
using System.Configuration;
namespace Nehemiah.Specs.Repositories
{
[Subject("Provider Repository")]
public class Initialized_Properly : ProviderRepositoryContext
{
static IList<User> userList;
//static IList<UserInRole> xrefList;
static IList<Role> roleList;
Because of = () =>
{
userList = Repository.GetAllUsers(applicationName);
//xrefList = Repository.GetAllUserInRole(applicationName);
roleList = Repository.GetAllRoles(applicationName);
};
It the_Role_table_should_contain_the_correct_number_of_records = () =>
{
roleList.Count.ShouldEqual(6);
};
It the_User_table_should_contain_the_correct_number_of_records = () =>
{
userList.Count.ShouldEqual(12);
};
//It the_UserInRole_table_should_contain_the_correct_number_of_records = () =>
//{
// xrefList.Count.ShouldEqual(15);
//};
}
#region - Role Specs -
[Subject("Provider Repository")]
public class NumberOfUsersInRole_method : ProviderRepositoryContext
{
static int userCount = -1;
Because of = () =>
{
userCount = Repository.NumberOfUsersInRole(applicationName, rolenameRegistered);
};
It should_return_the_number_of_users_in_the_specified_role = () =>
{
userCount.ShouldEqual(12);
};
}
[Subject("Provider Repository")]
public class Add_Role_method : ProviderRepositoryContext
{
static Role newRole;
static Role readRole;
static bool success;
Because of = () =>
{
// Delete the role if it already exists.
newRole = Repository.GetRoleByRoleName(applicationName, rolenameNew3);
if (newRole != null)
Repository.DeleteRole(applicationName, rolenameNew3);
newRole = new Role(applicationName, rolenameNew3);
success = Repository.Add(applicationName, newRole);
readRole = Repository.GetRoleByRoleName(applicationName, rolenameNew3);
};
It should_return_true_on_a_successful_add = () =>
{
success.ShouldBeTrue();
};
It should_add_the_role = () =>
{
readRole.ShouldNotBeNull();
readRole.ApplicationName.ShouldEqual(applicationName);
readRole.RoleName.ShouldEqual(rolenameNew3);
};
}
[Subject("Provider Repository")]
public class DeleteRole_method : ProviderRepositoryContext
{
static bool success = false;
static Role deletedRole;
Because of = () =>
{
success = Repository.DeleteRole(applicationName, rolenameNew3);
deletedRole = Repository.GetRoleByRoleName(applicationName, rolenameNew3);
};
It should_delete_the_role = () =>
{
success.ShouldBeTrue();
deletedRole.ShouldBeNull();
};
}
[Subject("Provider Repository")]
public class GetAllRoles_method : ProviderRepositoryContext
{
static IList<Role> roleList;
Because of = () =>
{
roleList = Repository.GetAllRoles(applicationName);
};
It should_a_list_of_all_roles = () =>
{
roleList.Count.ShouldEqual(6);
};
}
[Subject("Provider Repository")]
public class GetRoleByKey_method : ProviderRepositoryContext
{
static Role role;
Because of = () =>
{
role = Repository.GetRoleByKey(applicationName, 1);
};
It should_return_the_role_specified_by_the_RoleId = () =>
{
role.RoleId.ShouldEqual(1);
};
}
[Subject("Provider Repository")]
public class GetRoleList_method : ProviderRepositoryContext
{
static IList<Role> roleList;
Because of = () =>
{
roleList = Repository.GetRoleList(applicationName, 0, pageSize);
};
It should_return_a_list_of_roles = () =>
{
roleList.ShouldNotBeNull();
};
It list_count_should_equal_page_size_when_record_count_is_greater_than_page_size = () =>
{
roleList.ShouldNotBeEmpty();
roleList.Count.ShouldEqual(pageSize);
};
}
[Subject("Provider Repository")]
public class GetRoleListByRoleName_method : ProviderRepositoryContext
{
static IList<Role> roleList;
static IList<Role> shortList;
Because of = () =>
{
roleList = Repository.GetRoleListByRoleName(applicationName, roleSearchLong, 0, pageSize);
shortList = Repository.GetRoleListByRoleName(applicationName, roleSearchShort, 0, pageSize);
};
It should_return_a_list_of_users = () =>
{
roleList.ShouldNotBeNull();
shortList.ShouldNotBeNull();
};
It list_count_should_equal_page_size_when_record_count_is_greater_than_page_size = () =>
{
roleList.ShouldNotBeEmpty();
roleList.Count.ShouldEqual(pageSize);
};
It list_count_should_equal_all_records_when_record_count_is_less_than_page_size = () =>
{
shortList.ShouldNotBeEmpty();
shortList.Count.ShouldEqual(3);
};
}
[Subject("Provider Repository")]
public class NumberOfRoles_method : ProviderRepositoryContext
{
static int countOfRoles = 0;
Because of = () =>
{
countOfRoles = Repository.NumberOfRoles(applicationName);
};
It should_return_the_number_of_roles = () =>
{
countOfRoles.ShouldEqual(6);
};
}
[Subject("Provider Repository")]
public class Save_Role_method : ProviderRepositoryContext
{
static Role updatedRole;
static Role readRole;
static bool success;
Because of = () =>
{
updatedRole = Repository.GetRoleByRoleName(applicationName, rolenameAdmin);
updatedRole.RoleName = roleNewName;
success = Repository.Save(applicationName, updatedRole);
readRole = Repository.GetRoleByRoleName(applicationName, roleNewName);
};
It should_return_true_on_a_successful_save = () =>
{
success.ShouldBeTrue();
};
It should_save_the_changed_information = () =>
{
readRole.RoleName.ShouldEqual(roleNewName);
// Change the rolename back
readRole.RoleName = rolenameAdmin;
success = Repository.Save(applicationName, readRole);
};
}
[Subject("Provider Repository")]
public class GetRolesForUser_with_UserId_method : ProviderRepositoryContext
{
static IList<Role> roleList;
static User user;
Because of = () =>
{
user = Repository.GetUserByUserName(applicationName, usernameSearchName);
roleList = Repository.GetRolesForUser(applicationName, user.UserId);
};
It should_return_a_list_of_roles_for_the_specified_user = () =>
{
roleList.ShouldNotBeNull();
roleList.ShouldNotBeEmpty();
roleList.Count.ShouldEqual(3);
};
}
[Subject("Provider Repository")]
public class GetRolesForUser_with_UserName_method : ProviderRepositoryContext
{
static IList<Role> roleList;
Because of = () =>
{
roleList = Repository.GetRolesForUser(applicationName, usernameSearchName);
};
It should_return_a_list_of_roles_for_the_specified_user = () =>
{
roleList.ShouldNotBeNull();
roleList.ShouldNotBeEmpty();
roleList.Count.ShouldEqual(3);
};
}
#endregion
#region - User Specs -
[Subject("Provider Repository")]
public class Add_User_method : ProviderRepositoryContext
{
static User readUser;
static bool success;
Because of = () =>
{
success = Repository.Add(applicationName, userAdd);
readUser = Repository.GetUserByUserName(applicationName, userAddUserName);
};
It should_return_true_on_a_successful_add = () =>
{
success.ShouldBeTrue();
};
It should_return_the_user = () =>
{
readUser.ShouldNotBeNull();
readUser.ApplicationName.ShouldEqual(applicationName);
readUser.Approved.ShouldBeTrue();
readUser.Comment.ShouldEqual(userAddComment);
readUser.CreationDate.ShouldBeGreaterThan(DateTime.UtcNow.AddSeconds(-10));
readUser.CreationDate.ShouldBeLessThan(DateTime.UtcNow.AddSeconds(10));
readUser.Email.ShouldEqual(userAddEmail);
readUser.FailedPasswordAnswerAttemptCount.ShouldEqual(0);
readUser.FailedPasswordAnswerAttemptStartWindow.ShouldBeNull();
readUser.FailedPasswordAttemptCount.ShouldEqual(0);
readUser.FailedPasswordAttemptWindowStart.ShouldBeNull();
readUser.LastActivityDate.ShouldBeGreaterThan(DateTime.UtcNow.AddSeconds(-10));
readUser.LastActivityDate.ShouldBeLessThan(DateTime.UtcNow.AddSeconds(10));
readUser.LastLockedOutDate.ShouldBeNull();
readUser.LastLoginDate.ShouldBeNull();
readUser.LastPasswordChangedDate.ShouldBeNull();
readUser.LockedOut.ShouldBeFalse();
readUser.Online.ShouldBeFalse();
readUser.Password.ShouldEqual(userAddPassword);
readUser.PasswordAnswer.ShouldEqual(userAddPasswordAnswer);
readUser.PasswordQuestion.ShouldEqual(userAddPasswordQuestion);
//readUser.Roles.ShouldBeEmpty();
readUser.UserId.ShouldNotEqual(Guid.Empty);
readUser.UserName.ShouldEqual(userAddUserName);
};
}
[Subject("Provider Repository")]
public class DeleteUser_method : ProviderRepositoryContext
{
static User readUser;
static bool success;
Because of = () =>
{
readUser = Repository.GetUserByUserName(applicationName, userAddUserName);
if (readUser == null)
Repository.Add(applicationName, userAdd);
success = Repository.DeleteUser(applicationName, userAddUserName);
readUser = Repository.GetUserByUserName(applicationName, userAddUserName);
};
It should_return_true_on_a_successful_delete = () =>
{
success.ShouldBeTrue();
};
It user_should_be_removed_from_the_repository = () =>
{
readUser.ShouldBeNull();
};
}
[Subject("Provider Repository")]
public class GetUserByUserName_method : ProviderRepositoryContext
{
static User readUser;
Because of = () =>
{
readUser = Repository.GetUserByUserName(applicationName, usernameSearchName);
};
It should_return_the_user_specified_by_the_UserName = () =>
{
readUser.ShouldNotBeNull();
readUser.ApplicationName.ShouldEqual(applicationName);
readUser.Approved.ShouldBeTrue();
readUser.Comment.ShouldEqual(userSearchComment);
readUser.CreationDate.ShouldBeGreaterThan(DateTime.UtcNow.AddSeconds(-10));
readUser.CreationDate.ShouldBeLessThan(DateTime.UtcNow.AddSeconds(10));
readUser.Email.ShouldEqual(userSearchEmail);
readUser.FailedPasswordAnswerAttemptCount.ShouldEqual(0);
readUser.FailedPasswordAnswerAttemptStartWindow.ShouldBeNull();
readUser.FailedPasswordAttemptCount.ShouldEqual(0);
readUser.FailedPasswordAttemptWindowStart.ShouldBeNull();
readUser.LastActivityDate.ShouldBeGreaterThan(DateTime.UtcNow.AddSeconds(-10));
readUser.LastActivityDate.ShouldBeLessThan(DateTime.UtcNow.AddSeconds(10));
readUser.LastLockedOutDate.ShouldBeNull();
readUser.LastLoginDate.ShouldBeNull();
readUser.LastPasswordChangedDate.ShouldBeNull();
readUser.LockedOut.ShouldBeFalse();
readUser.Online.ShouldBeFalse();
readUser.Password.ShouldEqual(userSearchPassword);
readUser.PasswordAnswer.ShouldEqual(userSearchPasswordAnswer);
readUser.PasswordQuestion.ShouldEqual(userSearchPasswordQuestion);
readUser.Roles.Count.ShouldEqual(3);
readUser.UserId.ShouldNotEqual(Guid.Empty);
readUser.UserName.ShouldEqual(usernameSearchName);
};
}
[Subject("Provider Repository")]
public class GetUserByKey_method : ProviderRepositoryContext
{
static User readUser;
static User tempUser;
Because of = () =>
{
tempUser = Repository.GetUserByUserName(applicationName, usernameSearchName);
readUser = Repository.GetUserByKey(applicationName, tempUser.UserId);
};
It should_return_the_user_specified_by_the_UserId = () =>
{
readUser.ShouldNotBeNull();
readUser.UserId.ShouldEqual(tempUser.UserId);
readUser.Roles.Count.ShouldEqual(3);
};
}
[Subject("Provider Repository")]
public class GetUserByEmail_method : ProviderRepositoryContext
{
static User readUser;
static User tempUser;
Because of = () =>
{
tempUser = Repository.GetUserByUserName(applicationName, usernameSearchName);
readUser = Repository.GetUserByEmail(applicationName, tempUser.Email);
};
It should_return_the_user_specified_by_the_email_address = () =>
{
readUser.ShouldNotBeNull();
readUser.UserId.ShouldEqual(tempUser.UserId);
readUser.Roles.Count.ShouldEqual(3);
};
}
[Subject("Provider Repository")]
public class GetUserList_method : ProviderRepositoryContext
{
static IList<User> userList;
Because of = () =>
{
userList = Repository.GetUserList(applicationName, 0, pageSize);
};
It should_return_a_list_of_users = () =>
{
userList.ShouldNotBeNull();
};
It list_count_should_equal_page_size_when_record_count_is_greater_than_page_size = () =>
{
userList.ShouldNotBeEmpty();
userList.Count.ShouldEqual(pageSize);
};
}
[Subject("Provider Repository")]
public class GetUserListByEmail_method : ProviderRepositoryContext
{
static IList<User> userList;
static IList<User> shortList;
Because of = () =>
{
userList = Repository.GetUserListByEmail(applicationName, "there.com", 0, pageSize);
shortList = Repository.GetUserListByEmail(applicationName, "elsewhere.com", 0, pageSize);
};
It should_return_a_list_of_users = () =>
{
userList.ShouldNotBeNull();
shortList.ShouldNotBeNull();
};
It list_count_should_equal_page_size_when_record_count_is_greater_than_page_size = () =>
{
userList.ShouldNotBeEmpty();
userList.Count.ShouldEqual(pageSize);
};
It list_count_should_equal_all_records_when_count_is_less_than_page_size = () =>
{
shortList.ShouldNotBeEmpty();
shortList.Count.ShouldEqual(2);
};
}
[Subject("Provider Repository")]
public class GetUserListByUserName_method : ProviderRepositoryContext
{
static IList<User> userList;
static IList<User> shortList;
Because of = () =>
{
userList = Repository.GetUserListByUserName(applicationName, usernameSearchLong, 0, pageSize);
shortList = Repository.GetUserListByUserName(applicationName, usernameSearchShort, 0, pageSize);
};
It should_return_a_list_of_users = () =>
{
userList.ShouldNotBeNull();
shortList.ShouldNotBeNull();
};
It list_count_should_equal_page_size_when_record_count_is_greater_than_page_size = () =>
{
userList.ShouldNotBeEmpty();
userList.Count.ShouldEqual(pageSize);
};
It list_count_should_equal_all_records_when_record_count_is_less_than_page_size = () =>
{
shortList.ShouldNotBeEmpty();
shortList.Count.ShouldEqual(3);
};
}
[Subject("Provider Repository")]
public class NumberOfUsers_method : ProviderRepositoryContext
{
static int userCount = 0;
Because of = () =>
{
userCount = Repository.NumberOfUsers(applicationName);
};
It should_return_the_number_of_users_in_the_database = () =>
{
userCount.ShouldEqual(12);
};
}
[Subject("Provider Repository")]
public class NumberOfUsersByEmail_method : ProviderRepositoryContext
{
static int userCount = 0;
Because of = () =>
{
userCount = Repository.NumberOfUsersByEmail(applicationName, "there.com");
};
It should_return_the_number_of_users_matching_the_email = () =>
{
userCount.ShouldEqual(9);
};
}
[Subject("Provider Repository")]
public class NumberOfUsersByUserName_method : ProviderRepositoryContext
{
static int userCount = 0;
Because of = () =>
{
userCount = Repository.NumberOfUsersByEmail(applicationName, usernameSearchLong);
};
It should_return_the_number_of_users_matching_the_username = () =>
{
userCount.ShouldEqual(7);
};
}
[Subject("Provider Repository")]
public class NumberOfUsersOnline_method : ProviderRepositoryContext
{
static int userCount = 0;
Because of = () =>
{
userCount = Repository.NumberOfUsersOnline(applicationName, 10);
};
It should_return_the_number_of_users_presently_online = () =>
{
userCount.ShouldEqual(12);
};
}
[Subject("Provider Repository")]
public class Save_User_method : ProviderRepositoryContext
{
static User updatedUser;
static User readUser;
static bool success;
Because of = () =>
{
updatedUser = Repository.GetUserByUserName(applicationName, usernameSearchName);
updatedUser.Comment = userNewComment;
updatedUser.DeleteRole(roleNew2);
updatedUser.AddRole(roleAdmin);
success = Repository.Save(applicationName, updatedUser);
readUser = Repository.GetUserByUserName(applicationName, usernameSearchName);
};
It should_return_true_on_a_successful_save = () =>
{
success.ShouldBeTrue();
};
It should_save_the_changed_information = () =>
{
readUser.Comment.ShouldEqual(userNewComment);
};
It should_update_the_roles = () =>
{
readUser.Roles.Count.ShouldEqual(3);
readUser.HasRole(rolenameNew2).ShouldBeFalse();
readUser.HasRole(rolenameAdmin).ShouldBeTrue();
};
}
[Subject("Provider Repository")]
public class GetUsersInRole_method : ProviderRepositoryContext
{
static IList<User> userList;
Because of = () =>
{
userList = Repository.GetUsersInRole(applicationName, rolenameRegistered);
};
It should_return_a_list_of_all_users_with_the_specified_role = () =>
{
userList.ShouldNotBeNull();
userList.ShouldNotBeEmpty();
userList.Count.ShouldEqual(12);
};
}
[Subject("Provider Repository")]
public class GetUsersInRole_with_UserName_User_method : ProviderRepositoryContext
{
static IList<User> userList;
Because of = () =>
{
userList = Repository.GetUsersInRole(applicationName, rolenameRegistered, usernameSearchShort);
};
It should_return_a_list_of_all_users_with_the_specified_role = () =>
{
userList.ShouldNotBeNull();
userList.ShouldNotBeEmpty();
userList.Count.ShouldEqual(3);
};
}
#endregion
#region - Profile Specs -
#endregion
public abstract class ProviderRepositoryContext
{
private static bool Initialized = false;
protected static IProviderRepository Repository;
public static IFluentSessionFactory SessionFactory;
public static ILogger Logger;
protected static string applicationName = "Specs";
protected static string secondAppName = "OtherApplication";
protected static int pageSize = 5;
protected static User userAdd;
protected static string userAddUserName = "New User";
protected static string userAddEmail = "new@there.com";
protected static string userAddPassword = "pa55w0rd";
protected static string userAddPasswordQuestion = "This is a question";
protected static string userAddPasswordAnswer = "answer";
protected static bool userAddIsApproved = true;
protected static string userAddComment = "This is a comment";
protected static string userNewComment = "Ka Maika'i Ola";
protected static string userDelete = "Delete Me";
protected static string usernameSearchLong = "User"; // Long because the result list is long
protected static string usernameSearchShort = "UserName"; // Short because hte list of results is short
protected static string usernameSearchName = "SearchUser";
protected static string userSearchEmail = "search@elsewhere.com";
protected static string userSearchPassword = "!Password";
protected static string userSearchPasswordQuestion = "This is a question for the Search user";
protected static string userSearchPasswordAnswer = "answer to the Search user question";
protected static bool userSearchIsApproved = true;
protected static string userSearchComment = "This is a comment for the Search user";
protected static string rolenameAdmin = "Administrator";
protected static string rolenameRegistered = "Registered";
protected static string rolenameDelete = "DeleteRole";
protected static string rolenameNoUsers = "NoUsers";
protected static string rolenameNew1 = "NewRole1";
protected static string rolenameNew2 = "NewRole2";
protected static string rolenameNew3 = "NewRole3";
protected static string roleNewName = "Tester";
protected static string roleSearchLong = "e"; // Just a little cheat for testing
protected static string roleSearchShort = "role";
protected static Role roleAdmin;
protected static Role roleRegistered;
protected static Role roleDelete;
protected static Role roleNousers;
protected static Role roleNew1;
protected static Role roleNew2;
protected static Role roleNew3;
Establish context = () =>
{
//string connection = ConfigurationManager.AppSettings["Nehemiah"];
//// Todo: Remove this hardcoded value
//if (string.IsNullOrEmpty(connection) == true)
// connection = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=C:\Dev\Nehemiah - NHibernate\Nehemiah\App_Data\Specs.mdf;User Instance=true";
Logger = new Log4NetLogger();
//Repository = new SubSonicRepository(Logger);
//Repository = new Linq2SQLRepository(connection, Logger);
SessionFactory = new SQL2005SessionFactory();
//SessionFactory = new SQLiteSessionFactory();
Repository = new NHibernateRepository(SessionFactory, Logger);
if (Initialized == false)
{
Initialized = true;
// Clean up the database
foreach (User u in Repository.GetAllUsers(applicationName))
Repository.DeleteUser(u);
foreach (User u in Repository.GetAllUsers(secondAppName))
Repository.DeleteUser(u);
////foreach (Role r in Repository.GetAllRoles(applicationName))
//// Repository.DeleteRole(applicationName, r.RoleName);
// Add a couple of Roles to the database - Comment out after the roles are created in the database
Repository.Add(applicationName, new Role(applicationName, rolenameAdmin));
Repository.Add(applicationName, new Role(applicationName, rolenameRegistered));
Repository.Add(applicationName, new Role(applicationName, rolenameNoUsers));
Repository.Add(applicationName, new Role(applicationName, rolenameNew1));
Repository.Add(applicationName, new Role(applicationName, rolenameNew2));
Repository.Add(applicationName, new Role(applicationName, rolenameDelete));
roleAdmin = Repository.GetRoleByRoleName(applicationName, rolenameAdmin);
roleRegistered = Repository.GetRoleByRoleName(applicationName, rolenameRegistered);
roleDelete = Repository.GetRoleByRoleName(applicationName, rolenameDelete);
if (roleDelete == null)
Repository.Add(applicationName, new Role(applicationName, rolenameDelete));
roleNousers = Repository.GetRoleByRoleName(applicationName, rolenameNoUsers);
roleNew1 = Repository.GetRoleByRoleName(applicationName, rolenameNew1);
roleNew2 = Repository.GetRoleByRoleName(applicationName, rolenameNew2);
roleNew3 = Repository.GetRoleByRoleName(applicationName, rolenameNew3);
userAdd = new User(applicationName, userAddUserName, userAddEmail, userAddPassword, userAddPasswordQuestion, userAddPasswordAnswer, userAddIsApproved, userAddComment);
userAdd.Roles.Add(roleAdmin);
//Repository.Add(applicationName, userAdd);
// Add some extra users for general testing purposes
User user;
//Role role = Repository.GetRoleByRoleName(applicationName, rolenameRegistered);
user = new User(applicationName, "UserName", "me@there.com", "password", null, null, true, null);
user.LastActivityDate = DateTime.UtcNow;
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "UserName2", "me2@there.com", "password", null, null, true, null);
user.LastActivityDate = DateTime.UtcNow;
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "UserName3", "me3@there.com", "password", null, null, true, null);
user.LastActivityDate = DateTime.UtcNow;
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "UpdateUser", "update@there.com", "password", null, null, true, null);
user.LastActivityDate = DateTime.UtcNow;
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user5", "user5@there.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user6", "user6@there.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user7", "user7@there.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user8", "user8@there.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user9", "user9@there.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, "user10", "user10@elsewhere.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, userDelete, "user11@deletes.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
user = new User(applicationName, usernameSearchName, userSearchEmail, userSearchPassword, userSearchPasswordQuestion, userSearchPasswordAnswer, userSearchIsApproved, userSearchComment);
user.Roles.Add(roleRegistered);
user.Roles.Add(Repository.GetRoleByRoleName(applicationName, rolenameNew1));
user.Roles.Add(Repository.GetRoleByRoleName(applicationName, rolenameNew2));
Repository.Add(applicationName, user);
user = new User(secondAppName, "user99", "user99@elsewhere.com", "password", null, null, true, null);
user.Roles.Add(roleRegistered);
Repository.Add(applicationName, user);
}
};
}
}
Make sure the App.config in the Nehemiah.Specs project matches the code below. You can see that I have added configuration information for log4net.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<appSettings />
<connectionStrings>
<!-- Todo: Change the path to reflect the actual path of your MDF file -->
<add name="Nehemiah" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=C:\development\Erictopia\Nehemiah\Nehemiah\app_data\Specs.mdf;User Instance=true"/>
</connectionStrings>
<!-- log4net -->
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="App_Data\log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>
<system.web>
<membership defaultProvider="NehemiahMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<remove name="AspNetSqlMembershipProvider"/>
<add name="NehemiahMembershipProvider"
description =""
type="Nehemiah.Providers.NehemiahMembershipProvider, Nehemiah.Providers"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Clear"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="Nehemiah"/>
</providers>
</membership>
</system.web>
</configuration>
Below is an update to the MockProviderRepository.cs, located in the Nehemiah.Specs project. I have added a couple of new methods that will appear in Part 19. One additional change I made was to the MockProviderRepository.cs file to a folder named Support. If you do the same then you will need to update using statements in the MembershipProviderSpec, RoleProviderSpec and the ProfileProviderSpec files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nehemiah.Data;
using Nehemiah.Data.Models;
using System.Web;
namespace Nehemiah.Specs.Support
{
public class MockProviderRepository : IProviderRepository
{
IList<User> UserList;
IList<Role> RoleList;
IList<UserInRole> UserInRoleList;
IList<Profile> ProfileList;
public MockProviderRepository()
{
UserList = new List<User>
{
new User { ApplicationName = "Nehemiah"
, Approved = true
, Comment = "No comment"
, CreationDate = DateTime.UtcNow
, Email = "me@there.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = DateTime.UtcNow
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = true
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("01234567-89AB-CDEF-0123-456789ABCDEF")
, UserName = "UserName"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = true
, Comment = "No comment"
, CreationDate = DateTime.UtcNow
, Email = "me2@there.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = DateTime.UtcNow
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = true
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("22222222-2222-2222-2222-222222222222")
, UserName = "UserName2"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = true
, Comment = "No comment"
, CreationDate = DateTime.UtcNow
, Email = "me3@there.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("33333333-3333-3333-3333-333333333333")
, UserName = "UserName3"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = false
, Comment = ""
, CreationDate = DateTime.UtcNow
, Email = "update@somewhere.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = true
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("44444444-4444-4444-4444-444444444444")
, UserName = "UpdateUser"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = false
, Comment = ""
, CreationDate = DateTime.UtcNow
, Email = "update@somewhere.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = true
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("55555555-5555-5555-5555-555555555555")
, UserName = "LockedOutUser"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = false
, Comment = ""
, CreationDate = DateTime.UtcNow
, Email = "update@somewhere.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("66666666-6666-6666-6666-666666666666")
, UserName = "NotApprovedUser"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = false
, Comment = ""
, CreationDate = DateTime.UtcNow
, Email = "remove@somewhere.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("77777777-7777-7777-7777-777777777777")
, UserName = "RemoveUser1"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = false
, Comment = ""
, CreationDate = DateTime.UtcNow
, Email = "remove2@somewhere.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("88888888-8888-8888-8888-888888888888")
, UserName = "RemoveUser2"
} ,
new User { ApplicationName = "Nehemiah"
, Approved = true
, Comment = null
, CreationDate = DateTime.UtcNow
, Email = "deleteme@delete.com"
, FailedPasswordAnswerAttemptCount = 0
, FailedPasswordAnswerAttemptStartWindow = null
, FailedPasswordAttemptCount = 0
, FailedPasswordAttemptWindowStart = null
, LastActivityDate = null
, LastLockedOutDate = null
, LastLoginDate = null
, LastPasswordChangedDate = null
, LockedOut = false
, Online = false
, Password = "GoodPassword"
, PasswordAnswer = "Old answer"
, PasswordQuestion = "This is an old question"
, UserId = new Guid("11111111-2222-3333-4444-555555555555")
, UserName = "DeleteMe"
}
};
RoleList = new List<Role>
{
new Role { ApplicationName = "Nehemiah"
, RoleName = "Administrator"
, RoleId = 1
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "Registered"
, RoleId = 2
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "DeleteRole"
, RoleId = 3
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "NoUsers"
, RoleId = 4
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "NewRole1"
, RoleId = 5
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "NewRole2"
, RoleId = 5
} ,
new Role { ApplicationName = "Nehemiah"
, RoleName = "NewRole3"
, RoleId = 6
}
};
UserInRoleList = new List<UserInRole>
{
new UserInRole { RoleId = 1
, UserId = new Guid("01234567-89AB-CDEF-0123-456789ABCDEF")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("01234567-89AB-CDEF-0123-456789ABCDEF")
} ,
new UserInRole { RoleId = 3
, UserId = new Guid("01234567-89AB-CDEF-0123-456789ABCDEF")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("22222222-2222-2222-2222-222222222222")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("33333333-3333-3333-3333-333333333333")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("44444444-4444-4444-4444-444444444444")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("55555555-5555-5555-5555-555555555555")
} ,
new UserInRole { RoleId = 3
, UserId = new Guid("55555555-5555-5555-5555-555555555555")
} ,
new UserInRole { RoleId = 1
, UserId = new Guid("77777777-7777-7777-7777-777777777777")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("77777777-7777-7777-7777-777777777777")
} ,
new UserInRole { RoleId = 1
, UserId = new Guid("88888888-8888-8888-8888-888888888888")
} ,
new UserInRole { RoleId = 2
, UserId = new Guid("88888888-8888-8888-8888-888888888888")
}
};
ProfileList = new List<Profile>
{
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("01234567-89AB-CDEF-0123-456789ABCDEF")
, Authenticated = true
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "UserName"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("22222222-2222-2222-2222-222222222222")
, Authenticated = true
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "UserName2"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("33333333-3333-3333-3333-333333333333")
, Authenticated = false
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "UserName3"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("44444444-4444-4444-4444-444444444444")
, Authenticated = true
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "UpdateUser"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("55555555-5555-5555-5555-555555555555")
, Authenticated = true
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "LockedOutUser"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("66666666-6666-6666-6666-666666666666")
, Authenticated = true
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "NotApprovedUser"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("77777777-7777-7777-7777-777777777777")
, Authenticated = false
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "RemoveUser1"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
} ,
new Profile { ApplicationName = "Nehemiah"
, UserId = new Guid("88888888-8888-8888-8888-888888888888")
, Authenticated = false
, LastActivityDate = DateTime.UtcNow.AddDays(-8)
, LastUpdateDate = DateTime.UtcNow.AddDays(-8)
, UserName = "RemoveUser2"
, StringProperty = "ABC"
, Int32Property = 1001
, BooleanProperty = false
, DateTimeProperty = new DateTime(2009, 12, 25, 0, 0, 0, DateTimeKind.Utc)
}
};
}
#region - Profile -
public bool Add(string applicationName, Profile profile)
{
ProfileList.Add(profile);
return true;
}
public bool DeleteProfile(string applicationName, string userName)
{
Profile rec = (from p in ProfileList
join u in UserList on p.UserId equals u.UserId
where u.UserName == userName
select p).Single();
ProfileList.Remove(rec);
return true;
}
public bool DeleteProfile(string applicationName, Guid userId)
{
Profile rec = ProfileList.Where(p => p.ApplicationName == applicationName && p.UserId == userId).SingleOrDefault();
ProfileList.Remove(rec);
return true;
}
public bool Save(string applicationName, Profile profile)
{
bool success = true;
Profile rec = ProfileList.Where(p => p.ApplicationName == applicationName && p.UserName == profile.UserName).SingleOrDefault();
if (rec == null)
{
ProfileList.Add(profile);
}
else
{
ProfileList.Remove(rec);
ProfileList.Add(profile);
}
return success;
}
private IQueryable<Profile> Profiles(string applicationName)
{
return ProfileList.Where(p => p.ApplicationName == applicationName).AsQueryable();
}
public Profile GetProfileByUserName(string applicationName, string userName)
{
return Profiles(applicationName).Where(p => p.UserName == userName).SingleOrDefault();
}
public IList<Profile> GetAllProfiles(string applicationName, bool authenticated, DateTime inactiveDate)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.LastActivityDate < inactiveDate).ToList();
}
public IList<Profile> GetProfileList(string applicationName, int index, int pageSize)
{
return Profiles(applicationName).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, bool authenticated, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, DateTime inactiveDate, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.LastActivityDate < inactiveDate).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, bool authenticated, DateTime inactiveDate, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.LastActivityDate < inactiveDate).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, string username, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.UserName.Contains(username)).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, bool authenticated, string username, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.UserName.Contains(username)).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, DateTime inactiveDate, string username, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.LastActivityDate < inactiveDate && p.UserName.Contains(username)).OrderBy(p => p.UserName).ToList();
}
public IList<Profile> GetProfileList(string applicationName, bool authenticated, DateTime inactiveDate, string username, int index, int pageSize)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.LastActivityDate < inactiveDate && p.UserName.Contains(username)).OrderBy(p => p.UserName).ToList();
}
public int NumberOfProfiles(string applicationName)
{
return Profiles(applicationName).Count();
}
public int NumberOfProfiles(string applicationName, bool authenticated)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated).Count();
}
public int NumberOfProfiles(string applicationName, DateTime inactiveDate)
{
return Profiles(applicationName).Where(p => p.LastActivityDate < inactiveDate).Count();
}
public int NumberOfProfiles(string applicationName, bool authenticated, DateTime inactiveDate)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.LastActivityDate < inactiveDate).Count();
}
public int NumberOfProfiles(string applicationName, bool authenticated, string username)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.UserName.Contains(username)).Count();
}
public int NumberOfProfiles(string applicationName, bool authenticated, DateTime inactiveDate, string userName)
{
return Profiles(applicationName).Where(p => p.Authenticated == authenticated && p.LastActivityDate < inactiveDate && p.UserName.Contains(userName)).Count();
}
public int NumberOfProfiles(string applicationName, DateTime inactiveDate, string userName)
{
return Profiles(applicationName).Where(p => p.LastActivityDate < inactiveDate && p.UserName.Contains(userName)).Count();
}
public int NumberOfProfiles(string applicationName, string username)
{
return Profiles(applicationName).Where(p => p.UserName.Contains(username) == true).Count();
}
#endregion
#region - Role -
public bool Add(string applicationName, Role role)
{
RoleList.Add(role);
Role rec = RoleList.Where(r => r.ApplicationName == applicationName && r.RoleName == role.RoleName).SingleOrDefault();
return (rec != null);
}
public bool DeleteRole(string applicationName, string roleName)
{
Role rec = RoleList.Where(u => u.ApplicationName == applicationName && u.RoleName == roleName).SingleOrDefault();
RoleList.Remove(rec);
return true;
}
public bool DeleteRole(Role role)
{
RoleList.Remove(role);
return true;
}
private IQueryable<Role> Roles(string applicationName)
{
return RoleList.Where(u => u.ApplicationName == applicationName).AsQueryable();
}
public IList<Role> GetAllRoles(string applicationName)
{
return Roles(applicationName).OrderBy(r => r.RoleName).ToList();
}
public Role GetRoleByRoleName(string applicationName, string roleName)
{
return Roles(applicationName).Where(u => u.RoleName == roleName).SingleOrDefault();
}
public Role GetRoleByKey(string applicationName, int roleId)
{
return Roles(applicationName).Where(u => u.RoleId == roleId).SingleOrDefault();
}
public IList<Role> GetRoleList(string applicationName, int index, int pageSize)
{
return Roles(applicationName).OrderBy(u => u.RoleName).ToList();
}
public IList<Role> GetRoleListByRoleName(string applicationName, string roleName, int index, int pageSize)
{
return Roles(applicationName).Where(u => u.RoleName.Contains(roleName) || u.RoleName == roleName).OrderBy(u => u.RoleName).ToList();
}
public int NumberOfRoles(string applicationName)
{
return Roles(applicationName).Count();
}
public bool Save(string applicationName, Role role)
{
bool success = true;
Role rec = RoleList.Where(u => u.ApplicationName == applicationName && u.RoleId == role.RoleId).SingleOrDefault();
if (rec == null)
{
RoleList.Add(role);
}
else
{
RoleList.Remove(rec);
RoleList.Add(role);
}
return success;
}
#endregion
#region - User -
public bool Add(string applicationName, User user)
{
UserList.Add(user);
User rec = UserList.Where(u => u.ApplicationName == applicationName && u.UserName == user.UserName).SingleOrDefault();
return (rec != null);
}
public bool DeleteUser(string applicationName, string username)
{
User rec = UserList.Where(u => u.ApplicationName == applicationName && u.UserName == username).SingleOrDefault();
UserList.Remove(rec);
return true;
}
public bool DeleteUser(User user)
{
UserList.Remove(user);
return true;
}
private IQueryable<User> Users(string applicationName)
{
return UserList.Where(u => u.ApplicationName == applicationName).AsQueryable();
}
public IList<User> GetAllUsers(string applicationName)
{
return Users(applicationName).ToList();
}
public User GetUserByEmail(string applicationName, string email)
{
return Users(applicationName).Where(u => u.Email == email).SingleOrDefault();
}
public User GetUserByKey(string applicationName, Guid userId)
{
return Users(applicationName).Where(u => u.UserId == userId).SingleOrDefault();
}
public User GetUserByUserName(string applicationName, string username)
{
return Users(applicationName).Where(u => u.UserName == username).SingleOrDefault();
}
public IList<User> GetUserList(string applicationName, int index, int pageSize)
{
return Users(applicationName).OrderBy(u => u.UserName).ToList();
}
public IList<User> GetUserListByEmail(string applicationName, string email, int index, int pageSize)
{
return Users(applicationName).Where(u => u.Email.Contains(email) || u.Email == email).OrderBy(u => u.Email).ToList();
}
public IList<User> GetUserListByUserName(string applicationName, string username, int index, int pageSize)
{
return Users(applicationName).Where(u => u.UserName.Contains(username) || u.UserName == username).OrderBy(u => u.UserName).ToList();
}
public int NumberOfUsers(string applicationName)
{
return Users(applicationName).Count();
}
public int NumberOfUsersByEmail(string applicationName, string email)
{
return Users(applicationName).Where(u => u.Email.Contains(email)).Count();
}
public int NumberOfUsersByUserName(string applicationName, string userName)
{
return Users(applicationName).Where(u => u.UserName.Contains(userName)).Count();
}
public int NumberOfUsersOnline(string applicationName, int timeWindow)
{
return Users(applicationName).Where(u => u.LastActivityDate >= DateTime.UtcNow.AddMinutes(-1 * timeWindow)).Count();
}
public bool Save(string applicationName, User user)
{
bool success = true;
User rec = UserList.Where(u => u.ApplicationName == applicationName && u.UserId == user.UserId).SingleOrDefault();
if (rec == null)
{
UserList.Add(user);
}
else
{
UserList.Remove(rec);
UserList.Add(user);
}
return success;
}
public IList<User> GetUsersInRole(string applicationName, string rolename)
{
var list = from r in RoleList
join uir in UserInRoleList on r.RoleId equals uir.RoleId
join u in UserList on uir.UserId equals u.UserId
where r.RoleName == rolename
select u;
return list.ToList();
}
public IList<User> GetUsersInRole(string applicationName, string rolename, string username)
{
var list = from r in RoleList
join uir in UserInRoleList on r.RoleId equals uir.RoleId
join u in UserList on uir.UserId equals u.UserId
where r.RoleName == rolename && u.UserName.Contains(username)
select u;
return list.ToList();
}
public bool DeleteUserInRole(string userName, string roleName)
{
var roles = from r in RoleList
join uir in UserInRoleList on r.RoleId equals uir.RoleId
where r.RoleName == roleName
select uir;
foreach (var role in roles)
{
UserInRoleList.Remove(role);
}
return true;
}
#endregion
#region - UserInRole -
private IQueryable<UserInRole> UserInRoles(string applicationName)
{
var list = from r in RoleList
join uir in UserInRoleList on r.RoleId equals uir.RoleId
where r.ApplicationName == applicationName
select uir;
return list.AsQueryable();
}
public int NumberOfUsersInRole(string applicationName, int roleId)
{
return UserInRoles(applicationName).Where(r => r.RoleId == roleId).Count();
}
public int NumberOfUsersInRole(string applicationName, string roleName)
{
return (from r in RoleList
join uir in UserInRoleList on r.RoleId equals uir.RoleId
where r.ApplicationName == applicationName && r.RoleName == roleName
select uir).Count();
//UserInRoles(applicationName).Where(r => r.RoleId == roleId).Count();
}
public IList<Role> GetRolesForUser(string applicationName, Guid userId)
{
var list = from uir in UserInRoles(applicationName)
join r in RoleList on uir.RoleId equals r.RoleId
where uir.UserId == userId
select r;
return list.ToList();
}
public IList<Role> GetRolesForUser(string applicationName, string username)
{
var list = from uir in UserInRoles(applicationName)
join r in RoleList on uir.RoleId equals r.RoleId
join u in UserList on uir.UserId equals u.UserId
where u.UserName == username
select r;
return list.ToList();
}
public bool AddUserToRole(string applicationName, string userName, string roleName)
{
Role role;
User user;
// Cannot add a non-existant user
user = GetUserByUserName(applicationName, userName);
if (user == null)
{
return false;
}
// Cannot add a non-existant role
role = GetRoleByRoleName(applicationName, roleName);
if (role == null)
{
return false;
}
UserInRole userInRole = new UserInRole(user.UserId, role.RoleId);
UserInRoleList.Add(userInRole);
return true;
}
public IList<UserInRole> GetAllUserInRole(string applicationName)
{
var list = from uir in UserInRoles(applicationName)
select uir;
return list.ToList();
}
public bool DeleteUserInRole(UserInRole userInRole)
{
UserInRoleList.Remove(userInRole);
return true;
}
#endregion
} // End Class
} // End Namespace
Thats all for now. Go ahead and check these changes into source control. However, don’t expect the solution to build. There is still a lot of pieces to add to this puzzle.
Previous Articles in this Series
- Part 1, Introduction
- Part 2, Version Control
- Part 3, Automated Builds
- Part 4, BDD with MSpec
- Part 5, Writing Specs
- Part 6, Writing Specs Continued
- Part 7, Custom Web Errors
- Part 8, Adding a Custom Membership Provider
- Part 9, Adding a Custom Role Provider
- Part 10, Adding a Custom Profile Provider
- Part 11, Finishing the Custom Membership Provider
- Part 12, Finishing the Custom Role Provider
- Part 13, Finishing the Custom Profile Provider
- Part 14, Logging Services
- Part 15, Adding Ninject
- Part 16, Fun with NHibernate












