Search Results

Search found 17 results on 1 pages for 'lastactivitydate'.

Page 1/1 | 1 

  • C# asp.net MVC: When to update LastActivityDate?

    - by Oskar Kjellin
    I'm using asp.net mvc and creating a public website. I need to keep track of users that are online. I see that the standard way in asp.net of doing this is to keep track of LastActivityDate. My question is when should I update this? If I update it every time the users clicks somewhere, I will feel a performance draw back. However if I do not do that, people that only surf arround will be listed as offline. What is the best way to do this in asp.net MVC?

    Read the article

  • How to get LastActivityDate when using Active Directory Setup in a .net application

    - by user320587
    Hi, I have a requirement to show a list of all users along with the Last Activity Date. The application is .Net based. I found the MemberShip class provides the Last Activity date. However, this does not work when the MemberShip provider is ActiveDirectory Link to MSDN page because the ActiveDirectoryMemberShipUser does not implement the LastActivityDate property. Is there any workaround or other way, I can get the LastActivityDate of the user in the application. Thanks for any info

    Read the article

  • ASP.NET MVC Inheriting from ProfileBase

    - by Glen
    I have 2 related issues. I inherited from ProfileBase and I have a couple of properites as such public SomeType PropertyName { get { return (SomeType)base["PropertyName"]; } set { base["PropertyName"] = value; Save(); } } I also have a User class (UserId, UserName, Profile, LastActivityDate) that has 2 additional properties out of the profile that I retrieve in my View to show a list of Users (i.e. @Model.Profile.PropertyName). However, everytime I access a property (from my View) it seems to update the LastActivityDate in the aspnet_Users table because when I show the LastActivityDate as well as the profile properties on my screen the LastActivtyDate is out of sync with the database. Also there is a LastActivityDate property available in my profile which unfortunately is not available and is in fact set to null and throws an exception when accessing it saying the property UserName is null. So the static Create method provided by ProfileBase seems to retrieve the correct profile properties but does not set the base's UserName property even though you pass in a UserName parameter to the Create method. Is this a internal bug? I was kind of hoping if by accessing the property because the LastActivityDate is updated then I could store that value to update my LastActivityDate in my User class before it is rendered to the page. The only way I can think of doing it is: public SomeType PropertyName { get { SomeType result = (SomeType)base["PropertyName"]; OnLastActivityDateChanged(); return result; } set { base["PropertyName"] = value; } } then in my User class: ... public MyProfile() { Profile.LastActivityDateChanged += Profile_LastActivityDateChanged(); } ~MyProfile() { Profile.LastActivityDateChanged -= Profile_LastActivityDateChanged(); } ... void Profile_LastActivityDateChanged(object sender, EventArgs e) { //Run a query to get the latest LastActivityDate this.LastActivityDate = ... } It seems I have to make 1 call to retrieve the full list to my aspnet_Users table then another call for each row just to get the latest activity date. ARGGGGHHH!!! Am I going about this the wrong way! I put an ajax refresh hyperlink next to each User row and when I click it, immediately after loading the page, the value changes. Therefore my suspision is valid that calling a property via the inherited profilebase class updates the value. Is there a workaround? It is a bit miss leading when my page says User Smith has no activity for 4 days then I click my ajax refresh link (or refresh the whole page for that matter) and now it says Smith was active but it was just me meally showing the page that indirectly caused an activity read event.

    Read the article

  • Profile System: User share the same id

    - by Malcolm Frexner
    I have a strange effect on my site when it is under heavy load. I randomly get the properties of other users settings. I have my own implementation of the profile system so I guess I can not blame the profile system itself. I just need a point to start debugging from. I guess there is a cookie-value that maps to an Profile entry somewhere. Is there any chance to see how this mapping works? Here is my profile provider: using System; using System.Text; using System.Configuration; using System.Web; using System.Web.Profile; using System.Collections; using System.Collections.Specialized; using B2CShop.Model; using log4net; using System.Collections.Generic; using System.Diagnostics; using B2CShop.DAL; using B2CShop.Model.RepositoryInterfaces; [assembly: log4net.Config.XmlConfigurator()] namespace B2CShop.Profile { public class B2CShopProfileProvider : ProfileProvider { private static readonly ILog _log = LogManager.GetLogger(typeof(B2CShopProfileProvider)); // Get an instance of the Profile DAL using the ProfileDALFactory private static readonly B2CShop.DAL.UserRepository dal = new B2CShop.DAL.UserRepository(); // Private members private const string ERR_INVALID_PARAMETER = "Invalid Profile parameter:"; private const string PROFILE_USER = "User"; private static string applicationName = B2CShop.Model.Configuration.ApplicationConfiguration.MembershipApplicationName; /// <summary> /// The name of the application using the custom profile provider. /// </summary> public override string ApplicationName { get { return applicationName; } set { applicationName = value; } } /// <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> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "B2C Shop Custom Provider"); } if (string.IsNullOrEmpty(name)) name = "b2c_shop"; if (config["applicationName"] != null && !string.IsNullOrEmpty(config["applicationName"].Trim())) applicationName = config["applicationName"]; base.Initialize(name, config); } /// <summary> /// Returns the collection of settings property values for the specified application instance and settings property group. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application use.</param> /// <param name="collection">A System.Configuration.SettingsPropertyCollection containing the settings property group whose values are to be retrieved.</param> /// <returns>A System.Configuration.SettingsPropertyValueCollection containing the values for the specified settings property group.</returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { string username = (string)context["UserName"]; bool isAuthenticated = (bool)context["IsAuthenticated"]; //if (!isAuthenticated) return null; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection(); foreach (SettingsProperty prop in collection) { SettingsPropertyValue pv = new SettingsPropertyValue(prop); switch (pv.Property.Name) { case PROFILE_USER: if (!String.IsNullOrEmpty(username)) { pv.PropertyValue = GetUser(uniqueID); } break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } svc.Add(pv); } return svc; } /// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application usage.</param> /// <param name="collection">A System.Configuration.SettingsPropertyValueCollection representing the group of property settings to set.</param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string username = (string)context["UserName"]; CheckUserName(username); bool isAuthenticated = (bool)context["IsAuthenticated"]; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); if (uniqueID == 0) { uniqueID = dal.CreateProfileForUser(username, isAuthenticated, ApplicationName); } foreach (SettingsPropertyValue pv in collection) { if (pv.PropertyValue != null) { switch (pv.Property.Name) { case PROFILE_USER: SetUser(uniqueID, (UserInfo)pv.PropertyValue); break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } } } UpdateActivityDates(username, false); } // Profile gettters // Retrieve UserInfo private static UserInfo GetUser(int userID) { return dal.GetUser(userID); } // Update account info private static void SetUser(int uniqueID, UserInfo user) { user.UserID = uniqueID; dal.SetUser(user); } // UpdateActivityDates // Updates the LastActivityDate and LastUpdatedDate values // when profile properties are accessed by the // GetPropertyValues and SetPropertyValues methods. // Passing true as the activityOnly parameter will update // only the LastActivityDate. private static void UpdateActivityDates(string username, bool activityOnly) { dal.UpdateActivityDates(username, activityOnly, applicationName); } /// <summary> /// Deletes profile properties and information for the supplied list of profiles. /// </summary> /// <param name="profiles">A 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) { int deleteCount = 0; foreach (ProfileInfo p in profiles) if (DeleteProfile(p.UserName)) deleteCount++; return deleteCount; } /// <summary> /// 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) { int deleteCount = 0; foreach (string user in usernames) if (DeleteProfile(user)) deleteCount++; return deleteCount; } // DeleteProfile // Deletes profile data from the database for the specified user name. private static bool DeleteProfile(string username) { CheckUserName(username); return dal.DeleteAnonymousProfile(username, applicationName); } // Verifies user name for sise and comma private static void CheckUserName(string userName) { if (string.IsNullOrEmpty(userName) || userName.Length > 256 || userName.IndexOf(",") > 0) throw new ApplicationException(ERR_INVALID_PARAMETER + " user name."); } /// <summary> /// 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 System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are deleted.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the 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) { string[] userArray = new string[0]; dal.GetInactiveProfiles((int)authenticationOption, userInactiveSinceDate, ApplicationName).CopyTo(userArray, 0); return DeleteProfiles(userArray); } /// <summary> /// Retrieves profile information for profiles in which the user name matches the specified user names. /// </summary> /// <param name="authenticationOption">One of the 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 System.Web.Profile.ProfileInfoCollection containing user-profile information // for profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// 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 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 System.DateTime that identifies which user profiles are considered inactive. If the 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 System.Web.Profile.ProfileInfoCollection containing user profile information for inactive profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves user profile data for all profiles in the data source. /// </summary> /// <param name="authenticationOption">One of the 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 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) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// 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 System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the 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 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) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// 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 System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the 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) { int inactiveProfiles = 0; ProfileInfoCollection profiles = GetProfileInfo(authenticationOption, null, userInactiveSinceDate, 0, 0, out inactiveProfiles); return inactiveProfiles; } //Verifies input parameters for page size and page index. private static void CheckParameters(int pageIndex, int pageSize) { if (pageIndex < 1 || pageSize < 1) throw new ApplicationException(ERR_INVALID_PARAMETER + " page index."); } //GetProfileInfo //Retrieves a count of profiles and creates a //ProfileInfoCollection from the profile data in the //database. Called by GetAllProfiles, GetAllInactiveProfiles, //FindProfilesByUserName, FindInactiveProfilesByUserName, //and GetNumberOfInactiveProfiles. //Specifying a pageIndex of 0 retrieves a count of the results only. private static ProfileInfoCollection GetProfileInfo(ProfileAuthenticationOption authenticationOption, string usernameToMatch, object userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { ProfileInfoCollection profiles = new ProfileInfoCollection(); totalRecords = 0; // Count profiles only. if (pageSize == 0) return profiles; int counter = 0; int startIndex = pageSize * (pageIndex - 1); int endIndex = startIndex + pageSize - 1; DateTime dt = new DateTime(1900, 1, 1); if (userInactiveSinceDate != null) dt = (DateTime)userInactiveSinceDate; /* foreach(CustomProfileInfo profile in dal.GetProfileInfo((int)authenticationOption, usernameToMatch, dt, applicationName, out totalRecords)) { if(counter >= startIndex) { ProfileInfo p = new ProfileInfo(profile.UserName, profile.IsAnonymous, profile.LastActivityDate, profile.LastUpdatedDate, 0); profiles.Add(p); } if(counter >= endIndex) { break; } counter++; } */ return profiles; } } } This is how I use it in the controller: public ActionResult AddTyreToCart(CartViewModel model) { string profile = Request.IsAuthenticated ? Request.AnonymousID : User.Identity.Name; } I would like to debug: How can 2 users who provide different cookies get the same profileid? EDIT Here is the code for getuniqueid public int GetUniqueID(string userName, bool isAuthenticated, bool ignoreAuthenticationType, string appName) { SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = userName; parms[1].Value = appName; if (!ignoreAuthenticationType) { Array.Resize(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit) { Value = !isAuthenticated }; } int userID; object retVal = null; retVal = SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["SQLOrderB2CConnString"].ConnectionString, CommandType.StoredProcedure, "getProfileUniqueID", parms); if (retVal == null) userID = CreateProfileForUser(userName, isAuthenticated, appName); else userID = Convert.ToInt32(retVal); return userID; } And this is the SP: CREATE PROCEDURE [dbo].[getProfileUniqueID] @Username VarChar( 256), @ApplicationName VarChar( 256), @IsAnonymous bit = null AS BEGIN SET NOCOUNT ON; /* [getProfileUniqueID] created 08.07.2009 mf Retrive unique id for current user */ SELECT UniqueID FROM dbo.Profiles WHERE Username = @Username AND ApplicationName = @ApplicationName AND IsAnonymous = @IsAnonymous or @IsAnonymous = null END

    Read the article

  • How to pass a variable through url and use it inside a controller

    - by anthonypliu
    I have this controller: public ActionResult Details(String UserName) { using (var db = new MatchGamingEntities()) { var Users = from m in db.Users join m2 in db.MyProfiles on m.UserId equals m2.UserId where m.UserName == UserName select new UserViewModel { UserName = m.UserName, LastActivityDate = m.LastActivityDate, Address = m2.Address, City = m2.City, State = m2.State, Zip = m2.Zip }; return View(Users.SingleOrDefault()); } } I type in the url Profiles/Details/hello, but it does not work, if I do Profiles/Details?UserName=hello then it works. I have another ActionResult just like this except taking in an int id as parameter and it works fine with the first url format.

    Read the article

  • List of Users and Role using Membership Provider

    - by Jemes
    I’m trying to produce a view to show a list of users and their role using the built in membership provider. My model and controller are picking up the users and roles but I’m having trouble displaying them in my view. Model public class AdminViewModel { public MembershipUserCollection Users { get; set; } public string[] Roles { get; set; } } Controller public ActionResult Admin() { AdminViewModel viewModel = new AdminViewModel { Users = MembershipService.GetAllUsers(), Roles = RoleService.GetRoles() }; return View(viewModel); } View Inherits="System.Web.Mvc.ViewPage<IEnumerable<Account.Models.AdminViewModel>>" <table> <tr> <td>UserName</td> <td>Email</td> <td>IsOnline</td> <td>CreationDate</td> <td>LastLoginDate</td> <td>LastActivityDate</td> </tr> <% foreach (var item in Model) { %> <tr> <td><%=item.UserName %></td> <td><%=item.Email %></td> <td><%=item.IsOnline %></td> <td><%=item.CreationDate %></td> <td><%=item.LastLoginDate %></td> <td><%=item.LastActivityDate %></td> <td><%=item.ROLE %></td> </tr> <% }%> </table>

    Read the article

  • ASP.NET MVC2 custom rolemanager (webconfig problem)

    - by ile
    Structure of the web: SAMembershipProvider.cs namespace User.Membership { public class SAMembershipProvider : MembershipProvider { #region - Properties - private int NewPasswordLength { get; set; } private string ConnectionString { get; set; } //private MachineKeySection MachineKey { get; set; } //Used when determining encryption key values. public bool enablePasswordReset { get; set; } public bool enablePasswordRetrieval { get; set; } public bool requiresQuestionAndAnswer { get; set; } public bool requiresUniqueEmail { get; set; } public int maxInvalidPasswordAttempts { get; set; } public int passwordAttemptWindow { get; set; } public MembershipPasswordFormat passwordFormat { get; set; } public int minRequiredNonAlphanumericCharacters { get; set; } public int minRequiredPasswordLength { get; set; } public string passwordStrengthRegularExpression { get; set; } public override string ApplicationName { get; set; } // Indicates whether passwords can be retrieved using the provider's GetPassword method. // This property is read-only. public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } // Indicates whether passwords can be reset using the provider's ResetPassword method. // This property is read-only. public override bool EnablePasswordReset { get { return enablePasswordReset; } } // Indicates whether a password answer must be supplied when calling the provider's GetPassword and ResetPassword methods. // This property is read-only. public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } // For a description, see MaxInvalidPasswordAttempts. // This property is read-only. public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } // Indicates whether each registered user must have a unique e-mail address. // This property is read-only. public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } // The minimum number of characters required in a password. // This property is read-only. public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } // The minimum number of non-alphanumeric characters required in a password. // This property is read-only. public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } // A regular expression specifying a pattern to which passwords must conform. // This property is read-only. public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } #endregion #region - Methods - public override void Initialize(string name, NameValueCollection config) { throw new NotImplementedException(); } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } // Takes, as input, a user name, password, e-mail address, and other information and adds a new user // to the membership data source. CreateUser returns a MembershipUser object representing the newly // created user. It also accepts an out parameter (in Visual Basic, ByRef) that returns a // MembershipCreateStatus value indicating whether the user was successfully created or, if the user // was not created, the reason why. If the user was not created, CreateUser returns null. // Before creating a new user, CreateUser calls the provider's virtual OnValidatingPassword method to // validate the supplied password. It then creates the user or cancels the action based on the outcome of the call. public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } // Returns a MembershipUserCollection containing MembershipUser objects representing users whose user names // match the usernameToMatch input parameter. Wildcard syntax is data source-dependent. MembershipUser objects // in the MembershipUserCollection are sorted by user name. If FindUsersByName finds no matching users, it // returns an empty MembershipUserCollection. // For an explanation of the pageIndex, pageSize, and totalRecords parameters, see the GetAllUsers method. public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } // Returns a MembershipUserCollection containing MembershipUser objects representing all registered users. If // there are no registered users, GetAllUsers returns an empty MembershipUserCollection // The results returned by GetAllUsers are constrained by the pageIndex and pageSize input parameters. pageSize // specifies the maximum number of MembershipUser objects to return. pageIndex identifies which page of results // to return. Page indexes are 0-based. // // GetAllUsers also takes an out parameter (in Visual Basic, ByRef) named totalRecords that, on return, holds // a count of all registered users. public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } // Returns a count of users that are currently online-that is, whose LastActivityDate is greater than the current // date and time minus the value of the membership service's UserIsOnlineTimeWindow property, which can be read // from Membership.UserIsOnlineTimeWindow. UserIsOnlineTimeWindow specifies a time in minutes and is set using // the <membership> element's userIsOnlineTimeWindow attribute. public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } // Takes, as input, a user name and a password answer and returns that user's password. If the user name is not // valid, GetPassword throws a ProviderException. // Before retrieving a password, GetPassword verifies that EnablePasswordRetrieval is true. If // EnablePasswordRetrieval is false, GetPassword throws a NotSupportedException. If EnablePasswordRetrieval is // true but the password format is hashed, GetPassword throws a ProviderException since hashed passwords cannot, // by definition, be retrieved. A membership provider should also throw a ProviderException from Initialize if // EnablePasswordRetrieval is true but the password format is hashed. // // GetPassword also checks the value of the RequiresQuestionAndAnswer property before retrieving a password. If // RequiresQuestionAndAnswer is true, GetPassword compares the supplied password answer to the stored password // answer and throws a MembershipPasswordException if the two don't match. GetPassword also throws a // MembershipPasswordException if the user whose password is being retrieved is currently locked out. public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } // Takes, as input, a user name or user ID (the method is overloaded) and a Boolean value indicating whether // to update the user's LastActivityDate to show that the user is currently online. GetUser returns a MembershipUser // object representing the specified user. If the user name or user ID is invalid (that is, if it doesn't represent // a registered user) GetUser returns null (Nothing in Visual Basic). public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } // Takes, as input, a user name or user ID (the method is overloaded) and a Boolean value indicating whether to // update the user's LastActivityDate to show that the user is currently online. GetUser returns a MembershipUser // object representing the specified user. If the user name or user ID is invalid (that is, if it doesn't represent // a registered user) GetUser returns null (Nothing in Visual Basic). public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } // Takes, as input, an e-mail address and returns the first registered user name whose e-mail address matches the // one supplied. // If it doesn't find a user with a matching e-mail address, GetUserNameByEmail returns an empty string. public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } // Virtual method called when a password is created. The default implementation in MembershipProvider fires a // ValidatingPassword event, so be sure to call the base class's OnValidatingPassword method if you override // this method. The ValidatingPassword event allows applications to apply additional tests to passwords by // registering event handlers. // A custom provider's CreateUser, ChangePassword, and ResetPassword methods (in short, all methods that record // new passwords) should call this method. protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { base.OnValidatingPassword(e); } // Takes, as input, a user name and a password answer and replaces the user's current password with a new, random // password. ResetPassword then returns the new password. A convenient mechanism for generating a random password // is the Membership.GeneratePassword method. // If the user name is not valid, ResetPassword throws a ProviderException. ResetPassword also checks the value of // the RequiresQuestionAndAnswer property before resetting a password. If RequiresQuestionAndAnswer is true, // ResetPassword compares the supplied password answer to the stored password answer and throws a // MembershipPasswordException if the two don't match. // // Before resetting a password, ResetPassword verifies that EnablePasswordReset is true. If EnablePasswordReset is // false, ResetPassword throws a NotSupportedException. If the user whose password is being changed is currently // locked out, ResetPassword throws a MembershipPasswordException. // // Before resetting a password, ResetPassword calls the provider's virtual OnValidatingPassword method to validate // the new password. It then resets the password or cancels the action based on the outcome of the call. If the new // password is invalid, ResetPassword throws a ProviderException. // // Following a successful password reset, ResetPassword updates the user's LastPasswordChangedDate. public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } // Unlocks (that is, restores login privileges for) the specified user. UnlockUser returns true if the user is // successfully unlocked. Otherwise, it returns false. If the user is already unlocked, UnlockUser simply returns true. public override bool UnlockUser(string userName) { throw new NotImplementedException(); } // Takes, as input, a MembershipUser object representing a registered user and updates the information stored for // that user in the membership data source. If any of the input submitted in the MembershipUser object is not valid, // UpdateUser throws a ProviderException. // Note that UpdateUser is not obligated to allow all the data that can be encapsulated in a MembershipUser object to // be updated in the data source. public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } // Takes, as input, a user name and a password and verifies that they are valid-that is, that the membership data // source contains a matching user name and password. ValidateUser returns true if the user name and password are // valid, if the user is approved (that is, if MembershipUser.IsApproved is true), and if the user isn't currently // locked out. Otherwise, it returns false. // Following a successful validation, ValidateUser updates the user's LastLoginDate and fires an // AuditMembershipAuthenticationSuccess Web event. Following a failed validation, it fires an // // AuditMembershipAuthenticationFailure Web event. public override bool ValidateUser(string username, string password) { throw new NotImplementedException(); //if (string.IsNullOrEmpty(password.Trim())) return false; //string hash = EncryptPassword(password); //User user = _repository.GetByUserName(username); //if (user == null) return false; //if (user.Password == hash) //{ // User = user; // return true; //} //return false; } #endregion /// <summary> /// Procuses an MD5 hash string of the password /// </summary> /// <param name="password">password to hash</param> /// <returns>MD5 Hash string</returns> protected string EncryptPassword(string password) { //we use codepage 1252 because that is what sql server uses byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password); byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes); return Encoding.GetEncoding(1252).GetString(hashBytes); } } // End Class } SARoleProvider.cs namespace User.Membership { public class SARoleProvider : RoleProvider { #region - Properties - // The name of the application using the role provider. ApplicationName is used to scope // role data so that applications can choose whether to share role data with other applications. // This property can be read and written. public override string ApplicationName { get; set; } #endregion #region - Methods - public override void Initialize(string name, NameValueCollection config) { throw new NotImplementedException(); } // Takes, as input, a list of user names and a list of role names and adds the specified users to // the specified roles. // AddUsersToRoles throws a ProviderException if any of the user names or role names do not exist. // If any user name or role name is null (Nothing in Visual Basic), AddUsersToRoles throws an // ArgumentNullException. If any user name or role name is an empty string, AddUsersToRoles throws // an ArgumentException. public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } // Takes, as input, a role name and creates the specified role. // CreateRole throws a ProviderException if the role already exists, the role name contains a comma, // or the role name exceeds the maximum length allowed by the data source. public override void CreateRole(string roleName) { throw new NotImplementedException(); } // Takes, as input, a role name and a Boolean value that indicates whether to throw an exception if there // are users currently associated with the role, and then deletes the specified role. // If the throwOnPopulatedRole input parameter is true and the specified role has one or more members, // DeleteRole throws a ProviderException and does not delete the role. If throwOnPopulatedRole is false, // DeleteRole deletes the role whether it is empty or not. // // When DeleteRole deletes a role and there are users assigned to that role, it also removes users from the role. public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } // Takes, as input, a search pattern and a role name and returns a list of users belonging to the specified role // whose user names match the pattern. Wildcard syntax is data-source-dependent and may vary from provider to // provider. User names are returned in alphabetical order. // If the search finds no matches, FindUsersInRole returns an empty string array (a string array with no elements). // If the role does not exist, FindUsersInRole throws a ProviderException. public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } // Returns the names of all existing roles. If no roles exist, GetAllRoles returns an empty string array (a string // array with no elements). public override string[] GetAllRoles() { throw new NotImplementedException(); } // Takes, as input, a user name and returns the names of the roles to which the user belongs. // If the user is not assigned to any roles, GetRolesForUser returns an empty string array // (a string array with no elements). If the user name does not exist, GetRolesForUser throws a // ProviderException. public override string[] GetRolesForUser(string username) { throw new NotImplementedException(); //User user = _repository.GetByUserName(username); //string[] roles = new string[user.Role.Rights.Count + 1]; //roles[0] = user.Role.Description; //int idx = 0; //foreach (Right right in user.Role.Rights) // roles[++idx] = right.Description; //return roles; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } // Takes, as input, a role name and returns the names of all users assigned to that role. // If no users are associated with the specified role, GetUserInRole returns an empty string array (a string array with // no elements). If the role does not exist, GetUsersInRole throws a ProviderException. public override bool IsUserInRole(string username, string roleName) { throw new NotImplementedException(); //User user = _repository.GetByUserName(username); //if (user != null) // return user.IsInRole(roleName); //else // return false; } // Takes, as input, a list of user names and a list of role names and removes the specified users from the specified roles. // RemoveUsersFromRoles throws a ProviderException if any of the users or roles do not exist, or if any user specified // in the call does not belong to the role from which he or she is being removed. public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } // Takes, as input, a role name and determines whether the role exists. public override bool RoleExists(string roleName) { throw new NotImplementedException(); } #endregion } // End Class } From Web.config: <membership defaultProvider="SAMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="SAMembershipProvider" type="User.Membership.SAMembershipProvider, User" /> </providers> </membership> <roleManager defaultProvider="SARoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="SARoleProvider" type="User.Membership.SARoleProvider" /> </providers> </roleManager> When running project, I get following error: Server Error in '/' Application. Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: The method or operation is not implemented. Source Error: Line 71: <providers> Line 72: <clear/> Line 73: <add name="SARoleProvider" type="User.Membership.SARoleProvider" /> Line 74: </providers> Line 75: </roleManager> I tried: <add name="SARoleProvider" type="User.Membership.SARoleProvider, User" /> and <add name="SARoleProvider" type="User.Membership.SARoleProvider, SARoleProvider" /> and <add name="SARoleProvider" type="User.Membership.SARoleProvider, User.Membership" /> but none works Any idea what's wrong here? Thanks, Ile

    Read the article

  • Passing a string in Html.ActionLink in MVC 2

    - by 109221793
    I have completed the MVC Music Store application, and now am making my own modifications for practice, and also to prepare me to do similar tasks in my job. What I have done, is create a view that displays the current list of users. I have done this as I want to be able to change the passwords of users should they forget them. Here is a snippet from my view: <% foreach (MembershipUser user in Model) { %> <tr> <td><%: Html.ActionLink(user.UserName, "changeUserPassword", "StoreManager", new { username = user.UserName }) %></td> <td><%: user.LastActivityDate %></td> <td><%: user.IsLockedOut %></td> </tr> <% }%> What I want to know, is it possible to pass the username through the actionlink as I have done above. I have registered the following route in the global.asax.cs file, however I am unsure if I have done it correctly: routes.MapRoute( "AdminPassword", //Route name "{controller}/{action}/{username}", //URL with parameters new { controller = "StoreManager", action = "changeUserPassword", username = UrlParameter.Optional }); Here is my GET action: public ActionResult changeUserPassword(string username) { ViewData["username"] = username; return View(); } I have debugged through the code to find that ViewData["username"] = username doesn't populate so it looks like either I have not registered the routes properly, or I simply cannot pass the username using the actionlink like I have. I'd be grateful if someone could point me in the right direction.

    Read the article

  • Establishing Upper / Lower Bound in T-SQL Procedure

    - by Code Sherpa
    Hi. I am trying to establish upper / lower bound in my stored procedure below and am having some problems at the end (I am getting no results where, without the temp table inner join i get the expected results). I need some help where I am trying to join the columns in my temp table #PageIndexForUsers to the rest of my join statement and I am mucking something up with this statement: INNER JOIN #PageIndexForUsers ON ( dbo.aspnet_Users.UserId = #PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= @PageLowerBound AND #PageIndexForUsers.IndexId <= @PageUpperBound ) I could use feedback at this point - and, any advice on how to improve my procedure's logic (if you see anything else that needs improvement) is also appreciated. Thanks in advance... ALTER PROCEDURE dbo.wb_Membership_GetAllUsers @ApplicationName nvarchar(256), @sortOrderId smallint = 0, @PageIndex int, @PageSize int AS BEGIN DECLARE @ApplicationId uniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName IF (@ApplicationId IS NULL) RETURN 0 -- Set the page bounds DECLARE @PageLowerBound int DECLARE @PageUpperBound int DECLARE @TotalRecords int SET @PageLowerBound = @PageSize * @PageIndex SET @PageUpperBound = @PageSize - 1 + @PageLowerBound BEGIN TRY -- Create a temp table TO store the select results CREATE TABLE #PageIndexForUsers ( IndexId int IDENTITY (0, 1) NOT NULL, UserId uniqueidentifier ) -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Membership m, dbo.aspnet_Users u WHERE u.ApplicationId = @ApplicationId AND u.UserId = m.UserId ORDER BY u.UserName SELECT @TotalRecords = @@ROWCOUNT SELECT dbo.wb_Profiles.profileid, dbo.wb_ProfileData.firstname, dbo.wb_ProfileData.lastname, dbo.wb_Email.emailaddress, dbo.wb_Email.isconfirmed, dbo.wb_Email.emaildomain, dbo.wb_Address.streetname, dbo.wb_Address.cityorprovince, dbo.wb_Address.state, dbo.wb_Address.postalorzip, dbo.wb_Address.country, dbo.wb_ProfileAddress.addresstype,dbo.wb_ProfileData.birthday, dbo.wb_ProfileData.gender, dbo.wb_Session.sessionid, dbo.wb_Session.lastactivitydate, dbo.aspnet_Membership.userid, dbo.aspnet_Membership.password, dbo.aspnet_Membership.passwordquestion, dbo.aspnet_Membership.passwordanswer, dbo.aspnet_Membership.createdate FROM dbo.wb_Profiles INNER JOIN dbo.wb_ProfileAddress ON ( dbo.wb_Profiles.profileid = dbo.wb_ProfileAddress.profileid AND dbo.wb_ProfileAddress.addresstype = 'home' ) INNER JOIN dbo.wb_Address ON dbo.wb_ProfileAddress.addressid = dbo.wb_Address.addressid INNER JOIN dbo.wb_ProfileData ON dbo.wb_Profiles.profileid = dbo.wb_ProfileData.profileid INNER JOIN dbo.wb_Email ON ( dbo.wb_Profiles.profileid = dbo.wb_Email.profileid AND dbo.wb_Email.isprimary = 1 ) INNER JOIN dbo.wb_Session ON dbo.wb_Profiles.profileid = dbo.wb_Session.profileid INNER JOIN dbo.aspnet_Membership ON dbo.wb_Profiles.userid = dbo.aspnet_Membership.userid INNER JOIN dbo.aspnet_Users ON dbo.aspnet_Membership.UserId = dbo.aspnet_Users.UserId INNER JOIN dbo.aspnet_Applications ON dbo.aspnet_Users.ApplicationId = dbo.aspnet_Applications.ApplicationId INNER JOIN #PageIndexForUsers ON ( dbo.aspnet_Users.UserId = #PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= @PageLowerBound AND #PageIndexForUsers.IndexId <= @PageUpperBound ) ORDER BY CASE @sortOrderId WHEN 1 THEN dbo.wb_ProfileData.lastname WHEN 2 THEN dbo.wb_Profiles.username WHEN 3 THEN dbo.wb_Address.postalorzip WHEN 4 THEN dbo.wb_Address.state END END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRAN EXEC wb_ErrorHandler RETURN 55555 END CATCH RETURN @TotalRecords END GO

    Read the article

  • "requiresuniqueemail=true" implementation in asp.net site

    - by domineer
    Hi people I got a social networking site that is running live right now.The first time I launched my site I let requiresuniqueemail=false set-up on my web.config inorder for me to create dummy accounts for testing purposes and to start up the site you know.However the site is kind of stable right now w/ almost 5k members.So I would like to set-up the requiresuniqueemail to true so that users cannot reuse their existing email address and for me to make it sure that there will be unique email ad for each site user.I know the site got like 100 users with the same email address.My question is what could be the problem I'm going to face if I do this right now(requiresuniqueemail="true") and how to do this efficiently(without errors and if possible sitewide say in the global assax)?I tested and I already got an error if I logout an account.Like say a user try to click log-out this code runs: Dim d As DateTime = DateTime.Now.AddMinutes(-1 * Membership.UserIsOnlineTimeWindow) Dim theuser As MembershipUser = Membership.GetUser() theuser.LastActivityDate = d Membership.UpdateUser(theuser) If Not Cache(Page.User.Identity.Name.ToLower() + "currentstatus") Is Nothing Then Cache.Remove(Page.User.Identity.Name.ToLower() + "currentstatus") End If Then an exception occured on updateuser() function saying System.Configuration.Provider.ProviderException: The E-mail supplied is invalid. This is just one instance I know that I encountered a problem. Hoping to hear your ideas guys.....

    Read the article

  • ASP.NET MVC3 Custom Membership Provider - The membership provider name specified is invalid.

    - by David Lively
    I'm implementing a custom membership provider, and everything seems to go swimmingly until I create a MembershipUser object. At that point, I receive the error: The membership provider name specified is invalid. Parameter name: providerName In web.config the membership key is <membership defaultProvider="MembersProvider"> <providers> <clear/> <add name="MembersProvider" type="Members.Providers.MembersProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="DeviceDatabase" /> </providers> </membership> When creating the MembershipUser object from my custom User class: public static MembershipUser ToMembershipUser(User user) { MembershipUser member = new MembershipUser ("MembersProvider" , user.Name , user.Id , user.EmailAddress , user.PasswordQuestion , user.Comment , user.IsApproved , user.IsLockedOut , user.DateCreated , user.LastLoginDate ?? DateTime.MinValue , user.LastActivityDate ?? DateTime.MinValue , user.LastPasswordChangedDate ?? DateTime.MinValue , user.LastLockoutDate ?? DateTime.MinValue ); return member; } (I realize I could probably just inherit my User class from MembershipUser, but it's already part of an existing class hierarchy. I honestly think this is the first time I've encountered a legitimate need for for multiple inheritance!) My feeling is that the new MembershipUser(...) providerName parameter is supposed to match what's set in web.config, but, since they match already, I'm at a loss as to how to proceed. Is there a convenient way to get the name of the active membership provider in code? I'm starting to think that using the built-in membership system is overkill and more trouble than it's worth. Edit Not sure if it's relevant, but the custom membership provider class is in a class library, not the main WAP project. Update Here's the contents of the System.Web.Security.Membership.Provider object as show in the VS2010 command window: >eval System.Web.Security.Membership.Provider {Members.Providers.MembersProvider} [Members.Providers.MembersProvider]: {Members.Providers.MembersProvider} base {System.Configuration.Provider.ProviderBase}: {Members.Providers.MembersProvider} ApplicationName: null EnablePasswordReset: true EnablePasswordRetrieval: false MaxInvalidPasswordAttempts: 5 MinRequiredNonAlphanumericCharacters: 0 MinRequiredPasswordLength: 6 PasswordAttemptWindow: 10 PasswordFormat: Function evaluation was aborted. PasswordStrengthRegularExpression: Cannot evaluate expression because debugging information has been optimized away . RequiresQuestionAndAnswer: Cannot evaluate expression because debugging information has been optimized away . RequiresUniqueEmail: Cannot evaluate expression because debugging information has been optimized away .

    Read the article

  • Many-To-Many Query with Linq-To-NHibernate

    - by rjygraham
    Ok guys (and gals), this one has been driving me nuts all night and I'm turning to your collective wisdom for help. I'm using Fluent Nhibernate and Linq-To-NHibernate as my data access story and I have the following simplified DB structure: CREATE TABLE [dbo].[Classes]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](100) NOT NULL, [StartDate] [datetime2](7) NOT NULL, [EndDate] [datetime2](7) NOT NULL, CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED ( [Id] ASC ) CREATE TABLE [dbo].[Sections]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [ClassId] [bigint] NOT NULL, [InternalCode] [varchar](10) NOT NULL, CONSTRAINT [PK_Sections] PRIMARY KEY CLUSTERED ( [Id] ASC ) CREATE TABLE [dbo].[SectionStudents]( [SectionId] [bigint] NOT NULL, [UserId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_SectionStudents] PRIMARY KEY CLUSTERED ( [SectionId] ASC, [UserId] ASC ) CREATE TABLE [dbo].[aspnet_Users]( [ApplicationId] [uniqueidentifier] NOT NULL, [UserId] [uniqueidentifier] NOT NULL, [UserName] [nvarchar](256) NOT NULL, [LoweredUserName] [nvarchar](256) NOT NULL, [MobileAlias] [nvarchar](16) NULL, [IsAnonymous] [bit] NOT NULL, [LastActivityDate] [datetime] NOT NULL, PRIMARY KEY NONCLUSTERED ( [UserId] ASC ) I omitted the foreign keys for brevity, but essentially this boils down to: A Class can have many Sections. A Section can belong to only 1 Class but can have many Students. A Student (aspnet_Users) can belong to many Sections. I've setup the corresponding Model classes and Fluent NHibernate Mapping classes, all that is working fine. Here's where I'm getting stuck. I need to write a query which will return the sections a student is enrolled in based on the student's UserId and the dates of the class. Here's what I've tried so far: 1. var sections = (from s in this.Session.Linq<Sections>() where s.Class.StartDate <= DateTime.UtcNow && s.Class.EndDate > DateTime.UtcNow && s.Students.First(f => f.UserId == userId) != null select s); 2. var sections = (from s in this.Session.Linq<Sections>() where s.Class.StartDate <= DateTime.UtcNow && s.Class.EndDate > DateTime.UtcNow && s.Students.Where(w => w.UserId == userId).FirstOrDefault().Id == userId select s); Obviously, 2 above will fail miserably if there are no students matching userId for classes the current date between it's start and end dates...but I just wanted to try. The filters for the Class StartDate and EndDate work fine, but the many-to-many relation with Students is proving to be difficult. Everytime I try running the query I get an ArgumentNullException with the message: Value cannot be null. Parameter name: session I've considered going down the path of making the SectionStudents relation a Model class with a reference to Section and a reference to Student instead of a many-to-many. I'd like to avoid that if I can, and I'm not even sure it would work that way. Thanks in advance to anyone who can help. Ryan

    Read the article

  • Instance Failure in asp.net

    - by user85511
    I have a web application that is working perfectly in my system. However, when I copied it to another system, I couldn't login to the application. There is an error: Server Error in '/' Application. -------------------------------------------------------------------------------- Instance failure. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Instance failure. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOperationException: Instance failure.] System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +4858423 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +257 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4859187 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +87 System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +221 System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +815 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +105 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) +42 System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +78 System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) +60 System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +119 System.Web.UI.WebControls.Login.AttemptLogin() +115 System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +101 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37 System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 What could be the reason for such an error? How could I solve this?

    Read the article

  • C# MVC: User Password Reset Controller: Issues with email addresses as usernames

    - by 109221793
    Hi guys, I have written the code below for resetting users passwords (am using the aspnet membership api) in an C# MVC application, and tested successfully on a sample tutorial application (MVC Music Store). Skip to the end if you wish to read problem description first. InactiveUsers View (Partial View) <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Security.MembershipUserCollection>" %> <table class="normal" style="width: 100%; background-color: White;"> <tr> <th>User Name</th> <th>Last Activity date</th> <th>Locked Out</th> </tr> <%foreach (MembershipUser user in Model){ %> <tr> <td><%: Html.RouteLink(user.UserName, "AdminPassword", new { username = user.UserName }) %></td> <td><%: user.LastActivityDate %></td> <td><%: user.IsLockedOut %></td> </tr> <% }%> </table> InactiveUsers Controller public ActionResult InactiveUsers() { var users = Membership.GetAllUsers(); return View(users); } changeUserPassword GET and POST Controllers public ActionResult changeUserPassword(string username) { ViewData["username"] = username; return View(); } [HttpPost] public ActionResult changeUserPassword(ChangePasswordModel model, FormCollection values) { string username = values["username"]; string password = values["password"]; string confirmPassword = values["confirmPassword"]; MembershipUser mu = Membership.GetUser(username); if (password == confirmPassword) { if (mu.ChangePassword(mu.ResetPassword(), password)) { return RedirectToAction("Index", "ControlPanel"); } else { ModelState.AddModelError("", "The current password does not meet requirements"); } } return View(); } I also modified the Global.asax.cs file to cater for my route in the InactiveUsers partial: // Added in 10/01/11 RouteTable.Routes.MapRoute( "AdminPassword", // routename "ControlPanel/changeUserPassword/{username}", new { controller = "ControlPanel", action = "changeUserPassword", username = UrlParameter.Optional } ); // END Now, when I tested on the MVC Music Store, all of my usernames were just words, e.g. Administrator, User, etc. However now I am applying this code to a situation in my workplace and it's not working out quite as planned. The usernames used in my workplace are actually email addresses and I think this is what is causing the problem. When I click on the RouteLink in the partial InactiveUsers view, it should bring me to the reset password page with a url that looks like this: http://localhost:83/ControlPanel/changeUserPassword/[email protected], HOWEVER, what happens when I click on the RouteLink is an error is thrown to say that the view changeUserPassword cannot be found, and the URL looks like this: http://localhost:83/ControlPanel/changeUserPassword/example1%40gmail.com - See how the '@' symbol gets messed up? I've also debugged through the code, and in my GET changeUserPassword, the username is populating correctly: [email protected], so I'm thinking it's just the URL that's messing it up? If I type in the URL manually, the changeUserPassword view displays, however the password reset function does not work. An 'Object reference not set to an instance of an object' exception is thrown at the if (mu.ChangePassword(mu.ResetPassword(), password)) line. I think if I could solve the first issue (URL '@' symbol problem) it might help me along with my second issue. Any help would be appreciated :) Stack Trace - as requested Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOperationException: The view 'changeUserPassword' or its master was not found. The following locations were searched: ~/Views/ControlPanel/changeUserPassword.aspx ~/Views/ControlPanel/changeUserPassword.ascx ~/Views/Shared/changeUserPassword.aspx ~/Views/Shared/changeUserPassword.ascx] System.Web.Mvc.ViewResult.FindView(ControllerContext context) +495 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39 System.Web.Mvc.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11() +60 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +391 System.Web.Mvc.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13() +61 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +285 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

    Read the article

  • Help with MVC controller: passing a string from view to controller

    - by 109221793
    Hi guys, I'm having trouble with one particular issue, I was hoping someone could help me out. I've completed the MVC Music Store tutorial, and now I'm trying to add some administrator functionality - practice as I will have to do this in an MVC application in my job. The application is using the aspnet membership api, and what I have done so far is created a view to list the users. What I want to be able to do, is click on the users name in order to change their password. To try and carry the username to the changeUserPassword controller (custom made). I registered a new route in the global.asax.cs file in order to display the username in the URL, which is working so far. UserList View <%: Html.RouteLink(user.UserName, "AdminPassword", new { controller="StoreManager", action="changeUserPassword", username = user.UserName }) %> Global.asax.cs routes.MapRoute( "AdminPassword", //Route name "{controller}/{action}/{username}", //URL with parameters new { controller = "StoreManager", action = "changeUserPassword", username = UrlParameter.Optional} ); So now the URL looks like this when I reach the changeUserPassword view: http://localhost:51236/StoreManager/changeUserPassword/Administrator Here is the GET changeUserPassword action: public ActionResult changeUserPassword(string username) { ViewData["username"] = username; return View(); } I wanted to store the username in ViewData as I would like to use it in the GET changeUserPassword for display purposes, and also as a hidden value in the form. This is in order to pass it through to enable me to reset the password. Having debugged through the code, it seems that 'username' is null. How can I get this to work so that the username carries over from the Html.RouteLink, to the changeUserPassword action? Any help would be appreciated :) Here is my complete code: UserList.aspx <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Security.MembershipUserCollection>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> UserList </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>UserList</h2> <table> <tr> <th>User Name</th> <th>Last Activity date</th> <th>Locked Out</th> </tr> <%foreach (MembershipUser user in Model){ %> <tr> <td><%: Html.RouteLink(user.UserName, "AdminPassword", new { controller="StoreManager", action="changeUserPassword", username = user.UserName }) %></td> <td><%: user.LastActivityDate %></td> <td><%: user.IsLockedOut %></td> </tr> <% }%> </table> </asp:Content> changeUserPassword.aspx <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<musicStoreMVC.ViewModels.ResetPasswordAdmin>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> changeUserPassword </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Change Password: <%: ViewData["username"] %></h2> <% using (Html.BeginForm()) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%: Html.Hidden("username",ViewData["username"]) %> <%: Html.LabelFor(model => model.password) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.password) %> <%: Html.ValidationMessageFor(model => model.password) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.confirmPassword) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.confirmPassword) %> <%: Html.ValidationMessageFor(model => model.confirmPassword) %> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> My actions public ActionResult UserList() { var users = Membership.GetAllUsers(); return View(users); } public ActionResult changeUserPassword(string username) { ViewData["username"] = username; return View(); }

    Read the article

  • Server Error in '/' Application (ASP.NET)

    - by baeltazor
    Hi All I just setup up member ship roles and registration on my website with visual web developer using the tutorial on msdn. It works perfectly locally, but when i uploaded it to my server, I get the following page: "Server Error in '/' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty. Source Error: [No relevant source lines] Source File: machine.config Line: 160 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4016 " Does anybody know why I'm seeing this and how I may go about fixinf this? Any help is greatly appreciated. Thank you Bael. EDIT: I have just looked at my web.config file after reading the following line in the error message: "The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty." ... And have noticed that the following element is completely empty: <connectionStrings/> // Is this one supposed to be empty? if not what should go here? In the error it implies it shouldn't be empty. Also, I don't know where I should place LocalSqlServer LATEST EDIT After changing DataSource to LocalHost i get the following error: Server Error in '/JTS' Application. -------------------------------------------------------------------------------- A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849015 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +4862333 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +87 System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +221 System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +815 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +105 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) +42 System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +78 System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) +60 System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +119 System.Web.UI.WebControls.Login.AttemptLogin() +115 System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +101 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37 System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927

    Read the article

  • Unable to use nMock GetProperty routine on a property of an inherited object...

    - by Chris
    I am getting this error when trying to set an expectation on an object I mocked that inherits from MembershipUser: ContactRepositoryTests.UpdateTest : FailedSystem.InvalidProgramException: JIT Compiler encountered an internal limitation. Server stack trace: at MockObjectType1.ToString() Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref MessageData msgData, Int32 type) at System.Object.ToString() at NMock2.Internal.ExpectationBuilder.On(Object receiver) Here are the tools I am using... VS2008 (SP1) Framework 3.5 nUnit 2.4.8 nMock 2.0.0.44 Resharper 4.1 I am at a loss as to why this would be happening. Any help would be appreciated. Test Class... [TestFixture] public class AddressRepositoryTests { private Mockery m_Mockery; private Data.IAddress m_MockDataAddress; private IUser m_MockUser; [SetUp] public void Setup() { m_Mockery = new Mockery(); m_MockDataAddress = m_Mockery.NewMock<Data.IAddress>(); m_MockUser = m_Mockery.NewMock<IUser>(); } [TearDown] public void TearDown() { m_Mockery.Dispose(); } [Test] public void CreateTest() { string line1 = "unitTestLine1"; string line2 = "unitTestLine2"; string city = "unitTestCity"; int stateId = 1893; string postalCode = "unitTestPostalCode"; int countryId = 223; bool active = false; int createdById = 1; Expect.Once .On(m_MockUser) .GetProperty("Identity") .Will(Return.Value(createdById)); Expect.Once .On(m_MockDataAddress) .Method("Insert") .With( line1, line2, city, stateId, postalCode, countryId, active, createdById, Is.Anything ) .Will(Return.Value(null)); IAddressRepository addressRepository = new AddressRepository(m_MockDataAddress); IAddress address = addressRepository.Create( line1, line2, city, stateId, postalCode, countryId, active, m_MockUser ); Assert.IsNull(address); } } User Class... public interface IUser { int? Identity { get; set; } int? CreatedBy { get; set; } DateTime CreatedOn { get; set; } int? ModifiedBy { get; set; } DateTime? ModifiedOn { get; set; } string UserName { get; } object ProviderUserKey { get; } string Email { get; set; } string PasswordQuestion { get; } string Comment { get; set; } bool IsApproved { get; set; } bool IsLockedOut { get; } DateTime LastLockoutDate { get; } DateTime CreationDate { get; } DateTime LastLoginDate { get; set; } DateTime LastActivityDate { get; set; } DateTime LastPasswordChangedDate { get; } bool IsOnline { get; } string ProviderName { get; } string ToString(); string GetPassword(); string GetPassword(string passwordAnswer); bool ChangePassword(string oldPassword, string newPassword); bool ChangePasswordQuestionAndAnswer(string password, string newPasswordQuestion, string newPasswordAnswer); string ResetPassword(string passwordAnswer); string ResetPassword(); bool UnlockUser(); } public class User : MembershipUser, IUser { #region Public Properties private int? m_Identity; public int? Identity { get { return m_Identity; } set { if (value <= 0) throw new Exception("Address.Identity must be greater than 0."); m_Identity = value; } } public int? CreatedBy { get; set; } private DateTime m_CreatedOn = DateTime.Now; public DateTime CreatedOn { get { return m_CreatedOn; } set { m_CreatedOn = value; } } public int? ModifiedBy { get; set; } public DateTime? ModifiedOn { get; set; } #endregion Public Properties #region Public Constructors public User() { } #endregion Public Constructors } Address Class... public interface IAddress { int? Identity { get; set; } string Line1 { get; set; } string Line2 { get; set; } string City { get; set; } string PostalCode { get; set; } bool Active { get; set; } int? CreatedBy { get; set; } DateTime CreatedOn { get; set; } int? ModifiedBy { get; set; } DateTime? ModifiedOn { get; set; } } public class Address : IAddress { #region Public Properties private int? m_Identity; public int? Identity { get { return m_Identity; } set { if (value <= 0) throw new Exception("Address.Identity must be greater than 0."); m_Identity = value; } } public string Line1 { get; set; } public string Line2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } public bool Active { get; set; } public int? CreatedBy { get; set; } private DateTime m_CreatedOn = DateTime.Now; public DateTime CreatedOn { get { return m_CreatedOn; } set { m_CreatedOn = value; } } public int? ModifiedBy { get; set; } public DateTime? ModifiedOn { get; set; } #endregion Public Properties } AddressRepository Class... public interface IAddressRepository { IAddress Create(string line1, string line2, string city, int stateId, string postalCode, int countryId, bool active, IUser createdBy); } public class AddressRepository : IAddressRepository { #region Private Properties private Data.IAddress m_DataAddress; private Data.IAddress DataAddress { get { if (m_DataAddress == null) m_DataAddress = new Data.Address(); return m_DataAddress; } set { m_DataAddress = value; } } #endregion Private Properties #region Public Constructor public AddressRepository() { } public AddressRepository(Data.IAddress dataAddress) { DataAddress = dataAddress; } #endregion Public Constructor #region Public Methods public IAddress Create(string line1, string line2, string city, int stateId, string postalCode, int countryId, bool active, IUser createdBy) { if (String.IsNullOrEmpty(line1)) throw new Exception("You must enter a Address Line 1 to register."); if (String.IsNullOrEmpty(city)) throw new Exception("You must enter a City to register."); if (stateId <= 0) throw new Exception("You must select a State to register."); if (String.IsNullOrEmpty(postalCode)) throw new Exception("You must enter a Postal Code to register."); if (countryId <= 0) throw new Exception("You must select a Country to register."); DataSet dataSet = DataAddress.Insert( line1, line2, city, stateId, postalCode, countryId, active, createdBy.Identity, DateTime.Now ); return null; } #endregion Public Methods } DataAddress Class... public interface IAddress { DataSet GetByAddressId (int? AddressId); DataSet Update (int? AddressId, string Address1, string Address2, string City, int? StateId, string PostalCode, int? CountryId, bool? IsActive, Guid? ModifiedBy); DataSet Insert (string Address1, string Address2, string City, int? StateId, string PostalCode, int? CountryId, bool? IsActive, int? CreatedBy, DateTime? CreatedOn); } public class Address : IAddress { public DataSet GetByAddressId (int? AddressId) { Database database = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = database.GetStoredProcCommand("prAddress_GetByAddressId"); DataSet dataSet; try { database.AddInParameter(dbCommand, "AddressId", DbType.Int32, AddressId); dataSet = database.ExecuteDataSet(dbCommand); } catch (SqlException sqlException) { string callMessage = "prAddress_GetByAddressId " + "@AddressId = " + AddressId; throw new Exception(callMessage, sqlException); } return dataSet; } public DataSet Update (int? AddressId, string Address1, string Address2, string City, int? StateId, string PostalCode, int? CountryId, bool? IsActive, Guid? ModifiedBy) { Database database = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = database.GetStoredProcCommand("prAddress_Update"); DataSet dataSet; try { database.AddInParameter(dbCommand, "AddressId", DbType.Int32, AddressId); database.AddInParameter(dbCommand, "Address1", DbType.AnsiString, Address1); database.AddInParameter(dbCommand, "Address2", DbType.AnsiString, Address2); database.AddInParameter(dbCommand, "City", DbType.AnsiString, City); database.AddInParameter(dbCommand, "StateId", DbType.Int32, StateId); database.AddInParameter(dbCommand, "PostalCode", DbType.AnsiString, PostalCode); database.AddInParameter(dbCommand, "CountryId", DbType.Int32, CountryId); database.AddInParameter(dbCommand, "IsActive", DbType.Boolean, IsActive); database.AddInParameter(dbCommand, "ModifiedBy", DbType.Guid, ModifiedBy); dataSet = database.ExecuteDataSet(dbCommand); } catch (SqlException sqlException) { string callMessage = "prAddress_Update " + "@AddressId = " + AddressId + ", @Address1 = " + Address1 + ", @Address2 = " + Address2 + ", @City = " + City + ", @StateId = " + StateId + ", @PostalCode = " + PostalCode + ", @CountryId = " + CountryId + ", @IsActive = " + IsActive + ", @ModifiedBy = " + ModifiedBy; throw new Exception(callMessage, sqlException); } return dataSet; } public DataSet Insert (string Address1, string Address2, string City, int? StateId, string PostalCode, int? CountryId, bool? IsActive, int? CreatedBy, DateTime? CreatedOn) { Database database = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = database.GetStoredProcCommand("prAddress_Insert"); DataSet dataSet; try { database.AddInParameter(dbCommand, "Address1", DbType.AnsiString, Address1); database.AddInParameter(dbCommand, "Address2", DbType.AnsiString, Address2); database.AddInParameter(dbCommand, "City", DbType.AnsiString, City); database.AddInParameter(dbCommand, "StateId", DbType.Int32, StateId); database.AddInParameter(dbCommand, "PostalCode", DbType.AnsiString, PostalCode); database.AddInParameter(dbCommand, "CountryId", DbType.Int32, CountryId); database.AddInParameter(dbCommand, "IsActive", DbType.Boolean, IsActive); database.AddInParameter(dbCommand, "CreatedBy", DbType.Int32, CreatedBy); database.AddInParameter(dbCommand, "CreatedOn", DbType.DateTime, CreatedOn); dataSet = database.ExecuteDataSet(dbCommand); } catch (SqlException sqlException) { string callMessage = "prAddress_Insert " + "@Address1 = " + Address1 + ", @Address2 = " + Address2 + ", @City = " + City + ", @StateId = " + StateId + ", @PostalCode = " + PostalCode + ", @CountryId = " + CountryId + ", @IsActive = " + IsActive + ", @CreatedBy = " + CreatedBy + ", @CreatedOn = " + CreatedOn; throw new Exception(callMessage, sqlException); } return dataSet; } }

    Read the article

1