Monday, December 19, 2011

Custom Membership User

Custom Membership User

Hello again. In the first part of these mini series we discussed how you can create a custom membership provider and a custom role provider.
Many times you will find yourself in a situation where you need to store and retrieve more data for a specific user than it is available in the  MembershipUser class, which is the default for a MembershipProvider. While there is a way to acomplish this by using profiles and the ProfileProvider class here I will show you how to accomplish this by creating a custom membership user.

In the example that I'm going to provide, as in the previous examples I use Linq-to-SQL data source and my own table structure to keep membership/user and role data.
In order to create a custom membership user you need to inherit from MembershipUser class.
Here's the example:
namespace Custom.CustomUser
{
    using System;
    using System.Web.Security;

    public class CustomMembershipUser : MembershipUser
    {
        public int CompanyFK { get; set; }

        public string Name { get; set; }

        public CustomMembershipUser(
            string providername,
            string username,
            object providerUserKey,
            string email,
            string passwordQuestion,
            string comment,
            bool isApproved,
            bool isLockedOut,
            DateTime creationDate,
            DateTime lastLoginDate,
            DateTime lastActivityDate,
            DateTime lastPasswordChangedDate,
            DateTime lastLockedOutDate,
            int companyFK,
            string name) :
            base(providername,
                username,
                providerUserKey,
                email,
                passwordQuestion,
                comment,
                isApproved, 
                isLockedOut, 
                creationDate,
                lastLoginDate, 
                lastPasswordChangedDate, 
                lastActivityDate,
                lastLockedOutDate)
        {
            CompanyFK = companyFK;
            Name = name;
        }
    }
}
After you create the new class you need to use it in your CustomMembershipProvider as we did in our example in our previous post:
public CustomMembershipUser CreateUser(
                string username,
                string password,
                string email,
                string passwordQuestion,
                string passwordAnswer,
                bool isApproved,
                object providerUserKey,
                out MembershipCreateStatus status,
                int companyID,
                string name,
                string phoneNumber)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if ((RequiresUniqueEmail && (GetUserNameByEmail(email) != String.Empty)))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            CustomMembershipUser customMembershipUser = GetUser(username);

            if (customMembershipUser == null)
            {
                try
                {
                    using (CustomDataContext _db = new CustomDataContext())
                    {
                        User user = new User();
                        user.CompanyFK = companyID;
                        user.Name = name;
                        user.UserName = username;
                        user.Password = EncodePassword(password);
                        user.Email = email.ToLower();
                        user.CreatedOn = DateTime.Now;
                        user.ModifiedOn = DateTime.Now;
                        user.Phone = phoneNumber;
                        _db.Users.InsertOnSubmit(user);

                        _db.SubmitChanges();

                        status = MembershipCreateStatus.Success;

                        return GetUser(username);
                    }

                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                }
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }

            return null;
        }
You don't have to provide settings in the web.config to make this work. You just need to use it in your membership provider.
Now, all you have to do in your code in order to create a user with your custom memebrship user class is something like:
CustomMembershipUser user = membershipProvider.CreateUser("username", "password", "mail@somewhere.com", "", "", true, null, out unusedStatus, c.CompanyId, "contact", "");
if (user != null) {
 // if successfully created add the new user to some role
 membershipProvider.AddUsersToRoles(new string[] { user.UserName }, new string[] { "Role" });
}
If you want to get the user you need to get it from the Membership class as in this example:
CustomMembershipUser user = Membership.GetUser(username) as CustomMembershipUser;
That's it. Now you have a custom membership provider, a custom role provider and a custom user to carry and store extra user informatiion in the storage that you provided while creating your custom membership and role providers.
Until next time...Happy programming.

Other chapters from these series

1 comment:

  1. Thanks Bojan. It's a lot of coding, but I hope it'll be extrauseful in my app - when I finally implement it. Thanks again.

    ReplyDelete