Click here to Skip to main content
15,879,074 members
Articles / Web Development / ASP.NET

Webbased Voting Or Survey Application

Rate me:
Please Sign up or sign in to vote.
4.75/5 (8 votes)
18 Aug 2010CPOL2 min read 28.9K   12   12
Application receives votes from different computer with validation of time limit and displays the same

Introduction

Hello everyone... thank you for giving your time to read this article.

This application simply counts and calculates votes gathered from different clients and finally displays them.

Here, I have kept validation that one user can only vote one time in one Hour of Timespan. Although I have not used any authentication of user, it simply detects IP of voter and stores them in XML file and keeps validating.

Application stores data to XML file rather than database for Quick propagation and flexibility of data, and giving high performance on round trips.

Background

Frankly speaking, I made this application for my use only... there is an interesting reason behind it.

Indian idol season 5 (an Indian Singing competition) was going on those days and there were three finalists and I was very curious to know what my friends think who will finally win the season. FYI, there were three finalists on the floor at that time.

Nothing much interesting about this application. I simply developed it to sharpen my skills in extra time. And I thought someone may find it useful or may be get a path to their application.

Using the Code

Ahh.. The main thing is code.

To store data in XML, I have specified the format stated below.

XML
<?xml version="1.0" encoding="utf-8"?>
<Participants>
  <Participant Name="Sreeram Chandra" ID="SRC" Vote="22">
    <Vote IP="127.0.0.1" DateTime="8/14/2010 2:57:39 PM" HostName="127.0.0.1" />
  </Participant>
  <Participant Name="Bhoomi Trivedi" ID="BT" Vote="23">
    <Vote IP="127.0.0.1" DateTime="8/12/2010 2:59:20 PM" HostName="127.0.0.1" />
    <Vote IP="127.0.0.1" DateTime="8/13/2010 1:57:14 PM" HostName="127.0.0.1" />
    <Vote IP="127.0.0.1" DateTime="8/14/2010 1:06:02 PM" HostName="127.0.0.1" />
  </Participant>
  <Participant Name="Rakesh Maini" ID="RM" Vote="21">
    <Vote IP="127.0.0.1" DateTime="8/15/2010 12:08:59 PM" HostName="127.0.0.1" />
    <Vote IP="127.0.0.1" DateTime="8/16/2010 1:08:00 PM" HostName="127.0.0.1" />
  </Participant>
</Participants>

Let's dig into the above XML format. In that, you will find root node which depicts participants, I mean the people or things for which polling is to be done and under that node, there is another node called Vote which is the sub-node of Participants which is Vote given by an individual user so that we can keep history of vote and can store IP of voters.

C#
public class VoteParticipant
{
    public string Name { get; set; }
    public List<voters> VotersList { get; set; }
    public string ID { get; set; }
    public int Vote { get; set; }
    
    public static void insertVotetoXML(Voters vote,string FileName)
    {
        String VoteXMLPath = HttpContext.Current.Server.MapPath(FileName);
        XmlDocument XmlDoc = new XmlDocument();
        XmlDoc.Load(VoteXMLPath);
        XmlNodeList nodeList = XmlDoc.GetElementsByTagName("Participant");
        foreach (XmlNode node in nodeList)
        {
            if (node.Attributes["ID"].Value == vote.ID)
            {
                XmlNode newNode = XmlDoc.CreateNode(XmlNodeType.Element, "Vote", "");
                newNode.Attributes.Append(XmlDoc.CreateAttribute("IP"));
                newNode.Attributes.Append(XmlDoc.CreateAttribute("DateTime"));
                newNode.Attributes.Append(XmlDoc.CreateAttribute("HostName"));
                newNode.Attributes["IP"].Value = vote.IP;
                newNode.Attributes["DateTime"].Value = vote.VoteDateTime.ToString();
                newNode.Attributes["HostName"].Value = vote.HostName;
                node.AppendChild(newNode);
                node.Attributes["Vote"].Value = 
		(int.Parse(node.Attributes["Vote"].Value) + 1).ToString();
                XmlDoc.Save(VoteXMLPath);
            }
        }
        SetVoteQuote(FileName, vote);
    }

    private static void SetVoteQuote(string FileName,Voters vote)
    {
        List<poll> pollList = PollGenerator.returnPolls().Where
			(p => p.XmlFileName == FileName).ToList();
        List<voteparticipant> participantList = VoteParticipant.GetParticipants
			(FileName).Where(p=>p.ID==vote.ID).ToList();
        QuoteService.Gotten.Add(new VoteQuote() 
		{ DateTime = vote.VoteDateTime, FromIP = vote.IP, 
		ParticipantName = participantList[0].Name, 
		PollName = pollList[0].Title });
    }
    public static List<voteparticipant> GetParticipants(string FileName)
    {
        String VoteXMLPath = HttpContext.Current.Server.MapPath(FileName);
        XmlDocument XmlDoc = new XmlDocument();
        XmlDoc.Load(VoteXMLPath);
        XmlNodeList nodeList = XmlDoc.GetElementsByTagName("Participant");
        List<voteparticipant> iList = new List<voteparticipant>();
        foreach (XmlNode node in nodeList)
        {
            VoteParticipant objParticipant = new VoteParticipant();
            objParticipant.ID = node.Attributes["ID"].Value.ToString();
            objParticipant.Name = node.Attributes["Name"].Value.ToString();
            objParticipant.Vote = int.Parse(node.Attributes["Vote"].Value.ToString());
            List<voters> objVoters = new List<voters>();
            if (node.HasChildNodes)
            {
                XmlNodeList childNodes = node.ChildNodes;
                foreach (XmlNode childNode in childNodes) 
                {
                    objVoters.Add(new Voters 
			{ ID = node.Attributes["ID"].Value, 
			IP = childNode.Attributes["IP"].Value, 
			VoteDateTime = DateTime.Parse(childNode.Attributes
			["DateTime"].Value), 
			HostName = childNode.Attributes["HostName"].Value });
                }
            }
            objParticipant.VotersList = objVoters;
            iList.Add(objParticipant);
        }
        return iList;
    }
}
public class Voters
{
    public string ID { get; set; }
    public string IP { get; set; }
    public DateTime VoteDateTime { get; set; }
    public string HostName { get; set; }
    public Voters() { }
}

The above C# code depicts the following things:

C#
Class VoteParticipant

    public static void insertVotetoXML(Voters vote,string FileName)

    public static List<voteparticipant /> GetParticipants(string FileName)

Class Voters

Above, there are two classes: one is voteparticipant which has two methods to insert newly created vote to XML and another is to get whole XML in a Votepartcipant List format to get all the participants and all the voters belonging to that participant.

Now take a look at the ASPX page structure:

XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Vote your Vote</title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="Header">
        <span id="spnTitle" runat="server" style='font-weight:15px;
		font-weight:bold;font-family:Verdana;color:Blue'>
        <asp:Label ID="lblTitle" runat="server"></asp:Label>
        </span>
    </div>
    <div id="divVote" runat="server">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
        </asp:RadioButtonList>
        <asp:Button ID="btnVote" runat="server" Text="VOTE" OnClick="btnVote_Click" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="RadioButtonList1" 
            ErrorMessage="Select one of Participant First"></asp:RequiredFieldValidator>
    </div>
    <div id="divResult" runat="server">
        <asp:GridView ID="grdResult" runat="server" onrowcreated="grdResult_RowCreated">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

And also look at the Back End of the Form:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Vote : System.Web.UI.Page
{
    string CurrentxmlFileName = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentxmlFileName = Server.MapPath("VoteXML.xml");
            
        if (!Page.IsPostBack)
        {
            lblTitle.Text = PollGenerator.GetTitle(CurrentxmlFileName);
            bool Flag = true;
            List<voteparticipant> objParticipants = 
		VoteParticipant.GetParticipants(CurrentxmlFileName);
            foreach (VoteParticipant participan in objParticipants)
            {
                List<voters> voters = participan.VotersList;
                foreach (Voters vote in voters)
                {
                    if (vote.IP == Request.ServerVariables["REMOTE_ADDR"].ToString())
                    {
                        DateTime VoteTime = vote.VoteDateTime;
                        TimeSpan ts = DateTime.Now.Subtract(VoteTime);
                        if (!(ts.Hours >= 1))
                        {
                            Flag = false;
                        }
                    }
                }
            }
            if (Flag)
            {
                ShowVote();
                List<voteparticipant> SettoRadioButton = VoteParticipant.GetParticipants
						(CurrentxmlFileName);
                foreach (VoteParticipant participant in SettoRadioButton)
                {
                    RadioButtonList1.Items.Add(new ListItem
				(participant.Name, participant.ID));
                }
            }
            else
            {
                PopulateResult();
                ShowResult();
            }            
        }
    }
    protected void btnVote_Click(object sender, EventArgs e)
    {
        Voters vote = new Voters();
        vote.HostName = Request.ServerVariables["REMOTE_HOST"].ToString();
        vote.ID = RadioButtonList1.SelectedItem.Value;
        vote.IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
        vote.VoteDateTime = DateTime.Now;
        VoteParticipant.insertVotetoXML(vote, CurrentxmlFileName);
        PopulateResult();
        ShowResult();
    }

    private void PopulateResult()
    {
        DataTable Table = new DataTable();
        Table.Columns.Add("Name");
        Table.Columns.Add("(%)Vote");
        Table.Columns.Add("Real Vote");
        int TotalVote = 0;
        List<voteparticipant> GetResult = 
		VoteParticipant.GetParticipants(CurrentxmlFileName);
        foreach (VoteParticipant participant in GetResult)
        {
            TotalVote = TotalVote + participant.Vote;
        }
        foreach (VoteParticipant participant in GetResult)
        {
            string Name = participant.Name;
            int PerVote = 0;
            if (TotalVote > 0)
            {
                PerVote = (participant.Vote * 100) / TotalVote;
            }
            int PartVote = participant.Vote;

            Table.Rows.Add(new string[3] { Name, PerVote.ToString() + 
					"%", PartVote.ToString() });
        }
        grdResult.DataSource = Table;
        grdResult.DataBind();
    }
    protected void ShowResult()
    {
        Page.FindControl("divVote").Visible = false;
        Page.FindControl("divResult").Visible = true;
    }
    protected void ShowVote()
    {
        Page.FindControl("divVote").Visible = true;
        Page.FindControl("divResult").Visible = false;
    }
    protected void grdResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        string onMouseOverStyle = "this.style.backgroundColor='blue';
				this.style.color='white';";
        string onMouseOutStyle = "this.style.backgroundColor='@backgroundColor';
				this.style.color='@ForeColor'";
        string RowBackColor = String.Empty;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", onMouseOverStyle);
            e.Row.Attributes.Add("onmouseout", onMouseOutStyle.Replace
		("@backgroundColor", "White").Replace("@ForeColor", "black"));
        }
    }
}

Nothing new in the above code, it just checks on the page Load event that if the user(dedicated IP) has already voted in one hour of timespan, then it will instantly show them a Result division directly, and if not, then it takes to Voting Division.

Points of Interest

Just for fun!!!

Enjoy!!!

History

  • 18th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
He is a Smart IT devloper with Few years of Expeariance But having Great command on ASP.net,C#,SQL Query,SSRS,Crystal Reports

Apart from that He Loves multimedia work too, Master of Adobe photoshop, Illustrator, CSS , HTML and all things.

He is Currently working in Microsoft Dynamics CRM and Having Nice Expearince with CRM. CRM Rocks!!!

Comments and Discussions

 
GeneralMy vote of 5 Pin
dental implant23-Jul-23 6:16
professionaldental implant23-Jul-23 6:16 
BugIncomplete code Pin
adeelgr8one23-Mar-12 20:05
adeelgr8one23-Mar-12 20:05 
QuestionAwesome! Pin
Member 867945726-Feb-12 12:57
Member 867945726-Feb-12 12:57 
GeneralMy vote of 3 Pin
uspatel14-Dec-11 19:23
professionaluspatel14-Dec-11 19:23 
Generalsome classe does not in this code Pin
uspatel14-Dec-11 19:23
professionaluspatel14-Dec-11 19:23 
GeneralMy vote of 1 Pin
Denno.Secqtinstien23-Mar-11 0:09
Denno.Secqtinstien23-Mar-11 0:09 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»26-Sep-10 22:36
professionalKunal Chowdhury «IN»26-Sep-10 22:36 
GeneralRe: My vote of 5 Pin
Hiren solanki27-Sep-10 20:46
Hiren solanki27-Sep-10 20:46 
Generalgood work Pin
Sandeepkumar Ramani18-Aug-10 19:54
Sandeepkumar Ramani18-Aug-10 19:54 
GeneralRe: good work [modified] Pin
Hiren solanki18-Aug-10 22:40
Hiren solanki18-Aug-10 22:40 
GeneralMy vote of 3 Pin
Sandeepkumar Ramani18-Aug-10 19:53
Sandeepkumar Ramani18-Aug-10 19:53 
GeneralRe: My vote of 3 [modified] Pin
Hiren solanki18-Aug-10 22:40
Hiren solanki18-Aug-10 22:40 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.