Adding the Default.aspx Page
At this point in the tutorial I have created a new ASP.NET Empty Web Site. Next, we need to add a simple form that will allow a user to login and vote. To do this:
  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a loginview control onto the web form.
  8. Expand the loginview tasks menu and select AnonymousTemplate from the drop down list.
  9. Drag and drop a login control into the loginview.
  10. Underneath the loginview add in a new table that has 2 rows and 2 columns.
  11. Drag and drop a label into the top left cell of the table.
  12. Change the ID property of the label to ‘lblA’.
  13. Drag and drop a label into the top right cell of the table.
  14. Change the ID property of the label to ‘lblB’.
  15. Drag and drop a button into the bottom left cell of the table.
  16. Change the ID property of the button to ‘btnA’.
  17. Change the Text property of the button to ‘Vote A’.
  18. Drag and drop a button into the bottom right cell of the table.
  19. Change the ID property of the button to ‘btnB’.
  20. Change the Text propert of the button to ‘Vote B’.
You should now have a simple form that looks like this: 
Adding the DatabaseNext, we need to add in a database with a few small tables that will allow us to keep track of the votes. To do this:
  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder.
  5. Select add new item…
  6. Select a SQL Database.
  7. Name it ‘Database.mdf’.
  8. Click add.
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
Next, we need to add in two tables, one to keep track of the votes and one to keep track of the users who have already voted. To do this:
  1. Expand the Database.mdf folder in your server/database explorer.
  2. Right click the Tables folder.
  3. Select add new table
  4. Add the following columns with their respective types to the table:
    Column Name Data Type 
    VoteId nvarchar(50) 
    NumVotes int 
  5. Save the table as ‘Votes’.
  6. Right click the Tables folder.
  7. Select add new table.
  8. Add the following columns with their respective types to the table:
    Column Name Data Type 
    UserName nvarchar(50) 
  9. Save the table as ‘Voted’.
Next, we need to add some sample data to the Votes table. To do this:
  1. Right click the Votes table.
  2. Select Show Table Data.
  3. Add the following rows to the table:
    VoteId NumVotes 
    39 
    42 
Adding the ConnectionStringNow that we have our database setup, we need to add a connection string to it. To do this, add in the following code to the Web.Config file in between the <configuration> and <system.web> tags:
Code Block
Web.Config
The connection string to our database.
<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
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.
Enabling and Creating UsersIn order for us to vote, we are going to need to be logged in to an account. To enable user creation and create a new user:
  1. Click the ASP.NET Configuration icon in your solution explorer.
  2. In the ASP.NET Web Site Administration Tool click the Security tab.
  3. Click Select authentication type.
  4. Select From the internet.
  5. Click Done.
  6. Click Create User.
  7. Fill out the information and create a new account.
  8. Close the ASP.NET Web Site Administration Tool.
Adding the Voting FunctionalityNext, we need to add in some C# code that will allow us to vote if we are logged in and have not yet voted. To avoid incorrect polls we avoid letting users vote more than one time. Here I am going to limit their voting by 1 vote per unique username, however we can just as easily limit this another way by using something like an IP or even a MAC address. To begin, open up Default.aspx.cs up for editing and add the following code to the Page_Load event method:
Code Block
Default.aspx.cs
The Page_Load event method.
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataReader rdr;
    //GET # OF VOTES TO DISPLAY
    //connect to our db
    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
 
    //sql command to select everything from the first table
    SqlCommand cmd = new SqlCommand("SELECT * FROM Votes", conn);
    cmd.CommandType = CommandType.Text;
 
    using (conn)
    {
        //connect to the database
        conn.Open();
        //execute the qeury and store the results in our sqldatareader
        rdr = cmd.ExecuteReader();
        //read all entries and populate our labels and buttons
        while (rdr.Read())
        {
            if (rdr["VoteId"].ToString() == "A")
                lblA.Text = rdr["NumVotes"].ToString();
            if (rdr["VoteId"].ToString() == "B")
                lblB.Text = rdr["NumVotes"].ToString();
        }
    }
 
    //disable the voting buttons until we can verify that the current user is eligible
    btnA.Enabled = false;
    btnB.Enabled = false;
 
    //if user is currently logged in
    if (Page.User.Identity.IsAuthenticated)
    {
        //check if user is in the database
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        //the sql command to select the current user from the voted table
        cmd = new SqlCommand("SELECT * FROM Voted WHERE UserName=@UserName", conn);
        cmd.CommandType = CommandType.Text;
 
        cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);
 
        using (conn)
        {
            //connect to the database
            conn.Open();
            //execute query and store results in our sqldatareader
            rdr = cmd.ExecuteReader();
            //if no entries are read
            if (!rdr.Read())
            {
                //user was not found, they are eligible
                //enable buttons for voting
                btnA.Enabled = true;
                btnB.Enabled = true;
            }
 
        }
    }
 
}
This code will determine whether or not to enable the voting buttons based on if the user is logged in and has already voted or not. Next, we are going to write a method that will actually submit a Vote given a VoteId passed by a string to it. To do this, add the following method to the Default.aspx.cs class under the Page_Load method:
Code Block
Default.aspx.cs
The Vote method.
private void Vote(string VoteId)
{
    //ADD THEIR VOTE
    //connect to our db
    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    //command to increment the vote at the proper id
    SqlCommand cmd = new SqlCommand("UPDATE Votes SET NumVotes = NumVotes+1 WHERE VoteId=@VoteId", conn);
    cmd.CommandType = CommandType.Text;
 
    cmd.Parameters.AddWithValue("@VoteId", VoteId);
 
    using (conn)
    {
        //connect to the database
        conn.Open();
        //execute query
        cmd.ExecuteNonQuery();
    }
 
    //ADD THEIR NAME TO THE VOTED DATABASE SO THAT THEY WILL NOT BE ALLOWED TO VOTE AGAIN
    //connect to our db
    conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    //command to add their username to out voted table
    cmd = new SqlCommand("INSERT INTO Voted(UserName) VALUES (@UserName)", conn);
    cmd.CommandType = CommandType.Text;
 
    cmd.Parameters.AddWithValue("@UserName", Page.User.Identity.Name);
 
    using (conn)
    {
        //connect to the database
        conn.Open();
        //execute query
        cmd.ExecuteNonQuery();
    }
 
    //reload the page
    Response.Redirect("Default.aspx");
}
This will first increment the vote number in the proper cell of the Votes table based on the VoteId passed to it, and then add the current username to the Voted table which gets checked when the voting buttons are enabled. This will prevent the user from voting again. Next, we need to add in the code for the voting buttons. To do this, open up Default.aspx to design mode and double click btnA and add the following code to the btnA_Click event method:
Code Block
Default.aspx.cs
The btnA_Click event method.
protected void btnA_Click(object sender, EventArgs e)
{
    //call the vote method passing the A option
    Vote("A");
}
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.
This will call the Vote method we added earlier, passing the VoteId for option ‘A’ that the user has chosen to vote for. Next, we need to do the same thing for btnB, go back to the Default.aspx and double click btnB and add the following code to the btnB_Click event method:
Code Block
Default.aspx.cs
The btnB_Click event method.
protected void btnB_Click(object sender, EventArgs e)
{
    //call the vote method passing the B option
    Vote("B");
}
This will call the Vote method passing the Voted for option ‘B’.
TestingTo test this out, go ahead and load up the web site. Login to the account that you created earlier and choose to vote for option ‘A’ by clicking btnA. Notice that the page is reloaded and the buttons are now disabled even though you are logged in, this is because your account has already voted. Navigate to the Votes table in your database, right click it, and select Show Table Data. Notice that the number of votes corresponding to option ‘A’ has increased from 39 to 40. This is not the most secure voting system, but it is fairly easy to implement and will limit each account to one vote while keeping an accurate count of all votes.