Click here to Skip to main content
Click here to Skip to main content

Creating a Poll System Using ASP.NET 2.0 Callbacks

By , 18 Nov 2007
 

Introduction

Creating a poll on your website enables you to find out more about the interests of the user. I recently added a weekly poll system to KofeeKoder. In this article, I will explain how to create an AJAX enabled polling system using ASP.NET client callbacks.

Database Schema

The database schema consists of only two tables:

  1. PollQuestions: This table holds all the questions for the poll
  2. PollChoices: This table holds the choices of the poll questions

Take a look at the schema shown below:

Stored Procedure

CREATE PROCEDURE usp_GetLastestPoll

AS

DECLARE @pqID int
SELECT @pqID = MAX(PollQuestionID) FROM PollQuestions
PRINT @pqID

SELECT q.PollQuestionID,q.[Text] AS PollText,c.PollChoiceID,
  c.[Text] ChoiceText,c.Total FROM PollQuestions q JOIN PollChoices c
  ON q.PollQuestionID = c.PollQuestionID WHERE q.PollQuestionID = @pqID

GO

Poll Control Architecture

I wanted to create the polling user control in such a way that it does not depend on the page. Let's take a look at the class diagram below:

Now, let me explain each class in detail:

  • IPoll<code>: IPoll is an interface which will be used by all the polling classes
  • WeeklyPoll: This is the class responsible for creating weekly polls. It implements the IPoll interface
  • PollQuestion: This is an entity class which maps to the PollQuestions table in the database
  • PollChoice: This is an entity class which maps to the PollChoices table in the database
  • PollTableHelper: This is a helper class which is used to generate dynamic HTML tables
  • ControlToHtmlConvertor: This class contains helper methods to convert a control into pure HTML
  • DataAccess: This class serves as the DataAccess class and is used to INSERT and SELECT polls from the database

Implementation

Let's dive into the implementation details. We will see few important classes in this article. For complete implementation, you can use the code given below in this article.

IPollInterface

The IPollInterface is implemented by all classes that want to expose polling functionality.

public interface IPoll
    {
        string Create();
        string GetStats();
    }

WeeklyPoll

WeeklyPoll is one of the classes that implements the IPoll interface. The implementation is given below:

public class WeeklyPoll : IPoll
    {
        public string Create()
        {
            PollQuestion poll = PollQuestion.GetPoll();
            return PollTableHelper.GenerateTableForPoll(poll);
        }

        public string GetStats()
        {
            PollQuestion poll = PollQuestion.GetPoll();
            return PollTableHelper.GetPollStats(poll);
        }
    }

I will not discuss the PollTableHelper class since the code is simply used to build a table. You can download the complete code available for download at the top of this article and view the implementation.

PollControl.ascx

The PollControl.ascx is a user control which is used to display the poll to the user. Let's first take a look at the HTML code for the PollControl.ascx control.

Yup, that's it!

Now, let's take a look at the code behind:

protected void Page_Load(object sender, EventArgs e)
        {
               RegisterCallbacks();
        }

        private void RegisterCallbacks()
        {

        string sbReference = Page.ClientScript.GetCallbackEventReference
            (this, "arg", "ReceiveServerData", "context");
        string cbScript = String.Empty;
        // check if the script is already registered or not
        if (!Page.ClientScript.IsClientScriptBlockRegistered("CallServer"))
        {
            cbScript = @" function CallServer(arg,context) 
                { " + sbReference + "} window.setTimeout(CallServer,100); ";
            Page.ClientScript.RegisterClientScriptBlock
                (this.GetType(), "CallServer", cbScript, true);
        }

        }

In the code above I am simply registering the callbacks. If you are interested in learning more about how to register the page/usercontrol to use callbacks, then take a look at this article.

Everything about registering the callback method is the same except the call to the window.setTimeout function. I made this call so I can fire the CallServer method right after registering it on the page. I know you must be thinking why not simply fire CallServer('', '') at the end of the callback registration process. Unfortunately, this technique does not work since the CallServer takes arguments from the page.

For the callbacks to work, you must implement the ICallbackEventHandler interface as shown below:

public partial class PollControl : 
    System.Web.UI.UserControl, ICallbackEventHandler

The ICallbackEventHandler interface consists of two methods namely, GetCallbackResult and RaiseCallbackEvent. Let's see the implementation below:

public void RaiseCallbackEvent(string eventArgument)
        {
            // update the polls
            string[] selection = eventArgument.Split(':');
            if (selection.Length > 1)
            {
                PollQuestion.Update(Int32.Parse(selection[0]), 
                    Int32.Parse(selection[1]));
                // create a cookie for the user
                CreatePollCookie();
            }
        }

The RaiseCallbackEvent is fired when the user casts the vote using the "Vote" button. I check if the user has selected some choice and if so, update the choice in the database. After updating the choice I also create a cookie so that the user will not be able to vote for some time.

I could have also used IP address to keep track of which user has given a vote but using IP address has some disadvantages. If a person is on a LAN which is behind a firewall then the vote given by him will be the vote for the entire LAN since computers connected to the LAN are behind a firewall giving them the same IP address.

The CreatePollCookie is used to create HttpCookie:

private void CreatePollCookie()
    {
        HttpCookie pollCookie = new HttpCookie("PollCookie");
        pollCookie.Value = "PollCookie";

      pollCookie.Expires = DateTime.Now.AddDays(7);
        Response.Cookies.Add(pollCookie);
    }

The method GetCallbackResult is fired right before sending the contents to the client.

public string GetCallbackResult()
        {
            string result = String.Empty;
            IPoll poll = new WeeklyPoll();

            if (DoesCookieExists())
            {
                result = poll.GetStats();
            }
            else
            {
                result = poll.Create();
            }

            return result;
        }

The method DoesCookieExists ensures that if the client has already voted, then you need to show her or him the vote statistics, otherwise show the poll. This is performed by checking for the existence of the cookie.

  private bool DoesCookieExists()
        {
            if (Request.Cookies["PollCookie"] != null) return true;
            else return false;
        }

The JavaScript Code

All the JavaScript code is stored in the Site.js file. All the pages of the website must have a reference to the JS file for the poll control to work.

function vote()
{
    var pollWidget = document.getElementById("divPoll");
    var inputElements = pollWidget.getElementsByTagName("INPUT");
    var userSelection;

    for(i=0; i<inputElements.length;i++)
    {
        if(isRadioButton(inputElements[i]))
        {
            if(inputElements[i].checked)
            {
                userSelection = inputElements[i].id;
                break;
            }
        }
    }

    // call the server method to note the changes
    CallServer(userSelection,'');
}

function ReceiveServerData(rValue)
{
    document.getElementById("divPoll").innerHTML = rValue;
}

function isRadioButton(target)
{
    return target.type == 'radio';
}

You can see the polling control live in action on the upper right hand side of the screen. Hey! When you are there, please do cast your vote!

I hope you liked the article, happy programming!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

azamsharp
Web Developer
United States United States
Member
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 2memberNnamdi00719 Apr '13 - 3:09 
No Working Demo
GeneralMy vote of 3memberalexfire25 Aug '10 - 4:51 
jghjghjghj
GeneralMy vote of 4memberrvargas152 Jul '10 - 9:36 
test
Generalsos! compilation errormemberthe bill8 Feb '08 - 11:37 
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
 
Compiler Error Message: The compiler failed with error code 1.
 
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.1433
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.
 
c:\Inetpub\wwwroot\WebSite\PollControl.ascx.cs(912305,33): error CS0115: 'ASP.pollcontrol_ascx.FrameworkInitialize()': no suitable method found to override
GeneralRe: sos! compilation errormemberthe bill8 Feb '08 - 12:55 
now i get The target '__Page' for the callback could not be found or did not implement ICallbackEventHandler.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: System.InvalidOperationException: The target '__Page' for the callback could not be found or did not implement ICallbackEventHandler.
 
Source Error:
 

Line 18: private void RegisterCallbacks()
Line 19: {
Line 20: string sbReference = Page.ClientScript.GetCallbackEventReference (this, "arg", "ReceiveServerData", "context");
Line 21: string cbScript = String.Empty;
Line 22: // check if the script is already registered or not


the inherits IPoll had been commented out in the code i downloaded
QuestionNot able to run codemembershahzadsb005 Dec '07 - 1:20 
i am not able to run code of this project.
It is giving me error that
 
"The project type is not supported by this installation"
 
Any idea ....!!
GeneralRe: Not able to run codememberazamsharp5 Dec '07 - 5:37 
What framework are you using?
 
Mohammad Azam
azamsharp@gmail.com
www.KoffeeKoder.com
Houston, TEXAS

AnswerRe: Not able to run codememberAntony M Kancidrowski15 May '08 - 0:49 
This is most likely a problem with the version of Visual Studio that you are using. The solution is for VS2005, if you are running the Express version that may be the problem.
 
You can always create a blank solution and add the source files to that.
 
Ant.
 
I'm hard, yet soft.
I'm coloured, yet clear.
I'm fruity and sweet.
I'm jelly, what am I? Muse on it further, I shall return!


- David Walliams (Little Britain)

Generalsuggestionmemberwissam14 Dec '07 - 19:11 
Hi Azam,
 
Thank you for the useful article.
 
According to the line:
 
PollQuestion.Update(Int32.Parse(selection[0]), Int32.Parse(selection[1]))
 
You pass both the questioned and the choiceid to the update method but your PollChoice Table contains the choiceid as a PK then in your case you don’t need to pass only the choiceid,but if you want to make the same sequence number for the choices for multiple questions(ex: choice 1,2,3,4 for question1 and choice 1,2,3,4 for question2) then you have to make both the questioned and the choiceid as PK(Composite key) then in this case you have to pass the questioned and the choceid for the update method.
 
Another thing that you have a gap in your article when you check if the cookie exists or not, suppose a certain user delete the cookie before it expires then he can vote another time for the same question,you speak about the ip address but I don’t understand exactly what you say,but I suggest to make a table that contains the userid and questionid and both of them are primary key (called it VotesTracking) and when the user vote for a certain question then add a record by the userid and the questionid and through your application after you get the latest poll you can check if the user has record for this question in the table and based on this you can createpoll or show the statistics.
 
And if you want to track the votes then you can add Choiceid,VotedDate to the VotesTracking table then later you can make a report.
 
Your help is highly appreciated
 
Best regards.
GeneralRe: suggestionmemberazamsharp5 Dec '07 - 5:43 
Hi Wissam,
 
Thanks for your comments. I am passing the questionID and the choiceID back so I know which question was presented and what choice user selected.
 
1,3 means that question 1 and choice 3. Question1 means the poll question like "What is the capital of Texas?" and choices means selections like "Houston", "Austin","Dallas" etc.
 
Off course you can delete cookie and vote again! There are couple of ways you can stop this. One is to make user sign in (authenticated account) to vote. Another is to extract the IP of the user and put it in database when he has voted but then this would not be fair to ppl who have only a single computer at home as all of them can vote only once.
 
For a simple poll application like this one I just stayed with cookies.
 
Also, I noticed that in my article above some HTML code is missing maybe due to the code project format. You can also view the article at the following link:
 
http://koffeekoder.com/ArticleDetails.aspx?id=322[^]
 
Mohammad Azam
azamsharp@gmail.com
www.KoffeeKoder.com
Houston, TEXAS

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 18 Nov 2007
Article Copyright 2007 by azamsharp
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid