Loop through timer in c# - asp.net

I want execute a piece of code within a time period and want to exit after a certin time period.
I have a piece of code below which goes into infinite loop.
protected void Page_Load(object sender, EventArgs e)
{
System.Timers.Timer aTimer;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
try
{
Console.WriteLine("Page loaded", null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, "Default");
}
}
I want to run this code for 1 minute.
So how to stop the execution and get out of the loop after 50 or 60 seconds.
Plz help me in this.

Try this:
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(60);
}
// Stop timing
stopwatch.Stop();

Can you set a boolean m_SetEnabled = true in your existing OnElapsedTime event and then add if(m_SetEnabled) { m_SetEnabled = false; return; } to just ignore the single event that gets fired.
Use the Timer class.
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval=5000;
aTimer.Enabled=true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
The Elapsed event will be raised every X amount of seconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify, in the example above it is OnTimedEvent

Related

Incrementing variables in ASP.net on every button click

I want to increment date in every click ASP.NET.
But Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0.
I need to persist a value across postbacks but I don't how to do that. I would appreciate for any help.
Here is what I'am trying to do:
int myNumber = 0;
protected void Button1_Click1(object sender, EventArgs e)
{
lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(myNumber).ToShortDateString();
myNumber++;
}
Update:
My finaly goal is to get next weeks first day with next button and Previous week, I mean I want to forword and backword...
public int NextCount
{
get { return ViewState["Count"] != null ? (int)ViewState["Count"] : 7; }
set { ViewState["Count"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount+7;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount - 7;
}
But When I click Prev button .. there is delay with one click after two or three Click then reaction coming the same with next button when you click from prev to next. Maybe I have to store it in session?
I have updated your code below by using ViewState to handle this. Other easiest option would be storing the same in Session, Cache or Cookie.
While storing a value in ViewState, it will create a hidden field
in the page and store the value to maintain it across the postback.
public int NextCount
{
get { return ViewState["NextCount"] != null ? (int)ViewState["NextCount"] : 0; }
set { ViewState["NextCount"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
NextCount = NextCount+7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
NextCount = NextCount - 7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}

Wierd behavior while many clients generate cache

I show you my problem by simple code snippet.
This is popular scenario. Users load our page when there is no cache so we generate one. In my code example this take 120 seconds to save cache and before this i inrement static variable.
My qustion is why static variable "i" doesn't increment when i open this page many times in the same moment and cache is null.
public partial class _Default : Page
{
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
int i;
var cache = Cache.Get("cache") as string;
if (string.IsNullOrEmpty(cache))
{
i = GenerateCache();
}
else
{
i = Convert.ToInt32(cache);
}
Response.Write(i.ToString());
}
public int GenerateCache()
{
var sw = new Stopwatch();
sw.Start();
++i;
Response.Write(i+"<br>");
while (sw.ElapsedMilliseconds < 1000 * 120) { }
Cache.Insert("cache", i.ToString());
return i;
}
}
Because you have a bug by declaring again the i on the PageLoad
protected void Page_Load(object sender, EventArgs e)
{
int i; // <----- here, this is probably bug and you must remove this line
also you need some kind of locking to avoid multiple calls at the same moment, even tho you saved by the lock of the page session for the moment.

How to retain Serial Port State after postback ASP.net

I am trying to send the data to serial port in ASP.net. After connecting to serial port Before postback data is being sent. But after postback i get exception while sending data.
'System.InvalidOperationException: The port is closed.'
I tried everything by connecting to port on pageload: ispostback, and disconnecting and connecting again. Still it shows same exception. Is there any way to retain the state of serial port..
here's my code. Please Help me Out...
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
openPort("COM10");
disconnect();
connect();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//disconnect();
openPort("COM10");
connect();
check(TextBox1.Text); //Data Sending Successful but after postback even it doesnt work too.
}
public void connect()
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void disconnect()
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void openPort(string p)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
indata = sp.ReadExisting();
Debug.WriteLine(" Data Received:");
Debug.Write(" " + indata);
}
protected void Button4_Click(object sender, EventArgs e)
{
check("" + (char)26); //Exception in sending
}
protected void Button3_Click(object sender, EventArgs e)
{
check("\r\n"); //exception in sending
}
protected void Button2_Click(object sender, EventArgs e)
{
check(TextBox1.Text); // exception in sending
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
sp.Write(ss);
else
{
disconnect(); openPort("COM10"); connect();
sp.Write(ss);
}
}
}
I would simplify your code, so the port is configured on page load and the one handler deals with resetting your port. The disconnect, connect, I see is complicating it. Here I have given an example of using the button click event.
Please note the missing brace below.
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
if (!Page.IsPostBack)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
protected void Button1_Click(object sender, EventArgs e)
if sp.IsOpen = False then
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
else
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
{//missing brace
sp.Write(ss);
}//missing brace
else
{
sp.Open();
sp.Write(ss);
}
}
}
Edit 2:
As I mentioned in the comments the code will only run once.
The following examples are provided from the link below.
Have you tried writing some codes under the !IsPostBack code block to
check if the codes hits there when it postbacks? try this below for
testing
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("First load");
}
else
{
Response.Write("Postback occurs");
}
}
OR
I will refer the code you want to run as One Time Code. For what you
are attempting to achieve, following should work. Please note that
sessions also expire. So after about 20 minutes (default value) of
inactivity, if the user comes back to the site/hits refresh, the One
Time Code will run again. If you want something more persistent than
20 minutes you can try using cookies, but if user clears their cookies
your One Time Code with run again.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["firsttimeuser"] == null)
{
//put code here for One Time Code;
Session["firsttimeuser"] = true;
}
}
Please see this link:
There is lengthy discussion about this.
http://forums.asp.net/t/1314918.aspx/1
You should be able to create a solution from this, please advise.
Edit 1
Please see MSDN for Get Port Names:
Use the GetPortNames method to query the current computer for a list
of valid serial port names. For example, you can use this method to
determine whether COM1 and COM2 are valid serial ports for the current
computer.
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx
And SerialPort.Open
_serialPort.PortName = SetPortName(_serialPort.PortName)
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx
Edit 3
Try:
if (!IsPostBack) or
if(!Page.IsPostBack)
Please see:
Implementation of IsPostBack in page load
What is a postback?
and:
http://msdn.microsoft.com/en-us/library/ms178472.aspx

Does timer affect other processes?

I am using timer and thread in class file and then calling this class file in global file. If timer calls then will it affect other processes of the website ???
My code is as below :
public void Scheduler_Start()
{
Thread thread = new Thread(new ThreadStart(ThreadFunc));
thread.IsBackground = true;
thread.Name = "ThreadFunc";
thread.Start();
}
protected void ThreadFunc()
{
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 24 * 60 * 60 * 1000;
t.Enabled = true;
t.AutoReset = true;
t.Start();
t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
}
protected void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
{
// Code here...
}
Gloabl File :
void Application_Start(object sender, EventArgs e)
{
Scheduler myScheduler = new Scheduler();
myScheduler.Scheduler_Start();
}
If timer calls then will it affect other processes of the website ???
No, it will not affect other applications and processes. By the way when you wrote this recurring background processing in your web application were you aware of the dangers?

Wants to call a function after time interval in ASP.net

My problem is that I have a function implemented on my website which searches for Particular Tweets when I press the button. I want it to make it automatic such that, that function is called again and again after every two minutes, regardless some one uses the website or not..
I have a only a space piece of idea. Such as using a web service. Can any one help?
What you can do is add a System.Timers.Timer in Global.asax.
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerElapsed), null, new Timespan(0), new Timespan(24, 0, 0));
// This will run every 24 hours.
private void TimerElapsed(object o)
{
// Do stuff.
}
You could use a timer, declared in global.asax, like this:
void Application_Start(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 2000 * 60;
timer.Elapsed += Myhandler;
timer.Start();
Application.Add("timer", timer);
}
static void Myhandler(object sender, System.Timers.ElapsedEventArgs e)
{
}

Resources