TimerTick event is not firing when hooked inside !IsPostBack - c#

New to asp.net.
My motive is,
"User has to be taken to some page after a predefined set of the time interval.
Session should not be used."
So, I thought to use Timer and inside the timer tick event, I can do a Server.Redirect. This timer is inside the user control page, which is common across all pages.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
redirectTimer.Interval = 20000;
redirectTimer.Tick += new EventHandler<EventArgs>(redirectTimer_Tick);
}
}
void redirectTimer_Tick(object sender, EventArgs e)
{
Server.Transfer("~/SomePageGoesHere.aspx");
}
Case 2:
protected void Page_Load(object sender, EventArgs e)
{
redirectTimer.Interval = 20000;
redirectTimer.Tick += new EventHandler<EventArgs>(redirectTimer_Tick);
}
void redirectTimer_Tick(object sender, EventArgs e)
{
Server.Transfer("~/SomePageGoesHere.aspx");
}
But in this case, it worked.
My question is,
Whether "!IsPostBack" is having something to do with timer? (Case 1 and 2).
Is there any better approach available other than this timer, session or cookies. etc?
Could someone share some input here?

Related

Remeber Me C# app setting

I Create login form and want to put "remember me" check box on it.
But every time i open program it doesn't change.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
Project.Properties.Settings.Default.rememberMe = true;
Project.Properties.Settings.Default.Save();
}
else
{
Project.Properties.Settings.Default.rememberMe = false;
Project.Properties.Settings.Default.Save();
}
}
Also i want to save user login information, should i save them in app setting just like remember me setting or there is better way?
You're saving the settings, but you need to retrieve those settings too.
Subscribe to the Form's load event and set the value of the CheckBox.
private void Form1_Load(object sender, EventArgs e)
{
checkBox1.Checked = Project.Properties.Settings.Default.rememberMe;
}
Also, and this is just common practice, but your code could be shorter:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Project.Properties.Settings.Default.rememberMe = checkBox1.Checked;
Project.Properties.Settings.Default.Save();
}

how can I use BackGroundWorker to make continuous execution for a method which is depends on user input to stop? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How To Start And Stop A Continuously Running Background Worker Using A Button
I have 2 buttons the first one it's name "Continuous" .. the second one "Stop"
I want to call a method when press the continuous button :
private void continuous_Click(object sender ,EvantArgs e)
{
// continuous taking pictures ...
}
my question is : how can I stop the execution by pressing the stop button ??
I've written a code to take a picture and I've succeeded to take pictures ...
now I want the camera to take continuous snapshots ... but if I press stop button the camera should stop taking pictures ...
I've used BackGroundWorker but the code does not work !!!
this is the code :
private void ContinousSnaps_Click(object sender, EventArgs e)
{
Contiguous.DoWork += Contiguous_DoWork;
Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
Contiguous.RunWorkerAsync();
}
private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; ; i++) TakeSnapShotCommand();
}
private void Contiguous_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
MessageBox.Show("complete");
}
//------------------------------------------------------------------//
private void Stop_Click(object sender, EventArgs e)
{
Contiguous.CancelAsync();
}
//--------------------------------------------------------------------//
how can I achieve the result that I want ?!
Try and see if this is going to work:
In your _DoWork event:
private void Contiguous_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; ; i++)
{
if (Contiguous.CancellationPending)
{
e.Cancel = true;
return;
}
TakeSnapShotCommand();
}
}
And in the Stop_Click to the following:
private void Stop_Click(object sender, EventArgs e)
{
if (Contiguous.WorkerSupportsCancellation)
Contiguous.CancelAsync();
}
Also make sure you allow cancellation (and if you want to take my advice here - move these event registrations in a the form load, so they will be executed once, not every time the button is clicked - leave just the Continuous.RunWorkerAsync()):
// your form load <---
private void Form1_Load(object sender, EventArgs e)
{
Contiguous.DoWork += Contiguous_DoWork;
Contiguous.RunWorkerCompleted += Contiguous_RunWorkerCompleted;
Contiguous.WorkerSupportsCancellation = true; // allowing cancellation
}
private void ContinousSnaps_Click(object sender, EventArgs e)
{
// not a bad idea if you disable the button here at this point
Contiguous.RunWorkerAsync();
}

c# loop every minute - where to put the code?

Currently I'm moving from java to c# and I'm full of crazy questions.
I'm trying new things on a windows form application and now,I would like to create a loop wich is executing a code every 1 minute,the problem is that I have no idea where to put this code.
For example,the form structure is like:
using System;
namespace Tray_Icon
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(5000);
}
private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
label1.Text = "Baloon clicked!";
}
private void notifyIcon1_BalloonTipClosed(object sender, EventArgs e)
{
label1.Text = "baloon closed!";
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
private void option1ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option2ToolStripMenuItem_Click(object sender, EventArgs e)
{
//some code here
}
private void option3ToolStripMenuItem_Click(object sender, EventArgs e)
{
label1.Text = "Option 3 clicked!";
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
option1ToolStripMenuItem_Click(this, null);
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnWrite_Click(object sender, EventArgs e)
{
//code here
}
}
}
Where should I put the loop code? :(
Thanks in advance for ANY replay!!!
Add a Timer to your form:
set its Interval property to 60000 (one minute in milliseconds) and Enabled to True:
and attach an event handler to the Timer.Tick event, e.g. by double-clicking the timer in the Forms designer:
private void timer1_Tick(object sender, EventArgs e)
{
// do something here. It will be executed every 60 seconds
}
You would have to add a timer, and set the interval to 1000 miliseconds, and in the OnTick event you add the code with your loop
Timer tmr = null;
private void StartTimer()
{
tmr = new Timer();
tmr.Interval = 1000;
tmr.Tick += new EventHandler<EventArgs>(tmr_Tick);
tmr.Enabled = true;
}
void tmr_Tick(object sender, EventArgs e)
{
// Code with your loop here
}
You can't put any loop code in here.
In your designer look for the Timer control. When you have that, configure it to run every minute and place your code in the Timer_Tick event.
Or create a timer manually in code and respond to the event :) But for starters, doing it by the designer is easier!
Drag a Timer component on the Form and doubleclick it. There you go with the code.
The Timer component runs in the main thread so you can modify UI components without worrying.
Alternatively You could create a System.Timers.Timer, which has it's own thread and has some advantages, but possible caveats when modifying UI components. See http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Try to use Background Worker and put the code in the backgroundWorker.DoWork or use a Timer
Use System.Timers.Timer:
System.Timers.Timer aTimer;
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 60000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
for using Timer see this tutorial: C# Timer
How you do it in Java platform?
I think Java should be the same with .net.
In fact, a form program is just normal program which contains a event dispatcher. The event dispatcher listen to the UI events and dispatch them to the event handlers. I think all the UI mode should like this, no matter Java or .net platform.
So generally speaking, you have 2 options:
Start the loop at beginning. In this case, you should insert your
code in the constructor of the Form.
Start the loop when user
click the button. In this case, you should insert your code in the
event handler function.
Yes, as others mentioned, you should use the timer. But this should after you know where your code should locate. You also can use a endless loop with a sleep call. But timer is a better solution.
Idea of timer is more better. But If you want to use threads. Then Follow this
Let me assume that You want to do it right from the start of program
You can write in body of function (event in fact) named Form1_Load as
Your actual code is just within while loop other code only to guide
I can guide if you don't know the use of threads in C#
bool button2Clicked = false;
private void Form1_Load(object sender, EventArgs e)
{
// A good Way to call Thread
System.Threading.Thread t1 = new System.Threading.Thread(delegate()
{
while (!button2Clicked)
{
// Do Any Stuff;
System.Threading.Thread.Sleep(60000); //60000 Millieconds=1M
}
});
t1.IsBackground = true; // With above statement Thread Will automatically
// be Aborted on Application Exit
t1.Start();
}

Create event handler for OnScroll for web browser control

Has any one successfully trapped the event of mouse scroll in a web browerser component?
I have two web browser controls i would like to scroll at the same time.
But there are no scroll events for web browsers.
I would like to create an event something like this below? has any one done or seen this before?
private void webCompareSQL_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Document.Window.AttachEventHandler("OnScroll");
}
Here i would call my event and proceed with the code.
private void windowEvents_OnScroll()
{
int nPos = GetScrollPos(webCompareSQL.Handle, (int)ScrollBarType.SbVert);
nPos <<= 16;
uint wParam = (uint)ScrollBarCommands.SB_THUMBPOSITION | (uint)nPos;
SendMessage(WebPrevSQL.Handle, (int)Message.WM_VSCROLL, new IntPtr(wParam), new IntPtr(0));
}
I have found this code but don't know how to use it. its an event.
webCompareSQL.Document.Window.Scroll
I was able to get this working as follows. This example assumes that both web browser controls are navigating to the same Url. I am also syncing the horizontal scrollbar in addition to the vertical - this can be omitted if it is not required.
webBrowser1.DocumentCompleted
+= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser2.DocumentCompleted
+= new WebBrowserDocumentCompletedEventHandler(webBrowser2_DocumentCompleted);
NavigateToPage("www.google.com");
....
private void NavigateToPage(string url)
{
webBrowser1.Navigate(url);
webBrowser2.Navigate(url);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Window.AttachEventHandler("onscroll", OnScrollEventHandler1);
}
private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser2.Document.Window.AttachEventHandler("onscroll", OnScrollEventHandler2);
}
public void OnScrollEventHandler1(object sender, EventArgs e)
{
webBrowser2.Document.GetElementsByTagName("HTML")[0].ScrollTop
= webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollTop;
webBrowser2.Document.GetElementsByTagName("HTML")[0].ScrollLeft
= webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollLeft;
}
public void OnScrollEventHandler2(object sender, EventArgs e)
{
webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollTop
= webBrowser2.Document.GetElementsByTagName("HTML")[0].ScrollTop;
webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollLeft
= webBrowser2.Document.GetElementsByTagName("HTML")[0].ScrollLeft;
}
I note your comment in How to retrieve the scrollbar position of the webbrowser control in .NET, relating to this operation
webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollTop
not working. I can confirm that this definitely works on my machine, so if this code does not work on yours I can look into alternatives.
The real event name is "onscroll" not "OnScroll".
MSDN:http://msdn.microsoft.com/en-us/library/ie/ms536966(v=vs.85).aspx
Following code is firing the method when event occured.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Window.AttachEventHandler("onscroll", OnScrollEventHandler);
}
public void OnScrollEventHandler(object sender, EventArgs e)
{
}

How to keep and add items in a List of objects during button click events

I want to add new items to my generic list when user clicks on a button, but each the the list contains only the last introduced item, it seems that during each button click list get reinitialized :(.
This is a part of code:
List<ProdusBon> listaProduseBon = new List<ProdusBon>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
I also tried using this code:
List<ProdusBon> listaProduseBon = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
listaProduseBon = new List<ProdusBon>();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
but in this case a null reference exception was raised.
I must keep all the items in the list and not only the last one, and when click event was raised a new item to be added to the list.
All the controls in Default.aspx got the default values only the ListBox has "Enable AutoPostBack" set to true but i believe that this is not causing this behavior.
I do not how to keep the items in the list in these conditions, please give me a hand if you know how to do this.
Thanks !
Member variables are lost between page loads. You could store the variable in Session if you want it to remain the same value between loads.
List<ProdusBon> listaProduseBon
{
get { return (List<ProdusBon>) Session["ProdusBon"]; }
set { Session["ProdusBon"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (listaProduseBon == null) listaProduseBon = new List<ProdusBon>();
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
On your button click event first bind the list button and then add the new item from the textbox.
protected void Button1_Click(object sender, EventArgs e)
{
//code to bind your list goes here
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}

Categories

Resources