im using WatiN for app im working on. in the app i got a list of sites: List<string> sites;
and i got a timer that im runing every few second to load and send data or get data from the current site.
when i try runing this code nothing happend, not even Exception. i have no idea why.
private void watiNMethod()
{
Settings.AutoStartDialogWatcher = false;
Settings.AutoStartDialogWatcher = false;
ie = new IE(webBrowser1.ActiveXInstance);
ie.GoTo(sites[runing]);
ie.WaitForComplete();
MessageBox.Show("done loading");
}
int runing;
Thread watInThread;
private void button1_Click(object sender, EventArgs e)
{
timer = new System.Windows.Forms.Timer();
timer.Start();
watInThread = new Thread(watiNMethod);
watInThread.SetApartmentState(ApartmentState.STA);
runing = 0;
}
private void timer_tick(object sender, EventArgs e)
{
if (runing <= sites.Count)
{
watInThread.Start();
}
else
{
timer.Stop();
}
runing++;
}
i want to be able to load to the web browser control, wait for him to complete with WatiN methods, and send data to the site or just get data from him.
im not sure how do this, becuse i have to use Thread to run WatiN inside the WebBrowswer Control.
(sorry for my english)
I don't think you're setting timer.Tick?!?
timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(this.timer_tick);
timer.Start();
Related
I'm pretty new in c# and I'm programing just for my personal studies, I have been trying to program an instruction where a read some data from a remote station to my application (m64...mw74), it's running OK for couple minutes but its crash maybe after 5 minutes.
please see the code I'm using below to update my data every 1 second and write it in a simple text box in my form.enter image description here
Thank you very much in advance.
private void Load_act()
{
actvalueL1.Text = plc.Read("mw64").ToString();
actvaluep1.Text = plc.Read("mw68").ToString();
actvaluep2.Text = plc.Read("mw71").ToString();
actvaluep3.Text = plc.Read("mw74").ToString();
InitTimer();
}
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // in miliseconds
timer1.Start();
//Console.ReadLine();
}
private void timer1_Tick(object sender, EventArgs e)
{
Load_act();
}
You're chaining the timers, eventually going to run yourself out of memory as they cannot dispose - the timer creates the next with its own call. Return them on to a parent method that loops your timer 'initTimer'
I need to open a form on C# and then have it close automatically after, say, 5 seconds.. The thing is, I need the form to be closed from the form it was opened from because the form I am opening is sometimes opened from another form without being automatically closed.
I've tried this:
private void button6_Click(object sender, EventArgs e)
{
GetNumber gtn = new GetNumber();
gtn.Show();
System.Threading.Thread.Sleep(6000);
gtn.Hide();
gtn = null;
}
But the form was messed up when it started, same happened when I tried with a timer.
Anybody know how to solve my problem?
As itsme86 said, timers would work for what you are trying to do. If you are in .Net 4.5 or greater you can use the async/await features.
At its core, you need to free up the UI thread to continue on its way. Your Thread.Sleep is putting the UI thread out of commission. Using a timer or the async/await allows the UI thread to launch your dialog and process any user actions.
private async void button6_Click(object sender, EventArgs e)
{
GetNumber gtn = new GetNumber();
gtn.Show();
await Task.Delay(6000);
gtn.Hide();
gtn = null;
}
A timer would be the correct approach:
private void button6_Click(object sender, EventArgs e)
{
GetNumber gtn = new GetNumber();
gtn.Show();
System.Timers.Timer timer = new Timer(6000);
timer.Elapsed += (_, _2) => { Invoke((MethodInvoker)delegate { gtn.Close(); }); };
timer.Start();
}
Here's my code:
delegate void del(string data);
public partial class CreateUser : System.Web.UI.Page
{
static string rfidkey;
SerialPort serialPort1;
//Timer timer1;
del MyDlg;
private delegate void SetTextDeleg(string text);
public CreateUser()
{
serialPort1 = new SerialPort();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
//
timer1 = new Timer();
timer1.Interval = 100;
timer1.Enabled = false;
timer1.Tick += new EventHandler<EventArgs>(timer1_Tick);
//
MyDlg = new del(Display);
}
void Display(string s)
{
txtRFIDKey.Text = s;
}
void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Data.s = serialPort1.ReadExisting();
//txtRFIDKey.Text = Data.s;
MyDlg.BeginInvoke(Data.s, null, null);
}
}
This cannot be done the way you are coding it. Basically, you are trying to treat your web page like a Windows application. You need to understand the the "code behind", the code you have written above, runs on one computer, and the web page, where the text field is, is displayed on another. And once the page construction code finishes running, the server can't change the page. You can use postbacks and Ajax from the web page to call back to the server, but even that might not help you with the code you trying to write.
To get a better understanding of the fundamentals of asp.net web page processing, start here: ASP.NET page life cycle explanation
Or, you can just code your page as an Application using Windows Forms, or WPF.
I am working on a stopwatch, that i want to use in some sort of competition. I would like to start my stopwatch by clicking Button 1 in order that first wav file is played and after that stopwatch starts. But Stopwatch doesn't start. This is what I came up to till now.
Stopwatch sw = new Stopwatch();
private void button1_Click(object sender, EventArgs e)
{
new System.Threading.Thread(testMethod).Start();
}
private void testMethod(object obj)
{
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(#"D:\...\something.wav");
sp.Play();
}
void OnSoundPlayOver(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
sw.Start();
}
If your requirements are:
Start button that plays a sound, then starts a timer that displays the elapsed time on the screen.
Stop button that stops any current timers, leaving the last value on the screen.
Implemented in Windows Forms.
The following code is a BASIC example of how to get the above requirements working. It leverages the PlaySync method of SoundPlayer, a BackgroundWorker (to update the value on the label to be the elapsed seconds) and a Stopwatch for actually recording the elapsed time. It is definitely not the BEST way to accomplish this, but it should provide a starting point for you.
An important thing to note is that you cannot update a Label from a thread that is different from the thread that created the label (typically the UI thread). So if you're trying to update the Text of a label from another thread you need to use the labels .Invoke method (see the ThreadSafeUpdateLabel method in the code below).
This code does not take into account the situation where someone spam clicks the Start button (it just plays the sound as many times as you click) and the UI freezes when you click the Start button for as long as it takes the sound to play. I'll leave fixing those issues to you as a natural extension of the code.
Anyway, onto the code:
private Stopwatch _timer = new Stopwatch();
private BackgroundWorker _worker;
private void btnStop_Click(object sender, EventArgs e)
{
CancelExistingBackgroundWorker();
_timer.Stop();
}
private void btnStart_Click(object sender, EventArgs e)
{
CancelExistingBackgroundWorker();
_timer.Reset();
UpdateLabel(0);
_worker = new BackgroundWorker() { WorkerSupportsCancellation = true };
_worker.DoWork += (a, b) =>
{
while (true)
{
if ((a as BackgroundWorker).CancellationPending) return;
ThreadSafeUpdateLabel();
Thread.Sleep(100);
}
};
var soundPlayer = new SoundPlayer("wavfile.wav");
soundPlayer.PlaySync();
_timer.Start();
_worker.RunWorkerAsync();
}
private void ThreadSafeUpdateLabel()
{
if (lblElapsed.InvokeRequired)
{
lblElapsed.Invoke(new Action(() => ThreadSafeUpdateLabel()));
}
else
{
UpdateLabel(_timer.Elapsed.TotalSeconds);
}
}
private void UpdateLabel(double seconds)
{
lblElapsed.Text = seconds.ToString();
}
private void CancelExistingBackgroundWorker()
{
if (_worker != null)
{
_worker.CancelAsync();
_worker.Dispose();
}
}
My Excel AddIn is written in NetOffice, ExcelDNA, C#
It calls web service to get data. It takes a while to fetch a large amount of data.
During the process of data fetch, if network connection is lost, then Excel will hung, shows like "not responding". Now if I try to close Excel, it will ask you to close or debug. I simply close it.
Then when I restart Excel, there is an annoying message box comes up saying
"Excel experienced a serious problem with the 'commodity add-in' add-in. If you have seen this message multiple times, you should disable this add-in and check to see if an update is available. Do you want to disable this add-in?."
I wonder how to handle the situation when connection is lost appropriately? Thanks
Make the web service call asynchronously, if possible. Most WS will provide async versions and non-async versions of the calls that you can make.
If this is not possible, consider executing the web service data fetch within a separate thread.
In both scenarios, you should put some plumbing code in place to kill the job after a certain period, and probably some means to notify the user that not all is well.
"Excel experienced a serious problem with the 'XXX add-in' add-in. If
you have seen this message multiple times, you should disable this
add-in and check to see if an update is available. Do you want to
disable this add-in?."
You get this problem when an unhandled exception occurs. Excel will prompt you to disable the Add-In next start up. This can lead users to posts like this to fix it.
The pain is worse when you have to support clients using Citrix in non-admin environments. To get around the problem of Excel wanting to diable the add-In you have to add a Global Exception handler so the exception isn't referred back to Excel to avoid prompting users to disable the Add-In.
public YouAddInCtrl()
{
InitializeComponent();
// Add the event handler for handling UI thread exceptions to the event.
System.Windows.Forms.Application.ThreadException += ApplicationThreadException;
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += ApplicationUnhandledException;
}
private void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
addInManager.TopLevelExceptionHandler(e.Exception);
}
private void ApplicationUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
addInManager.TopLevelExceptionHandler((Exception)e.ExceptionObject);
}
// Any exceptions returned to Excel will cause the Addin to be disabled
// So we must swallow them here.
internal void TopLevelExceptionHandler(Exception ex)
{
var e = new NotificationEventArgs(NotificationEventArgs.NotificationEnum.TopLevelException);
if (NotifyEventTopLevelException != null)
{
if (NotifyEventTopLevelException(ex,e))
{
System.Diagnostics.Process.Start("mailto:Support#XYZ.com%3e?subject=XYZ%202%20PROD%20Environment%20Problem&body=Hi,%0A%0AIssue:%0A%0ASteps%20to%20Reproduce:");
}
}
LogExceptions(ex);
}
I would also suggest that you run the WebService request on a different thread, eg:
BackgroundWorker1.WorkerReportsProgress = true;
BackgroundWorker1.WorkerSupportsCancellation = true;
BackgroundWorker1.DoWork += DoWorkExecuteQuery;
BackgroundWorker1.RunWorkerCompleted += RunWorkerCompletedExecuteQuery;
private bool QueryData()
{
var thinkProgBar = new ThinkingProgressBar();
thinkProgBar.ShowCancelLink(true);
thinkProgBar.SetThinkingBar(true);
BackgroundWorker1.RunWorkerAsync(thinkProgBar);
thinkProgBar.ShowDialog();
if (thinkProgBar.Tag != null && thinkProgBar.Tag.ToString() == "Cancelled")
{
CancelGetDataByFilters();
thinkProgBar.SetThinkingBar(false);
return false;
}
thinkProgBar.SetThinkingBar(false);
return true;
}
private void DoWorkExecuteQuery(object sender, DoWorkEventArgs e)
{
dtQueryData = null;
e.Result = e.Argument;
((ThinkingProgressBar)e.Result).SetThinkingBar(true);
dtQueryData = WEBSERVICE.GetData(); //CALL YOUR WEBSERVICE HERE
}
private void RunWorkerCompletedExecuteQuery(object sender, RunWorkerCompletedEventArgs e)
{
var dlg = e.Result as ThinkingProgressBar;
if (dlg != null) {
((ThinkingProgressBar)e.Result).SetThinkingBar(false);
dlg.Close();
}
}
Here is the ThinkingProgress bar:
public partial class ThinkingProgressBar : Form
{
private System.DateTime startTime = DateTime.Now;
public ThinkingProgressBar()
{
InitializeComponent();
}
private void lblClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Tag = "Cancelled";
this.Hide();
}
public void ShowCancelLink(bool show)
{
lblClose.Visible = show;
}
public void SetThinkingBar(bool on)
{
if (on)
{
lblTime.Text = "0:00:00";
startTime = DateTime.Now;
timer1.Enabled = true;
timer1.Start();
}
else
{
timer1.Enabled = false;
timer1.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
var diff = new TimeSpan();
diff = DateTime.Now.Subtract(startTime);
lblTime.Text = diff.Hours + ":" + diff.Minutes.ToString("00") + ":" + diff.Seconds.ToString("00");
lblTime.Invalidate();
}
}