As I work on developing a timed online test in C# ASP.NET, I encountered an issue with the countdown timer functionality. Currently, the timer is based on the local machine time, but if there is a database disconnection or system hang, it needs to resume from where it left off once the system is back up and running.
I have attempted to address this challenge using the following code snippet, however, it does not fully meet the requirements for resuming the timer after unexpected interruptions:
int totalTime = (Convert.ToInt32(ViewState["totaltime"])) * 60;
DateTime startTime = (DateTime)ViewState["startTime"];
TimeSpan elapsedTime = DateTime.Now.Subtract(startTime);
Literal1.Text = elapsedTime.Hours.ToString() + "h" + ":" + elapsedTime.Minutes.ToString() +
"m" + ":" + elapsedTime.Seconds.ToString() + "s";
int finish = Convert.ToInt32(elapsedTime.TotalSeconds);
int remainingSec = (totalTime - finish);
TimeSpan remainingTime = TimeSpan.FromSeconds(remainingSec);
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
remainingTime.Hours,
remainingTime.Minutes,
remainingTime.Seconds,
remainingTime.Milliseconds);
LIteral2.Text = answer;
if (totalTime == finish)
{
lnkFinish_Click(sender, e);
Response.Redirect(@"~/Error.aspx");
}