Wednesday 20 July 2011

Add CreateUserWizard Steps with ASP.NET 4.0 and C#


This tutorial will demonstrate how to add a new custom step to ASP.NET's CreateUserWizard Control and how to store the extra data gathered in the database with other user information in C#.

Adding the CreateUserWizard Control
At this point in the tutorial I have created a new ASP.NET Empty Web Site in Microsoft Visual Web Developer and added in a blank Web Form named Default.aspx. The first thing we need to do here is add a new CreateUserWizard control, to do this:
  1. Open Default.aspx up to Design Mode.
  2. Expand the Login tab in your toolbox.
  3. Drag and drop a CreateUserWizard Control onto the Web Form.
Adding a New Step to the CreateUserWizard Control
The CreateUserWizard Control is designed to be extremely dynamic so that you can utilize it to get any and all information needed from your users when their accounts are created. One of the ways they accomplish this is by allowing us to add in our own custom steps to the control. Here we will add in a new step to get the user's address information. To do this:
  1. Expand the CreateUserWizard Tasks menu.
  2. SS1.jpg
  3. Click Add/Remove WizardSteps....
  4. In the WizardStep Collection Editor click Add.
  5. Click the UpArrow button to position this step between the Sign Up for Your New Account and Complete steps.
  6. SS2.jpg
  7. Edit the Title property of our new step to say 'Enter Your Address'.
  8. Click OK.
Now that our new step is added, we need to add some content to it so the user can actually enter their information in the appropriate text boxes. To do this:
  1. Expand the CreateUserWizard Tasks menu.
  2. In the DropDownList labeled Step: select the Enter Your Address step.
  3. SS3.jpg
  4. Click in the editable area of the CreateUserWizard Control.
  5. Select from the top menu Table > Insert Table.
  6. Set the Rows to '4' and Columns to '2'.
  7. Click OK.
  8. In the top left cell of the table type in 'Address:'.
  9. In the cell below type in 'City:'.
  10. In the cell below type in 'State:'.
  11. In the cell below type in 'PostalCode:'.
  12. Select these 4 cells and change the Align property to 'right'.
  13. In the top right cell of the table add in a new TextBox and change the ID property to 'txtAddress'.
  14. In the cell below add in a new TextBox and change the ID property to 'txtCity'.
  15. In the cell below add in a new TextBox and change the ID property to 'txtState'.
  16. In the cell below add in a new TextBox and change the ID property to 'txtPostalCode'.

Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.

Now we should have a decent looking form that will prompt the user to enter in the information for their address. If we were going to be using this for something professional we would want to add in some validation for these textboxes to make sure that they are entering information and that it is in the correct format. However, that is out of the scope for this tutorial so we will allow the user to enter anything or choose to leave these blank.

Adding a New Table For Our Data
Next, we are going to enable user creation and examine where the data for a user's account is stored by default. Then, we will add our own table to the database that will hold our new address data and associate it with the user's data from the default database. To enable user creation:
  1. Click the ASP.NET Configuration icon in the Solution Explorer to open up the ASP.NET Website Administration Tool.
  2. In the ASP.NET Website Administration Tool click the Security tab.
  3. Under the Users header click the Select authentication type link.
  4. Select From the internet and click Done.
This has created a new database in our project called ASPNETDB.mdf. To view this:
  1. Click the Refresh icon in the Solution Explorer.
  2. Notice a new folder named App_Data has been added to the project. If you expand this folder you will see the ASPNETDB.mdf database.
What we want to do now is add our own table inside of this database that will hold all of our address info. To do this:
  1. Open the Database Explorer.
  2. Expand the ASPNETDB.mdf data base folder.
  3. Right click on the Tables folder and select Add New Table.
Here we need to add the following columns to the table:

Column Name Data Type
UserId uniqueidentifier
Address varchar(50)
City varchar(50)
State varchar(50)
PostalCode varchar(50)

Once these are added we need to set the primary key for this table, in this case the UserId is going to be our primary key so right click the primary key row and select Set Primary Key.
SS4.jpg
Then save the table as 'm_Addresses'.

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Linking the CreateUserWizard Control to Our Table
Now that we have a place for our data to be stored, we need to direct our CreateUserWizard Control to it so we can store the appropriate data there. What we need to do is add some code that will execute when the finish button on the CreateUserWizard Control is clicked that will insert all of the data in the textboxes we created into our new table. To do this:
  1. Open the Default.aspx page in Design mode.
  2. Right click on the CreateUserWizard Control and click Properties.
  3. In the Properties window click the Events icon.
  4. Double click the FinishButtonClick event to generate the method for this event.
Now that we are in the Default.aspx.cs, we need to specify a few libraries that we will be using to write this code. Add the following code at the top of the class with the other using statements.

using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.Security;
using System.Data;

Next, we need to add the following code to the FinishButtonClick event method:

//After the user is created add the extra address data to the database
SqlConnection mConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);

SqlCommand cmd = new SqlCommand("Insert INTO m_Addresses(UserId, Address, City, State, PostalCode) VALUES (@UserId, @Address, @City, @State, @PostalCode) ", mConnection);

cmd.CommandType = CommandType.Text;
//specify the data to be inserted into the table
cmd.Parameters.AddWithValue("@UserId"Membership.GetUser(CreateUserWizard1.UserName).ProviderUserKey);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@State", txtState.Text);
cmd.Parameters.AddWithValue("@PostalCode", txtPostalCode.Text);

using (mConnection)
{
    mConnection.Open();
    cmd.ExecuteNonQuery();
}

Let's go over this line by line:

SqlConnection mConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
This creates a new SqlConnection to the ASPNETDB.mdf database. By default, a connection string is configured to the database called "LocalSqlServer".
SqlCommand cmd = new SqlCommand("Insert INTO m_Addresses(UserId, Address, City, State, PostalCode) VALUES (@UserId, @Address, @City, @State, @PostalCode) ", mConnection);
This defines a SQL Insert command that will insert the UserId and the data from our text boxes into the m_Addresses table.
cmd.Parameters.AddWithValue("@UserId"Membership.GetUser(CreateUserWizard1.UserName).ProviderUserKey);
This defines the @UserId parameter and sets it to the UserId column associated with the username created. The UserId will be used to link the data from our m_Addresses table to a specific user.
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
This defines the @Address parameter and sets it to the value in the txtAddress textbox.
cmd.Parameters.AddWithValue("@City", txtCity.Text);
This defines the @City parameter and sets it to the value in the txtCity textbox.
cmd.Parameters.AddWithValue("@State", txtState.Text);
This defines the @State parameter and sets it to the value in the txtState textbox.
cmd.Parameters.AddWithValue("@PostalCode", txtPostalCode.Text);
This defines the @PostalCode parameter and sets it to the value in the txtPostalCode textbox.
mConnection.Open();
This opens the connection to our ASPNETDB.mdf database.
cmd.ExecuteNonQuery();
This sends our SQL Insert command to the database.

What we are doing here is simply adding the data the user gave us to the table we just created.

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

Testing
To test this out and ensure that our data is being stored:
  1. Ensure that your CreateUserWizard Control Step is set to Sign Up For Your New Account in the CreateUserWizard Control Tasks menu.
  2. Load up the website.
  3. Create a new account with our CreateUserWizard Control making sure to fill out all of the information in our custom step.
  4. Close the website.
  5. In the Database Explorer right click on the m_Addresses table and select Show Table Data.
  6. Notice that our address information is stored here along with a UserId.
  7. In the Database Explorer right click on the aspnet_Memberships table and select Show Table Data.
  8. Notice that the UserId here matches the UserId in our m_Addresses table, linking the account we just created to the address data we stored.
The Default.aspx source looks like this:
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" ActiveStepIndex="1" 
            onfinishbuttonclick="CreateUserWizard1_FinishButtonClick">
            <WizardSteps>
                <asp:CreateUserWizardStep runat="server" />
                <asp:WizardStep runat="server" Title="Enter Your Address">
                    <table class="style1">
                        <tr>
                            <td align="right">
                                Address:</td>
                            <td>
                                <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td align="right">
                                City:</td>
                            <td>
                                <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td align="right">
                                State:</td>
                            <td>
                                <asp:TextBox ID="txtState" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td align="right">
                                Postal Code:</td>
                            <td>
                                <asp:TextBox ID="txtPostalCode" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                    </table>
                </asp:WizardStep>
                <asp:CompleteWizardStep runat="server" />
            </WizardSteps>
        </asp:CreateUserWizard>
    
    </div>
    </form>
</body>

The Default.aspx.cs code behind looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.Security;
using System.Data;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void CreateUserWizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        //After the user is created add the extra address data to the database
        SqlConnection mConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);

        SqlCommand cmd = new SqlCommand("Insert INTO m_Addresses(UserId, Address, City, State, PostalCode) VALUES (@UserId, @Address, @City, @State, @PostalCode) ", mConnection);

        cmd.CommandType = CommandType.Text;
        //specify the data to be inserted into the table
        cmd.Parameters.AddWithValue("@UserId"Membership.GetUser(CreateUserWizard1.UserName).ProviderUserKey);
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@City", txtCity.Text);
        cmd.Parameters.AddWithValue("@State", txtState.Text);
        cmd.Parameters.AddWithValue("@PostalCode", txtPostalCode.Text);

        using (mConnection)
        {
            mConnection.Open();
            cmd.ExecuteNonQuery();
        }

    }
}

No comments:

Post a Comment