Creating a DotNetNuke User Account From Code 

Just recently an issue was brought to my attention that my External Database Provider module when creating users was making it so that notification e-mails could not be sent when assigning roles. So I started looking into the code, and how I was creating a user. The user creation code was something that I have been using for a long time, some code that was first found on a blog or forum post about 2-3 years ago. Not noticing anything wrong with the code, at least from an obvious point of view I started to look into the database to see if there were any differences at the database level. Looking into the users' information I noticed that they were missing their user profile, and then I found out that a few key elements still needed to be set to "fully" create the user. This posting shows you the "Full Code" to insert a user into a DotNetNuke portal from a C# Codebehind, translation into VB should be very simple.

The Code

The most logical starting point here is to share the code. THe following code snippet shows the proper way to create a DotNetNuke user, with full integration to ensure that no errors will be encountered.

   1:  UserInfo oUser = new UserInfo();
   2:  oUser.PortalID = this.PortalId;
   3:  oUser.IsSuperUser = false;
   4:  oUser.FirstName = "FirstName";
   5:  oUser.LastName = "LastName";
   6:  oUser.Email = "test@test.com";
   7:  oUser.Username = "MyUsername";
   8:  oUser.DisplayName = "FirstName LastName";
   9:   
  10:  //Fill MINIMUM Profile Items (KEY PIECE)
  11:  oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
  12:  oUser.Profile.TimeZone = PortalSettings.TimeZoneOffset;
  13:  oUser.Profile.FirstName = oUser.FirstName;
  14:  oUser.Profile.LastName = oUser.LastName;
  15:   
  16:  //Set Membership
  17:  UserMembership oNewMembership = new UserMembership();
  18:  oNewMembership.Approved = true;
  19:  oNewMembership.CreatedDate = System.DateTime.Now;
  20:  oNewMembership.Email = oUser.Email;
  21:  oNewMembership.IsOnLine = false;
  22:  oNewMembership.Username = oUser.Username;
  23:  oNewMembership.Password = oExternalUserAccount.Password;
  24:   
  25:  //Bind membership to user
  26:  oUser.Membership = oNewMembership;
  27:   
  28:  //Add the user, ensure it was successful
  29:  if (UserCreateStatus.Success == UserController.CreateUser(ref oUser))
  30:  {
  31:  //Take Success Action
  32:  }

As you can see from this were have three distinct actions that we perform before we actually create the users account. The first step is to declare the user object and fill the common informaiton such as name, display name, and email address. We then progress to populating the profile, this is the key piece missing from many of the examples. We set the locale and timezone to match the portal default, this ensures that all localization and other features work for the user. Lastly we configure their membership information, including password.

Once the users information has been properly configured we call the CreateUser method of the UserController to actually create the user and check the creation status for errors. A very simple code example, but something that is not always straightforward to work with.

Summary

I hope this has helped someone else looking to create users in code from DotNetNuke. Please share any comments below, for assistance please post to the forum.

Posted by Mitchel on Monday, December 22, 2008
 

Comments

Great example! I had posted something like this once. And folks may want to keep an eye out for a great Wrox Blox on this topic in January. It is written by Antonio Chagoury, the DNN Blog Module lead.

By Will Strohl on Monday, December 22, 2008 at 1:48 PM

works like a charm! great post!

By xavi on Saturday, January 24, 2009 at 11:50 AM

Thanks for the post.
Any idea how to send a notification email to the user (username and password)? I know it's somewhere in DNN core, but still wondering if you have an instant answer.

By Frank Wang on Tuesday, February 10, 2009 at 12:33 AM

Frank,

I would have to go digging for this, but my guess is that it is somewhere in the UserController, or User Class.

By mitchel.sellers@gmail.com on Tuesday, February 10, 2009 at 8:52 AM

What is oExternalUserAccount.Password? in your code? How do i pass password from my form text box.

By Raj Gohil on Wednesday, April 22, 2009 at 10:27 AM

Raj,

That is simply the password from the external system. (This code is taken from my auth provider.)

To get from a textbox, simply replace that call with the code to get your textbox value!

By mitchel.sellers@gmail.com on Wednesday, April 22, 2009 at 10:34 AM

thanks for this post
i search long time to find this useful code

By almny on Thursday, May 14, 2009 at 9:32 PM

i get error in this line
oNewMembership.Password = oExternalUserAccount.Password;

i nedd any namespace to add it ?

By almny on Sunday, May 17, 2009 at 8:07 AM

thanks it's working good now

By almny on Monday, May 18, 2009 at 2:32 AM

add a User To a Role
DotNetNuke.Security.Roles.RoleController rc
= new DotNetNuke.Security.Roles.RoleController();

//retrieve role
string groupName = "mygroup";
DotNetNuke.Security.Roles.RoleInfo ri = rc.GetRoleByName(PortalId, groupName);
//suppose your userinfo object is ui
DotNetNuke.Entities.Users.UserInfo ui
= DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();

rc.AddUserRole(PortalId, ui.UserID, ri.RoleID, Null.NullDate);

Posted by Ahmed at 1:41 AM

http://dotnetnuke-free.blogspot.com/2009/04/add-user-to-role.html

By almny on Monday, May 18, 2009 at 4:22 AM

I'm pulling my hair out over an issue I'm having with this exact thing. I create the user exaclty as described, but than try to login as my new user and the password fails. I've tried everything to set the password within membership, but nothing seems to work except for going straight to the DB and copying a previously created password and salt from another user onto my new one. Any idea what I'm doing wrong? BTW this is DNN 5!

By BobJohnson on Thursday, June 18, 2009 at 10:44 AM

Even I am getting same error

oNewMembership.Password = oExternalUserAccount.Password

oExternalUserAccount does not exists.... What name space I need to add

By Murthy on Monday, September 21, 2009 at 2:27 AM


"oNewMembership.Password = oExternalUserAccount.Password

oExternalUserAccount does not exists.... What name space I need to add"

The "oExternalUserAccount.Password" simply returns a string and refers to an object set up by Mitchel elsewhere.

Try:

oNewMembership.Password = "letmein"

That will work - pass any string, it doesn't have to be "letmein" of course!!! - in practice you would normally read this string from a password textbox.

By Craig on Tuesday, November 10, 2009 at 9:00 AM

Where can i find the VB.NET version of this code? can someone please help.

By Suman on Wednesday, February 24, 2010 at 10:16 AM

Getting the vb.net version of this is pretty simple.

Change "this" to "Me", remove the ; characters and change the syntax on the if statement and variable declaration.

By mitchel.sellers@gmail.com on Wednesday, February 24, 2010 at 11:19 AM

Hi,

I already did the action. I also want to send an email notification when user created with verification code..

I did something like that:

uinfo.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
UserCreateStatus createStatus = UserController.CreateUser(ref uinfo);
if (UserCreateStatus.Success == createStatus)
{
DotNetNuke.Entities.Modules.UserUserControlBase.UserCreatedEventArgs args = new DotNetNuke.Entities.Modules.UserUserControlBase.UserCreatedEventArgs(uinfo);
args.Notify = true;
args.CreateStatus = createStatus;
DotNetNuke.Entities.Modules.UserUserControlBase a = new UserUserControlBase();
a.OnUserCreated(args);
a.OnUserCreateCompleted(args);




}
else
{
lblCSVMsg.Text = UserCreateStatus.UnexpectedError.ToString();
}

But seem to me email notification dnt going right.

By Ajit on Saturday, April 03, 2010 at 10:36 PM

As soon as the step:
oUserInfo.FirstName = rdr.Item("FIRST_NAME")
is executed, an exception is thrown:
The type initializer for 'DotNetNuke.Entities.Profile.ProfileController' threw an exception.
The object accepts the PortalID and IsSuperUser values.

By Chris on Thursday, April 15, 2010 at 2:22 PM

I was able to solve my problem. I am new to DNN and I had to clean up some issues with my development environment. Thanks to your help, my import works nicely!

By Chris on Friday, April 16, 2010 at 10:18 AM

Thank you very much for your post, I've been struggling with customizing the standard DNN user creation through the Users & Security module with very little luck.

With a bit of an adjustment I got your code to work perfectly for my DNN 05.04.02. Below are the adjustments that I made for anyone who could use them:

protected void Click_Buttons_AddUser_Submit(object sender, EventArgs e)
{
DotNetNuke.Entities.Users.UserInfo oUser = new DotNetNuke.Entities.Users.UserInfo();

oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = TextBox_AddUser_Name.Text;
oUser.LastName = TextBox_AddUser_Surname.Text;
oUser.Email = TextBox_AddUser_Email.Text;
oUser.Username = TextBox_AddUser_Username.Text;
oUser.DisplayName = TextBox_AddUser_Name.Text;

oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
oUser.Profile.TimeZone = PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;

oUser.Membership.Approved = true;
oUser.Membership.CreatedDate = System.DateTime.Now;
oUser.Membership.IsOnLine = false;
oUser.Membership.Password = TextBox_AddUser_Password.Text;

try
{
if (DotNetNuke.Security.Membership.UserCreateStatus.Success == DotNetNuke.Entities.Users.UserController.CreateUser(ref oUser))
{
Notice_Success(Success_Msg + "YAY!");
}
}
catch (System.Exception ex)
{
ErrorLogging(ex);
Notice_Error(Oops_Msg + "awww :( ");
}
}

By Griimm on Tuesday, June 29, 2010 at 4:31 PM

Hi !
I'm trying do do my own registration module and I did what Ajit did by firing the OnUserCreate() event and no email is sent... Did someone found a way to make it happen ?

I also need to automatically log the newly created user. Can you help me ?

Thanks,

Vincent.

By vbontoux on Monday, September 20, 2010 at 1:14 PM

Be nice if you didn't include line numbers in the code sample. Kinda pain to cut & paste. Thank you anyway, I assume it works. Will find out soon. And the using statements would be nice.

By Jim on Friday, October 01, 2010 at 11:05 AM

I am beginner with DNN and i need create a new user but I don't understand where is the connection string or how I need configure it??
tks

By Humbert on Thursday, December 09, 2010 at 12:54 PM

Here's the above code in vb with a few additions. Hope this helps.

Function CreateDNNUser(ByVal userName As String, _
ByVal userPassword As String, _
ByVal firstName As String, _
ByVal lastName As String, _
ByVal eMail As String, _
ByVal displayName As String, _
ByVal userRole As String) As UserCreateStatus
Dim oUser As UserInfo = New UserInfo()

With oUser
.PortalID = PortalId
.IsSuperUser = False
.FirstName = firstName
.LastName = lastName
.Email = eMail
.Username = userName
.DisplayName = displayName
End With

With oUser.Profile
.PreferredLocale = PortalSettings.DefaultLanguage
.TimeZone = PortalSettings.TimeZoneOffset
.FirstName = oUser.FirstName
.LastName = oUser.LastName
End With

With oUser.Membership
.Approved = True
.CreatedDate = System.DateTime.Now
.IsOnLine = False
.Password = userPassword
End With

Dim result As UserCreateStatus = UserController.CreateUser(oUser)
If result = UserCreateStatus.Success Then
If userRole.Length > 0 Then
Dim roleController As DotNetNuke.Security.Roles.RoleController = New DotNetNuke.Security.Roles.RoleController()
Dim roleInfo As DotNetNuke.Security.Roles.RoleInfo = roleController.GetRoleByName(PortalId, userRole)
roleController.AddUserRole(PortalId, oUser.UserID, roleInfo.RoleID, Null.NullDate)
End If
End If

Return result
End Function

By Derek on Thursday, February 03, 2011 at 7:15 AM

Thanks for your code sample, Derek. I was just looking for something like that.

By Tomaz on Tuesday, March 15, 2011 at 1:08 PM

Hi,
I have to create DNN user account from an external website.
First of all I m very new to DNN.
However, I try this code :
DotNetNuke.Entities.Users.UserInfo oUser = new DotNetNuke.Entities.Users.UserInfo();
oUser.PortalID = 0;
oUser.IsSuperUser = false;
oUser.FirstName = "stan";
oUser.LastName = "LastName";
oUser.Email = "test@test.com";
But I get an NullReference exception error on the line oUser.FirstName="stan";

and by the way (hope this post is still active)... what would be the files and/or settings I have to add to my external project and webconfig....

I thank you in advance for your support

By Stan on Wednesday, April 27, 2011 at 12:03 PM

I keep getting the NullReference exception error as well.
Is there a way to work around it?

By Nate on Friday, May 27, 2011 at 6:18 PM

Great post Mitch. Thanks.

By Seth on Friday, November 11, 2011 at 11:46 AM

DotNetNuke 6.0 (DNN6.0 +) update:

The TimeZone line should be done as follows (the Profile.TimeZone and TimeZoneOffset are deprecated).

oUser.Profile.PreferredTimeZone = PortalSettings.TimeZone;

By Dan Gilleland on Saturday, February 04, 2012 at 1:27 PM

Name (required)

Email (required)

Website

CAPTCHA image
Enter the code shown above:

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Friend of RedGate

www.datasprings.com - DotNetNuke ModulesICG

Click here for advertising information.

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.