Ruminations of idle rants and ramblings of a code monkey

More on Membership (from Zain's Presentation yesterday)

.NET Stuff | Web (and ASP.NET) Stuff

When I posted the notes yesterday from Zain's presentation, I posted something about adding users in code ... but I only mentioned the CreateUser() method.  Well, I just got an email from the person that requested this little tip ... with a little curve thrown in.  They also needed to add some profile information.  So, I sat down and wrote a little sample of how to do this (liberally sprinkled with comments).  For those that attended my peformance session in Second Life, there's another little perf tip in here that I forgot to put into my presentation (it's going in now though). 

Here it is ...

    //Some assumptions ...
    //You have all the user information in a data reader
    //It actually doesn't matter where it comes from
    //but using a reader makes the sample easier. :)
    //The using statements that are important here:
    //using System.Web.Security;
    //using System.Web.Profile;
    public static void AddUsers(SqlDataReader rdr)
        //Set the script timeout to 10 minutes ...
        //Use a reasonable value
        HttpContext.Current.Server.ScriptTimeout = 60000;
        //And we will get the indexes for the fields that we want
        //This is a good deal more efficient than rdr["FieldName"]
        //but ... you *must* do it before entering the loop.
        //It's also type safe as well. :-)
        int userId = rdr.GetOrdinal("UserID");
        int password = rdr.GetOrdinal("Password");
        int email = rdr.GetOrdinal("Reader");
        int favColor = rdr.GetOrdinal("FavoriteColor");
        int height = rdr.GetOrdinal("Height");
        int street = rdr.GetOrdinal("Street");
        while (rdr.Read())
            //Add the users ...
            //I'm using one of the overloads here ... there are several.
            //This returns the membership user that was created;
            MembershipUser usr = Membership.CreateUser(rdr.GetString(userId),
                rdr.GetString(password), rdr.GetString(email));
            //Now you will need to create the profile. 
            ProfileBase prof = System.Web.Profile.ProfileBase.Create(usr.UserName);
            //And I'm making up some properties here.
            //These will need to be configured.
            prof.PropertyValues["FavoriteColor"].PropertyValue = rdr.GetString(favColor);
            prof.PropertyValues["Height"].PropertyValue = rdr.GetString(height);
            //And, if you're using groups
            //(A good idea if you have a lot of properties)
            ProfileGroupBase addrGroup = prof.GetProfileGroup("Address");
            addrGroup.SetPropertyValue("Street", rdr.GetString(street));
            //Make sure that the profile is saved



And ... that's all folks!

Comments are closed