Create New Users
12 Jun 2009 @ 08:15AM

Updated: 27 Jan 2010 @ 08:15AM
We're almost finished with the user management. We just need to be able to add a new user. We'll set the stage by adding a 'Add User' link to the bottom of the user management form.
content += @"</tbody>
<tfoot>
     <tr>
          <td colspan=10>* total (visible)<br>
               <a href='default.aspx?option=addUser'>Add User</a>
          </td>
     </tr>
</tfoot>
</table>"
;
Comments (0)
Next we alter our Page_Load() method to catch the addUser option.
case "addUser":
     if (accessLevel < 255)
     {
          break;
     }
     showblogs = false;
     content += addUser();
     content += userManagement(0);
     break;

So we put this in the GET case statement and just run a method called addUser().
Comments (0)
private string addUser()
{
     string content = null;

     string userUsername = null, userDisplayname = null, userEmail = null, error = null;
     int userShowEmail = 0, userAccessLevel = 0;

     content += "<form method='POST' action='default.aspx' style='display: inline;'>" +
     "<table class='addUser'>" +
     "<tbody>" +
          "<tr>" +
               "<th>Username</th>" +
               "<td><input name='username' value='" + userUsername + "'></td>" +
          "</tr><tr>" +
               "<th>Display Name</th>" +
               "<td><input name='displayName' value='" + userDisplayname + "'></td>" +
          "</tr><tr>" +
               "<th>Email</th>" +
               "<td><input name='email' value='" + userEmail + "'></td>" +
          "</tr><tr>" +
               "<th>ShowEmail</th>" +
               "<td><select name='showEmail'>" +
                    "<option value=0";
     content += (userShowEmail == 0) ? " selected" : "";
     content += ">No</option>" +
                    "<option value=1";
     content += (userShowEmail == 1) ? " selected" : "";
     content += ">Yes</option" +
                    "</select>" +
               "</td>" +
          "</tr><tr>" +
               "<th>Access</th>" +
               "<td><select name='accessLevel'>" +
                    "<option value=0";
     content += (userAccessLevel == 0) ? " selected" : "";
     content += ">User</option>" +
                    "<option value=100";
     content += (userAccessLevel == 100) ? " selected" : "";
     content += ">Blogger</option>" +
                    "<option value=255";
     content += (userAccessLevel == 255) ? " selected" : "";
     content += ">Admin</option>" +
                    "</select>" +
               "</td>" +
          "</tr><tr>" +
               "<th>Password</th>" +
               "<td><input type='password' name='password1'></td>" +
          "</tr><tr>" +
               "<th>Verify</th>" +
               "<td><input type='password' name='password2'></td>" +
          "</tr><tr>" +
               "<td colspan=2 class='error'>" + error + "</td>" +
          "</tr><tr>" +
               "<td colspan=2>" +
                    "<input type='submit' name='option' value='Save New User'></form>" +
                    "<form action='default.aspx' method='GET' style='display: inline;'>" +
                         "<input type='hidden' name='option' value='userManagement'>" +
                         "<input type='submit' value='Cancel'>" +
                    "</form>" +
          "</tr>" +
     "</tbody>" +
     "</table>";
     return content;
}

Here I've created my add user form. I've also prepared it for use in actually saving a new user. Basically we're just initializing some variables, then writing out a form. Nothing insanely awesome just yet.
Comments (0)
case "Save New User":
     if (accessLevel < 255)
     {
          break;
     }
     showblogs = false;
     content += addUser();
     break;

Here we catch our Save New User variable. This is in the Page_Load() method, specifically in the POST case.
Comments (0)
And now for the changes to the addUser() method.
ArrayList errors = new ArrayList();
if (getVariable("option", var.POST) == "Save New User")
{
     //save a new user
     userUsername = sanitize(getVariable("username", var.POST), clean.DB);
     userDisplayname = sanitize(getVariable("displayName", var.POST), clean.DB);
     userEmail = sanitize(getVariable("email", var.POST), clean.DB);
     userShowEmail = (getVariable("showEmail", var.POST) == "1") ? 1 : 0;
     userAccessLevel = Convert.ToInt16(getVariable("userAccessLevel", var.POST));

     string password1 = getVariable("password1", var.POST);
     string password2 = getVariable("password2", var.POST);
     if (password1 != password2)
     {
          errors.Add("Passwords don't match.");
     }//checking to see if passwords match
     else if (password1 == null || password1.Length < 6)
     {
          errors.Add("Password needs to be at least 6 characters long.");
     }

     if (userAccessLevel != 0 && userAccessLevel != 100 && userAccessLevel != 255)
     {
          errors.Add("Invalid access level");
     }//verify the access level is a valid value

     //verify the info doesn't already exist
     string select = @"SELECT count(*)
          FROM users
          WHERE displayName='"
+ userDisplayname + @"'";
     SqlDataReader dr = query(select);
     dr.Read();
     if (Convert.ToInt16(dr.GetValue(0)) > 0)
     {
          errors.Add("Display name already exists.");
     }
     dr.Dispose();

     select = @"SELECT count(*)
          FROM users
          WHERE username='"
+ userUsername + @"'";
     dr = query(select);
     dr.Read();
     if (Convert.ToInt16(dr.GetValue(0)) > 0)
     {
          errors.Add("User name already exists.");
     }
     dr.Dispose();

     select = @"SELECT count(*)
          FROM users
          WHERE email='"
+ userEmail + @"'";
     dr = query(select);
     dr.Read();
     if (Convert.ToInt16(dr.GetValue(0)) > 0)
     {
          errors.Add("Email already exists.");
     }
     dr.Dispose();

     if (errors.Count == 0)
     {
          //no errors, save new user
          select = @"INSERT INTO users
               (username, password, displayName, email, showEmail, createDate, accessLevel)
          VALUES
               ('"
+ userUsername + "', '" + FormsAuthentication.HashPasswordForStoringInConfigFile(password1, "MD5") + "', '" + userDisplayname + "', '" + userEmail + "', " + userShowEmail + ", getDate(), " + userAccessLevel + ")";
          dr = query(select);
          if (dr.RecordsAffected > 0)
          {
               errors.Add("User Added");
               userUsername = null;
               userDisplayname = null;
               userEmail = null;
          }
          else
          {
               errors.Add("There has been an error. No records were added.");
          }
          dr.Dispose();
     }
}//end save new user section

This section of code goes directly below the variable initializiation. Please notice that I decided to change the string error into an arraylist called errors. An arraylist is a type of variable, like string and int and bool, but it can hold a series of any other type of variable or object. In this case, I'm having it hold one or more strings. You will need to add the System.Collections namespace to your using list to access the arraylisy type. We'll see how I spit out the results in a moment, but first let's go over the code above. I've removed all references to the error string since we no longer use it.

I create an if block looking to see if option == "Save New User". This lets me execute the new user code when appropriate. I then grab all the passed variables, sanitizing as appropriate. Once I've grabbed the passwords, I immediately make sure they match... if they do not, I add an error to my arraylist. If they do match, I then check to make sure it's not equal to null and that it's at least 6 characters long. I had to check if it's null because I can't use the .Length property on a null string. If I had, the page would throw an exception. If the password is null or too short, I add an error.

Next I make sure the accessLevel is a valid number, in this case 0, 100 or 255. If not I create another error. Following this, I do a series of queries against the user table to verify that the userDisplayname, userUsername and userEmail are not already in use. In each case I add a different error.

After all the error checking, I see if the errors arraylist has a count of 0 (meaning no errors were added) and if so I insert the new user. Once more I use RecordsAffected to make sure the insert worked. There's no reason it shouldn't, of course. If it did succeed, I put a success message into the errors arraylist (because it was convenient) and then wipe out the userUsername, userDisplayname and userEmail fields. By wiping out those three fields, when the add user form is displayed again, it's immediately ready for another new user to be added. That could be very nice if you're trying to add a bunch of users at once.
Comments (0)
So how do we spit out the contents of that errors Arraylist?
"<td colspan=2 class='error'>";
foreach (string error in errors)
{
content += error + "<br>";
}
content += "</td>" +

This is in our form in place of the error string from before. Basically I use the foreach loop to loop through every arraylist item. I've initialized a string variable called error in the loop. Every time the loop executes, the current item in errors gets assigned to the string error. I then spit it out into the form. In most cases this will only be a single error, but it could be any number. This is the advantage of using arraylist and similar variable types.

With this our user management is basically complete. If you wanted to, you could add the ability to selectively reset passwords. However, the basic elements are all in place. We can create, edit and delete users. Following are all the files.

Files To This Point

Next we hit the final portion of our blog, the ability for users and anonymous people to comment.
Comments (0)