poll results

Introduction

The subject of our new article is to develop a simple and a nice poll application that we can use in our web-sites. Although most of the samples use the database to save the poll data, our choice will be xml.

Why Xml?

In practice, the internet users aren't so interested in the applications such as polls. In this case, we can assume that lots of people cannot vote simultaneously. In such cases, using xml data structure will be a logical choice in order for performance and coding.

Poll Data

We are keeping all of the data about the poll in a xml file. As its structure, while the value offered to the user is being kept in the node attributes, the poll data collected will be kept in the nodes.

<?xml version="1.0" encoding="iso-8859-9" ?>
<poll name="Which OS do you use?">
  <answer text="Windows?">60</answer>
  <answer text="Mac OS">15</answer>
  <answer text="Linux">8</answer>
  <answer text="BeOS">2</answer>
</poll>
soluiton.gif

Note : Keeping the data files under the App_Data will prevent the users from accessing it directly.

Poll Web User Control

In order for providing an easy usage within the site, we are designing the poll application as a web user control. Because the application has two different appereances, we are dividing our ascx file into two logical parts by providing benefits from MultiView control. The first one is the part that includes the poll questions and also it is the part that the user will vote and the other part will be the one that they will see the poll results.
    <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
    <asp:View ID="View1" runat="server">
        <table>
            <tr>
                <td id="header">
                    POLL
                </td>
            </tr>
            <tr>
                <td id="head">
                    <asp:Label ID="lblHead" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:RadioButtonList ID="rbQ" runat="server" Width="95%">
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <td id="footer">
                    <asp:Button ID="btnSubmit" runat="server" 
                     OnClick="btnSubmit_Click" Text="Submit" />
                </td>
            </tr>
        </table>
    </asp:View>
    <asp:View ID="View2" runat="server">
        <asp:Xml ID="Xml1" runat="server" DocumentSource="~/App_Data/pollData.xml" 
         TransformSource="~/App_Data/pollView.xsl"></asp:Xml>
    </asp:View>
</asp:MultiView>

Writting Code

When the web form is first loaded, by using LinqToXml, we are getting the data from the xml file.

            if (!IsPostBack)
            {
                if (IsExist(GetIpAddress()))
                    MultiView1.ActiveViewIndex = 1;
                else
                {
                    MultiView1.ActiveViewIndex = 0;
                    pollInformation();
                }
            }

        void pollInformation()
        {
            string path = Server.MapPath(@"App_Data/pollData.xml");
            //input xml doc
            XDocument myXml = XDocument.Load(path);
            //get header
            lblHead.Text = myXml.Element("Poll").Attribute("name").Value;
            //get answers
            foreach (var att in myXml.Element("Poll").Elements("answer"))
                rbQ.Items.Add(att.Attribute("text").Value);
        }

After loading the file into the memory with the XDocument, one by one;
-we are setting the poll header to the Text property of the Label control
-we are adding the questions(items count) to the RadioButtonList as an Item.

         
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string IpAddress = GetIpAddress();
            if (rbQ.SelectedValue != string.Empty && !IsExist(IpAddress))
            {
                string path = Server.MapPath(@"App_Data/pollData.xml");
                //input xml doc
                XDocument myXml = XDocument.Load(path);
                //get value of vote
                int value = Convert.ToInt32(myXml
                    .Descendants("answer")
                    .Where(n => ((string)n.Attribute("text").Value == rbQ.SelectedValue)).Single().Value);
                //increase value +1
                value++;
                //set new value of vote
                myXml.Descendants("answer").Single(n => ((string)n.Attribute("text").Value == rbQ.SelectedValue)).Value = value.ToString();
                //save xml doc
                myXml.Save(path);
                //add ipaddress
                AddIpAddress(IpAddress);
            }
            MultiView1.ActiveViewIndex = 1;
        }

In the voting part of poll whose presentation is completed, we are increasing the value of the node which belongs to the selected question to 1. In order to do this, we are querying the value of the selected item from radiobuttonlist control according to the belonging property and we'll get the concerned value. And then we are saving the xml data again.

Poll Results with Xslt

And now it is time for viewing the poll results. We are showing the data which is based on the idea that if there is a xml there is also xslt.

 <?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:variable name="summ" select="sum(Poll/answer)"></xsl:variable>
    <table>
      <tr>
        <td id="header" colspan="3">POLL RESULTS</td>
      </tr>
      <tr>
        <td id="head" colspan="3">
          <xsl:value-of select="Poll/@name"/>
        </td>
      </tr>
      <xsl:for-each select="Poll/answer">
        <tr>
          <td width="120">
            <xsl:value-of select="@text"/>
          </td>
          <td id="value">
            %<xsl:value-of select="format-number(. * 100 div $summ,'0')"/>
          </td>
          <td width="100">
            <xsl:variable name="innerSumm" select=". * 100 div $summ"></xsl:variable>
            <img src="images/bar.png" height="10" width="{$innerSumm}%" />
          </td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

It is doubtless that, the most important part in here is calculating the percentage of the votes

%<xsl:value-of select="format-number(. * 100 div $summ,'0')"/>

and determininig the bar of poll picture according to the percentage.

<img src="images/bar.png" height="10" width="{$innerSumm}%" />

Result

We have seen that the couple xml and xslt produce lots of practical results one more time. Our aim is not to write too much code, but to use the technology efficiently and in place.

Update

Preventing multiple votes.

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架