Haruna Ado
Haruna Ado

Reputation: 47

Creating User in dotnetnuke and Assign Role using c#

I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?

//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
   while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
   rndString += c;
}

string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();

//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;

//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;

UserCreateStatus result = UserController.CreateUser(ref oUser);

if (result == UserCreateStatus.Success)
{
   RoleController oDnnRoleController = new RoleController();

   //Get the role information
   RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
   // RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
   //Assign to user
   oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
   // oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}

Upvotes: 1

Views: 2303

Answers (1)

Mahogany
Mahogany

Reputation: 493

The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.

Sample settings

Upvotes: 2

Related Questions