In this article i will demonstrate a simple online exam to with a java script timer.
Introduction
This article gives an basic idea of how an online exam works with an java script timer function.
Objective
This article provide an users can login to the system and proceed for an attending an exam through online.
Here i have a different screens to manage and attend an exam by individual users through online with their specific courses.
Database DesignThe below are the few database design of my article with tbl_Exams table

DB Screen 2
Using the code
1. Student Exam Screen- Used by the students to attend an exam by logging in in to the system.
Design Page-Student Exam Screen<head runat="server">
<script type="text/javascript" language="javascript">
function Validate()
{
var stName=document.getElementById('txtName');
var ddlExam=document.getElementById('ddlExams').selectedIndex;
if((stName.value=='')||(ddlExam<=0))
{
alert('Please the input field');
return false;
}
else
{
return true;
}
}
</script>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Student Name
</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Choose the Exam
</td>
<td>
<asp:DropDownList ID="ddlExams" runat="server" Height="20px" Width="147px"
AutoPostBack="True" onselectedindexchanged="ddlExams_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Duration </td>
<td>
<asp:TextBox ID="txtExDuration" runat="server" ReadOnly="True"></asp:TextBox>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="btnStart" runat="server" OnClientClick="return Validate()" Text="Start" onclick="btnStart_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
Code Behind (.cs) file
//Connection String
string Conn = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
//Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillExams();
}
}
User Defined Method
protected void FillExams()
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_Exams", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ddlExams.DataSource = ds;
ddlExams.DataTextField = "ExName";
ddlExams.DataValueField = "Id";
ddlExams.DataBind();
ddlExams.Items.Insert(0, "-Select-");
}
else
{
}
}
Button Click Event
protected void btnStart_Click(object sender, EventArgs e)
{
Session["StName"] = txtName.Text.ToString();
Session["StExam"] = ddlExams.SelectedItem.Text;
Response.Redirect("AttendExam.aspx");
}
Course Selection
protected void ddlExams_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select ExDurSec,ExDurMin from tbl_Exams where ExName='"+ddlExams.SelectedItem.Text+"'", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtExDuration.Text = ds.Tables[0].Rows[0]["ExDurMin"].ToString()+" Minutes";
System.Configuration.Configuration web = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
web.AppSettings.Settings.Remove("Delay");
web.AppSettings.Settings.Add("Delay", "" + ds.Tables[0].Rows[0]["ExDurSec"].ToString()+"");
web.Save(ConfigurationSaveMode.Modified);
}
else
{
txtExDuration.Text = "";
}
}
Screen 2-Attending an ExamIn this screen the users will be actually attending an exam based on the exam duration in seconds/Minutes.The UI of this screen just display an users Name,Current Time & Exam duration running in seconds in
(Decreasing Order). The main functionality of an timer running is done by using a java script function without any timer control.
Design Page(.aspx)
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Exam Name:
</td>
<td>
<asp:Label ID="lblExName" runat="server" Font-Bold="True"></asp:Label>
</td>
<td align="right">
Exam Started:
</td>
<td>
<asp:Label ID="lblCurrTime" runat="server" Font-Bold="True"></asp:Label>
</td>
<td>
Time Left:
</td>
<td>
<asp:Label ID="lblExamStTime" runat="server" Font-Bold="True"></asp:Label>
</td>
</tr>
</table>
<table align="center">
<tr>
<td>
<asp:Label ID="lblQstn" runat="server"></asp:Label>
<td>
<asp:RadioButtonList ID="rblAns" runat="server" RepeatDirection="Horizontal"></asp:RadioButtonList>
</td>
</tr>
</table>
</div>
</form>
</body>
Javascript FunctionThe below function performs a timer calculation based on the Delay time which is stored in web.config file
<script type="text/javascript">
function myTimer(startVal,interval,outputId, dataField){
this.value = startVal;
this.OutputCntrl = document.getElementById(outputId);
this.currentTimeOut = null;
this.interval = interval;
this.stopped=false;
this.data = null;
var formEls = document.form1.elements;
if(dataField)
{
for(var i=0; i < formEls.length -1; i++)
{
if(formEls[i].name == dataField)
{
this.data = formEls[i];
i = formEls.length + 1;
}
}
}
myTimer.prototype.go = function ()
{
if(this.value > 0 && this.stopped == false)
{
this.value = (this.value - this.interval);
if(this.data)
{
this.data.value = this.value;
}
var current = this.value;
this.OutputCntrl.innerHTML = this.Hours(current) + ':' + this.Minutes(current) + ':' + this.Seconds(current);
this.currentTimeOut = setTimeout("Timer.go()",this.interval);
}
else
{
alert('Time Out!');
window.location('Default.aspx');
}
}
myTimer.prototype.stop = function (){
this.stopped = true;
if(this.currentTimeOut != null){
clearTimeout(this.currentTimeout);
}
}
myTimer.prototype.Hours = function(value){
return Math.floor(value/3600000);
}
myTimer.prototype.Minutes = function(value){
return Math.floor((value - (this.Hours(value)*3600000))/60000);
}
myTimer.prototype.Seconds = function(value){
var hoursMillSecs = (this.Hours(value)*3600000)
var minutesMillSecs = (this.Minutes(value)*60000)
var total = (hoursMillSecs + minutesMillSecs)
var ans = Math.floor(((this.value - total)%60000)/1000);
if(ans < 10)
return "0" + ans;
return ans;
}
}
</script>
Code Behind Class AttendExam .csusing System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;
Global Variable Declarations
string Conn = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
long timerStartValue = 1800;
string ExName = "";
Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
lblCurrTime.Text = DateTime.Now.ToLongTimeString();
ExName = Session["StExam"].ToString();
if (!IsPostBack)
{
FillQnA();
this.timerStartValue = long.Parse(ConfigurationManager.AppSettings["Delay"].ToString());
this.TimerInterval = 500;
if (Session["StName"] != null)
{
lblExName.Text = Session["StName"].ToString();
}
}
}
Page Events
void Page_PreRender(object sender, EventArgs e)
{
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblExamStTime.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
void Page_PreInit(object sender, EventArgs e)
{
string timerVal = Request.Form["timerData"];
if (timerVal != null || timerVal == "")
{
timerVal = timerVal.Replace(",", String.Empty);
timerStartValue = long.Parse(timerVal);
}
}
private Int32 TimerInterval
{
get
{
object o = ViewState["timerInterval"];
if (o != null) { return Int32.Parse(o.ToString()); }
return 50;
}
set { ViewState["timerInterval"] = value; }
}
User Defined Method
protected void FillQnA()
{
try
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmdQstns = new SqlCommand("select * from tbl_Qstns", cnn);
SqlCommand cmdAns = new SqlCommand("select * from tbl_Answrs where QuestionId=1", cnn);
SqlCommand cmdTime = new SqlCommand("select ExDurSec from tbl_Exams where ExName='"+ExName+"'", cnn);
SqlDataAdapter adQstns = new SqlDataAdapter(cmdQstns);
SqlDataAdapter adaAns = new SqlDataAdapter(cmdAns);
SqlDataAdapter adaTime = new SqlDataAdapter(cmdTime);
DataSet dsQstns = new DataSet();
DataSet dsAns = new DataSet();
DataSet dsTime = new DataSet();
adQstns.Fill(dsQstns);
adaAns.Fill(dsAns);
adaTime.Fill(dsTime);
if (dsQstns.Tables[0].Rows.Count > 0)
{
lblQstn.Text ="1."+ dsQstns.Tables[0].Rows[0]["Questions"].ToString();
}
if (dsAns.Tables[0].Rows.Count > 0)
{
rblAns.DataSource = dsAns;
rblAns.DataTextField = "Answers";
rblAns.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Web.Config FileThe web.config file stores an value for the duration of an exam under Appsettings which is calculated in seconds in below code the value=60000 denotes as 1 minute which calculates in seconds.
<appSettings>
<add key="Delay" value="60000" />
</appSettings>
Screen Shots


Conclusion
This article gives a basic idea on how an online exam can done for the users based on courses selection.