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 an example:

1:  namespace Custom.CustomUser  
2:  {  
3:    using System;  
4:    using System.Web.Security;  
5:    
6:    public class CustomMembershipUser : MembershipUser  
7:    {  
8:      public int CompanyFK { get; set; }  
9:    
10:      public string Name { get; set; }  
11:    
12:      public CustomMembershipUser(  
13:        string providername,  
14:        string username,  
15:        object providerUserKey,  
16:        string email,  
17:        string passwordQuestion,  
18:        string comment,  
19:        bool isApproved,  
20:        bool isLockedOut,  
21:        DateTime creationDate,  
22:        DateTime lastLoginDate,  
23:        DateTime lastActivityDate,  
24:        DateTime lastPasswordChangedDate,  
25:        DateTime lastLockedOutDate,  
26:        int companyFK,  
27:        string name) :  
28:        base(providername,  
29:          username,  
30:          providerUserKey,  
31:          email,  
32:          passwordQuestion,  
33:          comment,  
34:          isApproved,  
35:          isLockedOut,  
36:          creationDate,  
37:          lastLoginDate,  
38:          lastPasswordChangedDate,  
39:          lastActivityDate,  
40:          lastLockedOutDate)  
41:      {  
42:        CompanyFK = companyFK;  
43:        Name = name;  
44:      }  
45:    }  
46:  }  

After you create the new class you need to use it in your CustomMembershipProvider as we did in our example in our previous post:

1:  public CustomMembershipUser CreateUser(  
2:          string username,  
3:          string password,  
4:          string email,  
5:          string passwordQuestion,  
6:          string passwordAnswer,  
7:          bool isApproved,  
8:          object providerUserKey,  
9:          out MembershipCreateStatus status,  
10:          int companyID,  
11:          string name,  
12:          string phoneNumber)  
13:      {  
14:        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);  
15:    
16:        OnValidatingPassword(args);  
17:    
18:        if (args.Cancel)  
19:        {  
20:          status = MembershipCreateStatus.InvalidPassword;  
21:          return null;  
22:        }  
23:    
24:        if ((RequiresUniqueEmail && (GetUserNameByEmail(email) != String.Empty)))  
25:        {  
26:          status = MembershipCreateStatus.DuplicateEmail;  
27:          return null;  
28:        }  
29:    
30:        CustomMembershipUser customMembershipUser = GetUser(username);  
31:    
32:        if (customMembershipUser == null)  
33:        {  
34:          try  
35:          {  
36:            using (CustomDataContext _db = new CustomDataContext())  
37:            {  
38:              User user = new User();  
39:              user.CompanyFK = companyID;  
40:              user.Name = name;  
41:              user.UserName = username;  
42:              user.Password = EncodePassword(password);  
43:              user.Email = email.ToLower();  
44:              user.CreatedOn = DateTime.Now;  
45:              user.ModifiedOn = DateTime.Now;  
46:              user.Phone = phoneNumber;  
47:              _db.Users.InsertOnSubmit(user);  
48:    
49:              _db.SubmitChanges();  
50:    
51:              status = MembershipCreateStatus.Success;  
52:    
53:              return GetUser(username);  
54:            }  
55:    
56:          }  
57:          catch  
58:          {  
59:            status = MembershipCreateStatus.ProviderError;  
60:          }  
61:        }  
62:        else  
63:        {  
64:          status = MembershipCreateStatus.DuplicateUserName;  
65:        }  
66:    
67:        return null;  
68:      }  

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:

1:  CustomMembershipUser user = membershipProvider.CreateUser("username", "password", "mail@somewhere.com", "", "", true, null, out unusedStatus, c.CompanyId, "contact", "");  
2:  if (user != null) {  
3:   // if successfully created add the new user to some role  
4:   membershipProvider.AddUsersToRoles(new string[] { user.UserName }, new string[] { "Role" });  
5:  }  

If you want to get the user you need to get it from the Membership class as in this example:

1:  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 information in the storage that you provided while creating your custom membership and role providers.

Until next time…Happy coding.

Other chapters from these series

//

Advertisements

Posted by TheBoyan

I have been programming since I was 11 years old (Yes, I'm one of those, for real). First programming language I learned was BASIC, on a Commodore64. Then around high-school it was C and Assembly. Just before and during university days it was C++. I started doing some professional work during this period, part of the reason why I dropped out of uni in my final year. I have never stopped since then. Going through a plethora of technologies ranging from C and Assembly languages, Delphi to C++, C#, Java and so on and so forth... trough 20 (and more, who counts, does it even matter) years of software development. I have not lost even a single bit of my ambition and love for the craft from those first young days, nor the energy...I absolutely love what I do. I like to get my hands into all aspects of software development. Now-a-days I use mainly Microsoft related technologies .NET C#, with a lot of database design/management usage of SQL server, but not in any way limited to that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s