How to set Countdown For Each Candidate using Jquery - c#

I am working on online Q/A system,i have to show countdown for each candidate like 3 min,on expiring user will be redirect to Result.aspx page.
I am facing following
1.how to set counter for each candidate.
2.on page refresh counter set to default value.
i have following code
<div id="timer">
</div>
<script type="text/javascript">
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if (getCookie("minutes") && getCookie("seconds")) {
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes", mins, 10)
setCookie("seconds", seconds, 10)
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
//minutesSpan.innerHTML = current_minutes.toString();
//secondsSpan.innerHTML = (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
}
else {
if (mins > 1) {
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(3);
</script>
because multiple user will doing these test so i have handle each one differently,i have following code to assign to assign test for each candidate
private void NewCandidate()
{
var ClistCount = (from cl in ef.Candidate_Table where cl.Name == btnname.Text && cl.Status_Id==2 select cl).FirstOrDefault();
if (ClistCount != null)
{
string cnic = ClistCount.Cnic;
Session["token"] = cnic;
Response.Redirect("MainTestForm.aspx?id=" + cnic);
}
else
{
MsgLitteral.ShowNotification("No Candidate Is Here", true);
btnbrowse.Visible = false;
btnname.Visible = false;
}
}

There are two things which you need to do in order to make things working
1) Create perfectly working count down timer method
2) Solve the reload dependency
for reload thing just before reload/refresh, trigger a function that would store the current time elapsed from the predefined count down.
$(window).bind('beforeunload', function(){
//below function stores current elapsed time in cookie/local storage
callFunction();
return true;
});
for e.g if 3min countdown is set and the user refreshes or moves to
next question at 2min 40 secs then store 2min 40 sec in cookies or
html5 local storage
On every document ready event check the cookie value
if value present then
take this value and set countdown
else
with predefined value (for the first time case)
A simple countdown timer for reference

Related

Why is Javascript causing my page to crash?

so I'm using MVC 4 C#/Razor and I'm developing a page that uses SlickGrid to display grid data. Everything works fine, except when I try using it to display a large amount of data (something like 1 million rows).
When this happens, it appears to do just fine until it's just about finished. Right when it seems like it's going to be done with all dataloading, the web page crashes. I use getJSON to pull the data from a SQL database. I do it by column, and in batches of 300000 records. I have tried using Chrome memory profiling tools, and wasn't able to find anything useful. Below is some code snippets:
function pullAllGridData(tableName, colArray)
{
for (var i = 0; i < colArray.length; i++)
{
fetchColumn(tableName, colArray[i], 0);
}
}
function fetchColumn(tableName, fieldName, startAt)
{
$.getJSON('/WIMenu/GetTableData', { tableName: tableName, fieldName: fieldName }, function (data)
{
if (data.slice(-1) !== '~')
{
var startPass = populateSlickData(data, fieldName, startAt);
colStatus[fieldName] = true;
if (loadFirstBatch())
{ populateGrid(); }
fetchColumn(tableName, fieldName, startPass);
}
else
{
data = data.slice(0, -1);
populateSlickData(data, fieldName, startAt);
colStatus[fieldName] = true;
if (loadFirstBatch())
{ populateGrid(); }
}
});
}
function populateSlickData(input, fieldName, startAt)
{
var output = startAt;
var valueArray = input.split('|');
output += valueArray.length;
if (!isInBlackList(fieldName, tableName))
{
var datatype = columns[getColumnIndex(fieldName)].datatype;
var startIndex = startAt;
var endIndex = startAt + valueArray.length;
var counter = 0;
alert(fieldName + ': startIndex: ' + startIndex + ' endIndex: ' + endIndex + ' count: ' + endIndex-startIndex);
for (var x = startIndex; x < endIndex; x++)
{
if (!slickdata[x])
{ slickdata[x] = {}; }
if (valueArray[x - startAt] == 'null') { valueArray[x - startAt] = ''; }
if (datatype == 'System.DateTime')
{
if (valueArray[x-startAt] !== '')
{
var date = new Date(valueArray[x - startAt]);
valueArray[x - startAt] = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
}
}
else if (datatype == 'System.Decimal' || datatype == 'System.Int32' || datatype == 'System.Int16' || datatype == 'System.Int64')
{
valueArray[x - startAt] = parseFloat(valueArray[x - startAt]);
}
slickdata[x][fieldName] = valueArray[x - startAt];
counter++;
}
}
currentColumn = fieldName;
filteredData = slickdata;
return output;
}
fetchColumn uses recursion to keep getting column data until all of it has been received. The populateGrid method simply syncs the SlickGrid object to the slickdata object. My goal here is to find out why the page is crashing and learn how it can be fixed.
Through using alerts, it seems that at some point, it gets stuck in the for loop in the populateSlickData method, and I cant figure out why. I've tried printing the for indexing data, but it all seems to be normal.
You can't pull a million rows of data into memory and expect any web page to do anything other than slow to a crawl, or indeed crash. This is what grid paging is for, coupled with on-demand ajax. Your grid should only pull the data needed to display the current page of data when the page is changed. You should not load everything ahead of time.
Here's an example on the SlickGrid github site: http://mleibman.github.io/SlickGrid/examples/example4-model.html
Here's more information: https://github.com/teleological/slickback/wiki/Pagination

Timer inside a listbox c#

So I am currently working on a program in which I need to have a timer attached to each item inside of a list box, I have that working, but I can't select any of the items, is there a way to be able to select the items but also have a timer displayed to each item in the list box?
Update:
when adding the item to a new list box here is the code that I have:
private void btnSchedule_Click(object sender, EventArgs e)
{
try
{
string name = lsbScheduled.SelectedItem.ToString();// saves the selected item to a string
string newItem = (moveItem(name));//calls the method and passes the variable to it
tmrCheckedIn.Enabled = true;
tmrCheckedIn.Start();
newItem += " " + "00:00:00";
lsbScheduled.Items.Remove(name);// removes the item from the list
lsbCheckedIn.Items.Add(newItem); //adds the item to the list
}
catch (NullReferenceException)
{
}
}
here is my code for the tick event:
private void tmrCheckedIn_Tick(object sender, EventArgs e)
{
int count = lsbCheckedIn.Items.Count;
for (int i = 0; i < count; i++)
{
string item = lsbCheckedIn.Items[i].ToString();
string[] line = item.Split();
string time = line[8];
Time oldTime = new Time();
oldTime.StartTime = time;
lsbCheckedIn.Items.Remove(item);
string newTime = string.Format(line[0] + " " + line[1] + " " +line[2] + " " + "{0:c}", oldTime.EndTime);
lsbCheckedIn.Items.Add(newTime);
oldTime = null;
}
}
and here is my class that I use to increase the timer:
public class Time
{
private int seconds, minutes, hours;
string startTime, endTime;
public Time()
{
seconds = 00;
minutes = 00;
hours = 00;
startTime = " ";
endTime = "";
}
public string StartTime
{
set { startTime = value;
CalcNewTime();
}
get { return startTime; }
}
public string EndTime
{
set { endTime = value; }
get { return endTime; }
}
public int Hours
{
set { hours = value; }
get { return hours; }
}
public int Minutes
{
set { minutes = value; }
get { return minutes; }
}
public int Second
{
set { seconds = value; }
get { return seconds; }
}
private void CalcNewTime()
{
const int LIMIT = 6, CONVERT = 10;
string[] divisions = startTime.Split(':');
hours = Convert.ToInt32(divisions[0]);
minutes = Convert.ToInt32(divisions[1]);
seconds = Convert.ToInt32(divisions[2]);
int hoursTens = hours / CONVERT;
int hoursOnes = hours % CONVERT;
int minutesTens = minutes / CONVERT;
int minuteOnes = minutes % CONVERT;
seconds += 1;
int secondTens = seconds / CONVERT;
int secondOnes = seconds % CONVERT;
if (secondTens >= LIMIT)
{
secondTens = 0;
secondOnes = 0;
minutes += 1;
minutesTens = Minutes / CONVERT;
minuteOnes = minutes % CONVERT;
if (minutesTens >= LIMIT)
{
minutesTens = 0;
minuteOnes = 0;
hours += 1;
hoursTens = hours / CONVERT;
hoursOnes = Hours % CONVERT;
}
}
endTime = Convert.ToString(hoursTens + hoursOnes + ":" + minutesTens + minuteOnes + ":" + secondTens + secondOnes);
}
}
in programming a windows form application using visual studio 2010 im using the timer that you can select from the toolbox. I need to be able to select the items in the list box but right now i can because im constantly adding and removing items from the list box. I want the time that is displayed in the list box to go up, but i also need it so that i can select the item in the list box.
Your problem is that you're removing items from the listbox, and then adding new ones. This is why items do not remain selected. Instead, just replace the items.
lsbCheckedIn.Items[i] = newTime;

WinForm With Multiple Timers

I am writing a WinForm application to use SNMP calls either every 30 seconds or 1 minute.
I have a timer working for calling my SNMP commands, but I want to add a texbox counter that display the total time elapsed during the operation.
There are many problems I am having so here is a list:
I want my SNMP timer 'timer' to execute once before waiting the allotted time so I have it going off at 3 seconds and then changing the interval in my handler. But this sometimes makes the timer go off multiple times which is not what I want.
Every time 'timer' goes off and my SNMP calls execute my counter timer 'appTimer' becomes out of sync. I tried a work around where I check if it is in the other handler and then just jump the timer to its appropriate time. Which works but I feel this is making it too complicated.
My last issue, that I know of, happens when I stop my application using my stop button which does not completely exit the app. When I go to start another run the time between both timers is becomes even greater and for some reason my counting timer 'appTimer' starts counting twice as fast.
I hope this description isn't too confusing but here is my code anyway:
using System;
using System.Net;
using SnmpSharpNet;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public static bool stop = false;
static bool min = true, eye = false, firstTick = false;
static string ipAdd = "", fileSaveLocation = "";
static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
static System.Windows.Forms.Timer appTimer = new System.Windows.Forms.Timer();
static int alarmCounter = 1, hours = 0, minutes = 0, seconds = 0, tenthseconds = 0, count = 0;
static bool inSNMP = false;
static TextBox textbox, timeTextbox;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textbox = outputBox;
timeTextbox = timeBox;
ipAdd = "192.168.98.107";
fileSaveLocation = "c:/Users/bshellnut/Desktop/Eye.txt";
min = true;
inSNMP = false;
}
private void IPtext_TextChanged(object sender, EventArgs e)
{
ipAdd = IPtext.Text;
}
private void stopButton_Click(object sender, EventArgs e)
{
stop = true;
timer.Stop();
appTimer.Stop();
count = 0;
hours = minutes = seconds = tenthseconds = 0;
inSNMP = false;
}
// This is the method to run when the timer is raised.
private static void TimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
inSNMP = true;
timer.Stop();
if (firstTick == true)
{
// Sets the timer interval to 60 seconds or 1 second.
if (min == true)
{
timer.Interval = 1000 * 60;
}
else
{
timer.Interval = 1000 * 30;
}
}
// Displays a message box asking whether to continue running the timer.
if (stop == false)
{
textbox.Clear();
// Restarts the timer and increments the counter.
alarmCounter += 1;
timer.Enabled = true;
System.IO.StreamWriter file;
//if (eye == true)
//{
file = new System.IO.StreamWriter(fileSaveLocation, true);
/*}
else
{
file = new System.IO.StreamWriter(fileSaveLocation, true);
}*/
// SNMP community name
OctetString community = new OctetString("public");
// Define agent parameters class
AgentParameters param = new AgentParameters(community);
// Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
param.Version = SnmpVersion.Ver2;
// Construct the agent address object
// IpAddress class is easy to use here because
// it will try to resolve constructor parameter if it doesn't
// parse to an IP address
IpAddress agent = new IpAddress(ipAdd);
// Construct target
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
// Define Oid that is the root of the MIB
// tree you wish to retrieve
Oid rootOid;
if (eye == true)
{
rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.14"); // ifDescr
}
else
{
rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.15");
}
// This Oid represents last Oid returned by
// the SNMP agent
Oid lastOid = (Oid)rootOid.Clone();
// Pdu class used for all requests
Pdu pdu = new Pdu(PduType.GetBulk);
// In this example, set NonRepeaters value to 0
pdu.NonRepeaters = 0;
// MaxRepetitions tells the agent how many Oid/Value pairs to return
// in the response.
pdu.MaxRepetitions = 5;
// Loop through results
while (lastOid != null)
{
// When Pdu class is first constructed, RequestId is set to 0
// and during encoding id will be set to the random value
// for subsequent requests, id will be set to a value that
// needs to be incremented to have unique request ids for each
// packet
if (pdu.RequestId != 0)
{
pdu.RequestId += 1;
}
// Clear Oids from the Pdu class.
pdu.VbList.Clear();
// Initialize request PDU with the last retrieved Oid
pdu.VbList.Add(lastOid);
// Make SNMP request
SnmpV2Packet result;
try
{
result = (SnmpV2Packet)target.Request(pdu, param);
}
catch (SnmpSharpNet.SnmpException)
{
timer.Stop();
textbox.Text = "Could not connect to the IP Provided.";
break;
}
// You should catch exceptions in the Request if using in real application.
// If result is null then agent didn't reply or we couldn't parse the reply.
if (result != null)
{
// ErrorStatus other then 0 is an error returned by
// the Agent - see SnmpConstants for error definitions
if (result.Pdu.ErrorStatus != 0)
{
// agent reported an error with the request
textbox.Text = "Error in SNMP reply. " + "Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
lastOid = null;
break;
}
else
{
// Walk through returned variable bindings
foreach (Vb v in result.Pdu.VbList)
{
// Check that retrieved Oid is "child" of the root OID
if (rootOid.IsRootOf(v.Oid))
{
count++;
textbox.Text += "#" + count + " " + v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
" " + v.Value.ToString() + Environment.NewLine;
file.WriteLine("#" + count + ", " + v.Oid.ToString() + ", " + SnmpConstants.GetTypeName(v.Value.Type) +
", " + v.Value.ToString(), true);
if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
lastOid = null;
else
lastOid = v.Oid;
}
else
{
// we have reached the end of the requested
// MIB tree. Set lastOid to null and exit loop
lastOid = null;
}
}
}
}
else
{
//Console.WriteLine("No response received from SNMP agent.");
textbox.Text = "No response received from SNMP agent.";
//outputBox.Text = "No response received from SNMP agent.";
}
}
target.Close();
file.Close();
}
else
{
// Stops the timer.
//exitFlag = true;
count = 0;
}
}
private static void ApplicationTimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
tenthseconds += 1;
if (tenthseconds == 10)
{
seconds += 1;
tenthseconds = 0;
}
if (inSNMP && !firstTick)
{
if (min)
{
seconds = 60;
}
else
{
textbox.Text += "IN 30 SECONDS!!!";
if (seconds < 30)
{
seconds = 30;
}
else
{
seconds = 60;
}
}
}
if(seconds == 60)
{
seconds = 0;
minutes += 1;
}
if(minutes == 60)
{
minutes = 0;
hours += 1;
}
timeTextbox.Text = (hours < 10 ? "00" + hours.ToString() : hours.ToString()) + ":" +
(minutes < 10 ? "0" + minutes.ToString() : minutes.ToString()) + ":" +
(seconds < 10 ? "0" + seconds.ToString() : seconds.ToString()) + "." +
(tenthseconds < 10 ? "0" + tenthseconds.ToString() : tenthseconds.ToString());
inSNMP = false;
firstTick = false;
}
private void eyeButton_Click(object sender, EventArgs e)
{
outputBox.Text = "Connecting...";
eye = true;
stop = false;
count = 0;
hours = minutes = seconds = tenthseconds = 0;
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Interval = 3000;
firstTick = true;
appTimer.Tick += new EventHandler(ApplicationTimerEventProcessor);
appTimer.Interval = 100;
appTimer.Start();
timer.Start();
}
private void jitterButton_Click(object sender, EventArgs e)
{
outputBox.Text = "Connecting...";
eye = false;
stop = false;
count = 0;
hours = minutes = seconds = tenthseconds = 0;
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Interval = 3000;
firstTick = true;
appTimer.Tick += new EventHandler(ApplicationTimerEventProcessor);
appTimer.Interval = 100;
appTimer.Start();
timer.Start();
}
private void Seconds_CheckedChanged(object sender, EventArgs e)
{
min = false;
}
private void Minutes_CheckedChanged(object sender, EventArgs e)
{
min = true;
}
private void exitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void savetextBox_TextChanged(object sender, EventArgs e)
{
fileSaveLocation = savetextBox.Text;
}
}
}
This is very easy to do with a single timer. The timer has a 1/10th second resolution (or so) and can be used directly to update the elapsed time. You can then use relative elapsed time within that timer to fire off your SNMP transaction, and you can reschedule the next one dynamically.
Here's a simple example
using System;
using System.Drawing;
using System.Windows.Forms;
class Form1 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
DateTime lastSnmpTime;
TimeSpan snmpTime = TimeSpan.FromSeconds(30);
DateTime startTime;
TextBox elapsedTimeTextBox;
Timer timer;
public Form1()
{
timer = new Timer { Enabled = false, Interval = 10 };
timer.Tick += new EventHandler(timer_Tick);
elapsedTimeTextBox = new TextBox { Location = new Point(10, 10), ReadOnly = true };
Controls.Add(elapsedTimeTextBox);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
startTime = DateTime.Now;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
// Update elapsed time
elapsedTimeTextBox.Text = (DateTime.Now - startTime).ToString("g");
// Send SNMP
if (DateTime.Now - lastSnmpTime >= snmpTime)
{
lastSnmpTime = DateTime.Now;
// Do SNMP
// Adjust snmpTime as needed
}
}
}
Updated Q&A
With this code the timer fires once at the beginning where after I
press the stop button and call timer.Stop() and then press my start
button the timer doesn't fire until roughly 12 seconds later. Will
resetting the DateTimes fix this?
When the user presses the Start button, set lastSnmpTime = DateTime.MinValue. This causes the TimeSpan of (DateTime.Now - lastSnmpTime) to be over 2,000 years, so it will be greater than snmpTime and will fire immediately.
Also my output time in the text box looks like this: 0:00:02.620262.
Why is that? Is there a way to make it display only 0:00:02.62?
When you subtract two DateTime values, the result is a TimeSpan value. I used a standard TimeSpan formatting string of "g". You can use a custom TimeSpan formatting string of #"d\:hh\:mm\:ss\.ff" to get days:hours:minutes:seconds.fraction (2 decimal places).
Also will the timer go on and print out to the text box when it is run
for over 9 hours? Because I plan to have this running for 24 hrs+
If you use the custom format with 'd' to show the number of days, it will run for TimeSpan.MaxValue which is slightly more than 10,675,199 days, which is more than 29,000 years.

How can i convert the timer time from seconds to minutes and show minutes:seconds?

Now its only counting back as seconds like 8..7..6..5..etc the interval of Timer1 is set to 1000ms
I want that if the user change the numericupdown1 to 9 so instead counting seconds back like now it will count it as minutes and show it as: 01(minute):10(seconds)
This is the code of Timer1_Tick event:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
numbers_radar = Convert.ToInt64(numericUpDown1.Value);
numbers_satellite = Convert.ToInt64(numericUpDown2.Value);
if (numbers_radar <= 0 || numbers_satellite <= 0)
{
timer1.Stop();
button1.Enabled = true;
numericUpDown1.Enabled = true;
numericUpDown2.Enabled = true;
MessageBox.Show("Value cannot be zero or below zero");
numericUpDown1.Text = "";
numericUpDown2.Text = "";
}
else
{
Numbers_Timer_radar = Numbers_Timer_radar + 1;
Numbers_Timer_satellite = Numbers_Timer_satellite + 1;
if (Numbers_Timer_radar >= numbers_radar)
{
try
{
filesdownload();
number_of_files_in_current_directory = Directory.GetFiles(sf, "radar*.png");
label13.Text = "Current Number Of Files In The Selected Directory Are: " + number_of_files_in_current_directory.Length;
button1.Enabled = false;
Numbers_Timer_radar = 0;
}
catch (Exception Local_Timer1_Exceptions)
{
Logger.Write("Timer1 Errors : " + Local_Timer1_Exceptions);
}
}
if (Numbers_Timer_satellite >= numbers_satellite)
{
satellite_downloads();
number_of_satellite_files_in_current_directory = Directory.GetFiles(satellite_dir, "satellite*.png");
label8.Text = "Current Number Of Files In The Selected Directory Are: " + number_of_satellite_files_in_current_directory.Length;
button1.Enabled = false;
Numbers_Timer_satellite = 0;
}
time_left_radar = numbers_radar - Numbers_Timer_radar;
time_left_satellite = numbers_satellite - Numbers_Timer_satellite;
//string t = GetTime((int)time_left_radar);
label21.Text = time_left_radar.ToString();
label22.Text = time_left_satellite.ToString();
label1.Text = "Next image radar will be download in: ";
label5.Text = "Next image satellite will be download in: ";
}
}
catch (Exception General_Exceptions)
{
Logger.Write("Show if numbers have wrong string input" + numbers_radar);
Logger.Write("Show if numbers have wrong string input" + numbers_satellite);
timer1.Stop();
Logger.Write("Exception: " + General_Exceptions + Environment.NewLine);
//numericUpDown1.Clear();
//numericUpDown2.Clear();
button1.Enabled = true;
numericUpDown1.Enabled = true;
numericUpDown2.Enabled = true;
Numbers_Timer_radar = 0;
Numbers_Timer_satellite = 0;
}
}
time_left_radar and time_left_satellite are both long variables
And in label21 and label22 instead see seconds backward counting 8..7..6..etc i want it to be like:
01(minutes):10(seconds)..01:9..01:8...or 01:09..01:08...
So it will count minutes and seconds.
I tried to use there in the timer1_tick event with GetTime method but it didnt work. The GetTime method code is:
public string GetTime(int Time)
{
//Seconds
Sec = Time % 60;
//Minutes
Min = ((Time - Sec) / 60) % 60;
//Hours
Hrs = ((Time - (Sec + (Min * 60))) / 3600) % 60;
return Hrs.ToString("00") + ":" +
Min.ToString("00") + ":" +
Sec.ToString("00");
}
Thanks for the help.

In my numericUpDown Changed event im calling a function() and when im changing the numeric value when program is running its getting slower

This is the numeric changed event code with timer2 wich didnt solve hte problem the function im calling is DoThresholdCheck()
The problem is that in this function im creating each time im changing the numeric value a temp list each time im moving the numeric value change it the list is been created from the start. The problem is that if im using a big file in my program the list is containing sometimes 16500 indexs and its taking time to loop over the list so i guess when im changing the numeric value its taking time to loop over the list. If im using smaller video file for example the list containing 4000 indexs so there is no problems. I tried to use Timer2 maybe i could wait 0.5 seconds between each time the numeric value is changed but still dosent work good.
When im changing the numeric value while the program is running on a big video file its taking the values to be changed like 1-2 seconds ! thats a lot of time.
Any way to solve it ? Maybe somehow to read the list loop over the list faster even if the list is big ?
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
Options_DB.Set_numericUpDownValue(numericUpDown1.Value);
if (isNumericChanged == true)
{
isNumericChanged = false;
myTrackPanelss1.trackBar1.Scroll -= new EventHandler(trackBar1_Scroll);
DoThresholdCheck();
counter = 0;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
counter++;
if (counter > 1)
{
isNumericChanged = true;
//timer2.Stop();
}
}
This is the DoThresholdChecks() function code:
private void DoThresholdCheck()
{
List<string> fts;
//const string D6 = "000{0}.bmp";
if (Directory.Exists(subDirectoryName))
{
if (!File.Exists(subDirectoryName + "\\" + averagesListTextFile + ".txt"))
{
return;
}
else
{
bool trackbarTrueFalse = false ;
fts = new List<string>();
int counter = 0;
double thershold = (double)numericUpDown1.Value;
double max_min_threshold = (thershold / 100) * (max - min) + min;
//label13.Text = max_min_threshold.ToString();
_fi = new DirectoryInfo(subDirectoryName).GetFiles("*.bmp");
for (int i = 0; i < myNumbers.Count; i++)
{
if (myNumbers[i] >= max_min_threshold)
{
//f.Add(i);
string t = i.ToString("D6") + ".bmp";
if (File.Exists(subDirectoryName + "\\" + t))
{
counter++;
button1.Enabled = false;
myTrackPanelss1.trackBar1.Enabled = true;
trackbarTrueFalse = true;
label9.Visible = true;
// myTrackPanelss1.trackBar1.Scroll += new EventHandler(trackBar1_Scroll);
//myTrackPanelss1.trackBar1.Minimum = 0;
// myTrackPanelss1.trackBar1.Maximum = f.Count;
// myTrackPanelss1.trackBar1.Value = f.Count;
// myFiles = new Bitmap(myTrackPanelss1.trackBar1.Value);
}
else
{
label9.Visible = false;
trackbarTrueFalse = false;
button1.Enabled = true;
myTrackPanelss1.trackBar1.Enabled = false;
myTrackPanelss1.trackBar1.Value = 0;
pictureBox1.Image = Properties.Resources.Weather_Michmoret;
label5.Visible = true;
secondPass = true;
break;
}
//fts.Add(string.Format(D6, myNumbers[i]));
}
}
//myTrackPanelss1.trackBar1.Maximum = _fi.Length - 1;
if (myTrackPanelss1.trackBar1.Maximum > 0)
{
if (trackbarTrueFalse == false)
{
myTrackPanelss1.trackBar1.Value = 0;
}
else
{
myTrackPanelss1.trackBar1.Maximum = counter;
myTrackPanelss1.trackBar1.Value = 0;
SetPicture(0);
myTrackPanelss1.trackBar1.Scroll += new EventHandler(trackBar1_Scroll);
}
//checkBox2.Enabled = true;
}
if (_fi.Length >= 0)
{
label15.Text = _fi.Length.ToString();
label15.Visible = true;
}
}
}
else
{
button1.Enabled = true;
}
}
try to cache results from DoThresholdCheck method
You can't magically get around the time the processing takes, if the processing is really necessary. You've got a couple of avenues to explore:
1) Minimise the processing being done - is all of it necessary? Can you cache any of it and only recompute a small amount each time the value changes?
2) Do the processing less often - do you have to recompute every single time?
3) Do the processing on another thread - then at least your UI remains responsive, and you can deliver the results to the UI thread when the background task is complete. However, this is going to be a relatively complicated variant of this pattern as you're going to need to be able to abort and restart if the value changes again while you're still processing the previous one.

Categories

Resources