Click here to Skip to main content
15,923,006 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Guys ,

I found an very resourceful implementation of online quiz .
Online Quiz[^]

But the problem is i wish to reuse this code and written in C# with code behind form.

I have been trying to convert but end up with ton of error. will be graceful if any one can figure it out.
I be deeply appreciate .

the code behind ,quiz.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;

public partial class _Default : System.Web.UI.Page
{
    //Relative file path to XML data

    string strXmlFilePath = Server.MapPath("quiz.xml");
    XPathDocument xDoc = new XPathDocument(strXmlFilePath);
    XPathNavigator xNav = xDoc.CreateNavigator;

    XPathNodeIterator xNodeIterator;
    //Initialize variables
    int intTotalQuestion;
    int intQuestionNo = 1;
    int intScore = 0;

    ArrayList arrAnswerHistory = new ArrayList();

    public void Page_Load(object sender, EventArgs e)
    {
        //Start a new quiz?

        if (!Page.IsPostBack)
        {
            //Yes! Count total question
            intTotalQuestion = xNav.Select("/quiz/mchoice").Count;

            //Record start time
            ViewState["StartTime"] = DateTime.Now;

            ShowQuestion(intQuestionNo);
        }
    }



    public void btnSubmit_Click(object src, EventArgs e)
    {
        //Retrieve essential variables from state bag
        intTotalQuestion = ViewState["TotalQuestion"];
        intQuestionNo = ViewState["QuestionNo"];
        intScore = ViewState["Score"];
        arrAnswerHistory = ViewState["AnswerHistory"];

        //Correct answer?
        if (rblAnswer.SelectedItem.Value == ViewState["CorrectAnswer"])
        {
            intScore += 1;
            arrAnswerHistory.Add(0);
        }
        else
        {
            arrAnswerHistory.Add(rblAnswer.SelectedItem.Value);
        }

        //End of quiz?

        if (intQuestionNo == intTotalQuestion)
        {
            //Yes! Show the result...
            QuizScreen.Visible = false;
            ResultScreen.Visible = true;

            //Render result screen
            ShowResult();


        }
        else
        {
            //Not yet! Show another question...
            QuizScreen.Visible = true;
            ResultScreen.Visible = false;
            intQuestionNo += 1;

            //Render next question
            ShowQuestion(intQuestionNo);
        }
    }


    public void ShowQuestion(int intQuestionNo)
    {
        string strXPath = null;
        int intLoop = 0;
        TimeSpan objTimeSpent = default(TimeSpan);

        strXPath = "/quiz/mchoice[" + intQuestionNo.ToString() + "]";

        //Extract question
        xNodeIterator = xNav.Select(strXPath + "/question");
        xNodeIterator.MoveNext();
        lblQuestion.Text = intQuestionNo.ToString() + ". " + xNodeIterator.Current.Value;

        //Extract answers
        xNodeIterator = xNav.Select(strXPath + "/answer");

        //Clear previous listitems
        rblAnswer.Items.Clear();

        intLoop = 0;
        while (xNodeIterator.MoveNext())
        {

            intLoop += 1;

            //Add item to radiobuttonlist
            rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value, intLoop));

            //Extract correct answer
            if (xNodeIterator.Current.GetAttribute("correct", "") == "yes")
            {
                ViewState["CorrectAnswer"] = intLoop;
            }

        }

        //Output Total Question
        lblTotalQuestion.Text = intTotalQuestion;

        //Output Time Spent
        objTimeSpent = DateTime.Now.Subtract(ViewState["StartTime"]);
        lblTimeSpent.Text = objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();

        //Store essential data to state bag
        ViewState["TotalQuestion"] = intTotalQuestion;
        ViewState["Score"] = intScore;
        ViewState["QuestionNo"] = intQuestionNo;
        ViewState["AnswerHistory"] = arrAnswerHistory;

    }

    public void ShowResult()
    {
        string strResult = null;
        int intCompetency = 0;
        int intLoop = 0;
        string strXPath = null;
        TimeSpan objTimeSpent = default(TimeSpan);

        objTimeSpent = DateTime.Now.Subtract(ViewState["StartTime"]);

        strResult = "<center>";
        strResult += "<h3>Quiz Result</h3>";
        strResult += "<p>Points: " + intScore.ToString() + " of " + intTotalQuestion.ToString();
        strResult += "<p>Your Competency: " + Conversion.Int(intScore / intTotalQuestion * 100).ToString() + "%";
        strResult += "<p>Time Spent: " + objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();
        strResult += "</center>";

        strResult += "<h3>Quiz Breakdown:</h3>";
        for (intLoop = 1; intLoop <= intTotalQuestion; intLoop++)
        {
            strXPath = "/quiz/mchoice[" + intLoop.ToString() + "]";
            xNodeIterator = xNav.Select(strXPath + "/question");
            xNodeIterator.MoveNext();
            strResult += "<b>" + intLoop.ToString() + ". " + xNodeIterator.Current.Value + "</b><br>";
            if (arrAnswerHistory[intLoop - 1] == 0)
            {
                strResult += "<font color=\"green\"><b>Correct</b></font><br><br>";
            }
            else
            {
                xNodeIterator = xNav.Select(strXPath + "/answer[" + arrAnswerHistory[intLoop - 1].ToString() + "]");
                xNodeIterator.MoveNext();
                strResult += "<b>You answered:</b> " + xNodeIterator.Current.Value + "<br>";
                strResult += "<font color=\"red\"><b>Incorrect</b></font><br><br>";
            }
        }

        lblResult.Text = strResult;
    }

}


the quiz.aspx.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Australian Geography Quiz</title>
</head>
<style>
body {
  font-size: 10pt;
  font-family: verdana,helvetica,arial,sans-serif;
  color:#000000;
  background-color:#eeeedd;
}
tr.heading {
  background-color:#900B08;
}
.button {
    border: 1px solid #000000;
    background-color: #ffffff;
}
</style>
<body>
<span id="QuizScreen" runat="server">
<form id="Form2" runat="server">
<table width="100%" border="0" cellpadding="2" cellspacing="0">
  <tr class="heading">
    <td width="50%"><font color="white"><b>Australian Geography Quiz</b></font></td>
    <td width="50%" align="right"><font color="white"><b>www.codeproject.com</b></font></td>
  </tr>
  <tr>
    <td colspan="2">
      <b><asp:label id="lblQuestion" runat="server" /></b><br>
      <asp:radiobuttonlist
         id="rblAnswer"
         RepeatDirection="vertical"
         TextAlign="right"
         RepeatLayout="table"
         runat="server" /><br>
      <asp:requiredfieldvalidator ID="Requiredfieldvalidator1"
         ControlToValidate="rblAnswer"
         ErrorMessage="Please pick an answer!"
         runat="server" /><br>
      <asp:button id="btnSubmit" class="button" text="  Next  " onClick="btnSubmit_Click" runat="server" />
    </td>
  </tr>
  <tr class="heading">
    <td width="50%"><font color="white"><b>Total <asp:label id="lblTotalQuestion" runat="server" /> questions</b></font></td>
    <td width="50%" align="right"><font color="white"><b>Time spent <asp:label id="lblTimeSpent" runat="server" /></b></font></td>
  </tr>
</table>
</form>
</span>
<span id="ResultScreen" runat="server">
<asp:label id="lblResult" runat="server" />
</span>
</body>
</html



the quiz.xml originated from Online Quiz[^]


<<pre lang="xml">?xml version="1.0" encoding="UTF-8"?>
<!-- 10 question quiz about Australian Geography -->
<quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="quiz.xsd">
    <mchoice>
        <question>What is the capital city of Australia?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Canberra</answer>
        <answer>Melbourne</answer>
        <answer>Gold Coast</answer>
    </mchoice>
    <mchoice>
        <question>Launceston is the second largest city in which Australian state?</question>
        <answer>Victoria</answer>
        <answer>New South Wales</answer>
        <answer correct="yes">Tasmania</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which state has the famous 'Twelve Apostles' ?</question>
        <answer correct="yes">Victoria</answer>
        <answer>South Australia</answer>
        <answer>New South Wales</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which is a popular ski resort in NSW?</question>
        <answer correct="yes">Perisher Blue</answer>
        <answer>Mt. Buller</answer>
        <answer>Mt. Baw-Baw</answer>
        <answer>Lake Mountain</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which of the following is <u>NOT</u> Australian native animals?]]></question>
        <answer>Kangaroo</answer>
        <answer correct="yes">Penguin</answer>
        <answer>Koala</answer>
        <answer>Wombat</answer>
    </mchoice>
    <mchoice>
        <question>Which city has an extensive tram network?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Melbourne</answer>
        <answer>Adelaide</answer>
        <answer>Ballarat</answer>
    </mchoice>
    <mchoice>
        <question>What is known as 'The Silver City' in Australia?</question>
        <answer>Alice Springs</answer>
        <answer correct="yes">Broken Hill</answer>
        <answer>Ballarat</answer>
        <answer>Silverton</answer>
    </mchoice>
    <mchoice>
        <question>In which location the war movie 'Thin Red Line' was taken?</question>
        <answer>Anglesea</answer>
        <answer>Apollo Bay</answer>
        <answer>Margaret River</answer>
        <answer>Monkey Mia</answer>
        <answer correct="yes">Townsville</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which is <u>NOT</u> true about Uluru ?]]></question>
        <answer>It is the world biggest monolith located in the centre of Australian continent</answer>
        <answer>It was named 'Ayers Rock' by European explorer William Gosse in 1873</answer>
        <answer correct="yes">Aboriginal people encourage tourists to climb Uluru</answer>
        <answer>The area contains carvings and paintings by Aboriginal people</answer>
    </mchoice>
    <mchoice>
        <question>What is so special about Longreach?</question>
        <answer>The place where a blacksmith named Thomas Hiscock found the first gold that triggerred gold rush</answer>
        <answer>The town has an expansive, well-preserved penal colony of Australia's early history</answer>
        <answer correct="yes">The first commercial flight by Qantas took from this town in 1921</answer>
        <answer>None of these answers are correct</answer>
    </mchoice>
</quiz>
Posted
Updated 30-Sep-18 9:31am

you may edit your lines:

string x = ViewState["CorrectAnswer"].ToString();
//Correct answer?
if (rblAnswer.SelectedItem.Value.Equals( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}
 
Share this answer
 
v3
public partial class OnlineTest : System.Web.UI.Page
{
string strXmlFilePath = HttpContext.Current.Server.MapPath("quiz11.xml");
System.Xml.XPath.XPathDocument xDoc;
XPathNavigator xNav;

XPathNodeIterator xNodeIterator;
//Initialize variables
int intTotalQuestion;
int intQuestionNo = 1;
int intScore = 0;

ArrayList arrAnswerHistory = new ArrayList();

protected void Page_Load(object sender, EventArgs e)
{

xDoc = new System.Xml.XPath.XPathDocument(strXmlFilePath);
xNav = xDoc.CreateNavigator();
//Start a new quiz?

if (!Page.IsPostBack)
{
//Yes! Count total question
intTotalQuestion = xNav.Select("/quiz/mchoice").Count;

//Record start time
ViewState["StartTime"] = DateTime.Now;

ShowQuestion(intQuestionNo);
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{

//Retrieve essential variables from state bag
intTotalQuestion =Convert.ToInt32(ViewState["TotalQuestion"]);
intQuestionNo = Convert.ToInt32(ViewState["QuestionNo"]);
intScore = Convert.ToInt32(ViewState["Score"]);
arrAnswerHistory =(ArrayList) ViewState["AnswerHistory"];
string x = ViewState["CorrectAnswer"].ToString();
//Correct answer?
if (rblAnswer.SelectedItem.Value.Equals( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}
else
{
arrAnswerHistory.Add(rblAnswer.SelectedItem.Value);
}

//End of quiz?

if (intQuestionNo == intTotalQuestion)
{
//Yes! Show the result...
QuizScreen.Visible = false;
ResultScreen.Visible = true;

//Render result screen
ShowResult();


}
else
{
//Not yet! Show another question...
QuizScreen.Visible = true;
ResultScreen.Visible = false;
intQuestionNo += 1;

//Render next question
ShowQuestion(intQuestionNo);
}
}
public void ShowQuestion(int intQuestionNo)
{

string strXPath = null;
int intLoop = 0;
TimeSpan objTimeSpent = default(TimeSpan);

strXPath = "/quiz/mchoice[" + intQuestionNo.ToString() + "]";

//Extract question
xNodeIterator = xNav.Select(strXPath + "/question");
xNodeIterator.MoveNext();
lblQuestion.Text = intQuestionNo.ToString() + ". " + xNodeIterator.Current.Value;

//Extract answers
xNodeIterator = xNav.Select(strXPath + "/answer");

//Clear previous listitems
rblAnswer.Items.Clear();

intLoop = 0;
while (xNodeIterator.MoveNext())
{

intLoop += 1;

//Add item to radiobuttonlist
rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value, intLoop.ToString()));

//Extract correct answer
string ans = xNodeIterator.Current.GetAttribute("correct", "");
if (xNodeIterator.Current.GetAttribute("correct", "") == "yes")
{
ViewState["CorrectAnswer"] = intLoop;
}

}

//Output Total Question
lblTotalQuestion.Text = intTotalQuestion.ToString();

//Output Time Spent
objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState["StartTime"]);
lblTimeSpent.Text = objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();

//Store essential data to state bag
ViewState["TotalQuestion"] = intTotalQuestion;
ViewState["Score"] = intScore;
ViewState["QuestionNo"] = intQuestionNo;
ViewState["AnswerHistory"] = arrAnswerHistory;

}

public void ShowResult()
{
string strResult = null;
int intCompetency = 0;
int intLoop = 0;
string strXPath = null;
TimeSpan objTimeSpent = default(TimeSpan);

objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState["StartTime"]);

strResult = "";
strResult += "Quiz Result";
strResult += "Points: " + intScore.ToString() + " of " + intTotalQuestion.ToString();
strResult += "Your Competency: " + Convert.ToInt32(intScore / intTotalQuestion * 100).ToString() + "%";
strResult += "Time Spent: " + objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();
strResult += "";

strResult += "Quiz Breakdown:";
for (intLoop = 1; intLoop " + intLoop.ToString() + ". " + xNodeIterator.Current.Value + "";
int ae=Convert.ToInt32(arrAnswerHistory[intLoop - 1]);
if (ae == 0)
{
strResult += "Correct";
}
else
{
xNodeIterator = xNav.Select(strXPath + "/answer[" + arrAnswerHistory[intLoop - 1].ToString() + "]");
xNodeIterator.MoveNext();
strResult += "You answered: " + xNodeIterator.Current.Value + "";
strResult += "Incorrect";
}
}

lblResult.Text = strResult;
}

}
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900