FileSystemWatcher stops catching events - c#

I am writing a c# program to let me know when a file has been added or deleted. I run it on my Windows 7 machine and watch an FTP server on our network.
It works fine but will suddenly stop catching any events. I'm guessing that it might be losing connection to the server or there is a glitch in the network.
How can I handle this situation in the code. Is there some exception I can watch for and try to restart the FileSystemWatcher object.
Any suggestions and code samples would be appreciated.

I needed to add an error handler for the FileSystemWatcher
fileSystemWatcher.Error += new ErrorEventHandler(OnError);
And then add this code:
private void OnError(object source, ErrorEventArgs e)
{
if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
{
txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n";
}
else
{
txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
}
NotAccessibleError(fileSystemWatcher ,e);
}
Here is how I reset the SystemFileWatcher object:
static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
source.EnableRaisingEvents = false;
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while (source.EnableRaisingEvents == false && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = true;
}
catch
{
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}
I think this code should do what I want it to do.

The previous answer does not fix it completely, I had to reset the watcher not just turn it on and off.
I use filesystemwatcher on a window service
void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while ((!Directory.Exists(source.Path) || source.EnableRaisingEvents == false) && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = false;
if (!Directory.Exists(source.Path))
{
MyEventLog.WriteEntry("Directory Inaccessible " + source.Path + " at " + DateTime.Now.ToString("HH:mm:ss"));
System.Threading.Thread.Sleep(iTimeOut);
}
else
{
// ReInitialize the Component
source.Dispose();
source = null;
source = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(source)).BeginInit();
source.EnableRaisingEvents = true;
source.Filter = "*.tif";
source.Path = #"\\server\dir";
source.NotifyFilter = System.IO.NotifyFilters.FileName;
source.Created += new System.IO.FileSystemEventHandler(fswCatchImages_Changed);
source.Renamed += new System.IO.RenamedEventHandler(fswCatchImages_Renamed);
source.Error += new ErrorEventHandler(OnError);
((System.ComponentModel.ISupportInitialize)(source)).EndInit();
MyEventLog.WriteEntry("Try to Restart RaisingEvents Watcher at " + DateTime.Now.ToString("HH:mm:ss"));
}
}
catch (Exception error)
{
MyEventLog.WriteEntry("Error trying Restart Service " + error.StackTrace + " at " + DateTime.Now.ToString("HH:mm:ss"));
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}

You can create a method that initiates the FileSystemWatcher, and in case of an error, just restart it.
private void WatchFile()
{
try
{
fsw = new FileSystemWatcher(path, filter)
{
EnableRaisingEvents = true
};
fsw.Changed += Fsw_Changed;
fsw.Error += Fsw_Error;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void Fsw_Error(object sender, ErrorEventArgs e)
{
Thread.Sleep(1000);
fsw.Changed -= Fsw_Changed;
fsw.Error -= Fsw_Error;
WatchFile();
}

Related

Xamarin app shows blank page while looping

I'm making an Android application on Xamarin and I want this code to be looped over and over.
But when it's looping it shows literally nothing
public MainPage()
{
InitializeComponent();
for (int i = 0; i < 100; i++)
{
Thread.Sleep(2000);
string app = "notepad";
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("LINK/ob/ob.php?text=" + app).Result;
var contents = result.Content.ReadAsStringAsync().Result;
string decider = contents.ToString();
if (decider.Length > 7)
{
van.Text = "The " + app + " is ON";
van.TextColor = Xamarin.Forms.Color.Green;
}
else
{
van.Text = "The " + app + " is off";
}
}
}
first, don't do this in the constructor. Doing so guarantees that your page won't display until the code completes
second, instead of doing this in a loop with Thread.Sleep() use a timer instead
Timer timer;
int counter;
protected override void OnAppearing()
{
timer = new Timer(2000);
timer.Elapsed += OnTimerElapsed;
timer.Enabled = true;
}
private void OnTimerElapsed(object sender, ElapsedEventArgs a)
{
counter++;
if (counter > 100) timer.Stop();
// put your http request code here
// only the UI code updates should run on the main thread
MainThread.BeginInvokeOnMainThread(() =>
{
if (decider.Length > 7)
{
van.Text = "The " + app + " is ON";
van.TextColor = Xamarin.Forms.Color.Green;
}
else
{
van.Text = "The " + app + " is off";
}
});
}

Multithread using backgroundworker and event handler

I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response

I get an error when network is disconnected

I have a C# windows form that is running automatically (as I have a timer set at the beginning). It is going to read and insert some records into the table. This program giving me error when network is disconnected. I want it resume working after network back as it is running automatically.
this is the program:
private void UtilityForm_Load(object sender, EventArgs e)
{
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(tmrProcess_Tick);
timer.AutoReset = true;
timer.SynchronizingObject = this;
timer.Interval = 1000;
timer.Enabled = true;
}
private void tmrProcess_Tick(object sender, EventArgs e)
{
ProcessLeads();
}
private void ProcessLeads()
{
tmrProcess.Stop();
lblActive.BackColor = Color.Red;
Application.DoEvents();
//I m getting error here
TransmissionBuilder transmissionBuilder = new TransmissionBuilder();
TransmissionAgent transmissionAgent = new TransmissionAgent();
int leadCount = 0;
if (transmissionBuilder.Count > 0)
{
toolStripProgress.Maximum = transmissionBuilder.Count;
toolStripProgress.Minimum = 0;
toolStripProgress.Value = 0;
}
try
{
foreach (XDocument document in transmissionBuilder)
{
transmissionAgent.SendPingTransmission (transmissionBuilder.CurrentPingDocument);
if (transmissionAgent.PingWasAccepted)
{
transmissionAgent.SendLeadTransmission(
transmissionBuilder.CreateLeadDocument(
transmissionAgent.ReservationCode
)
);
}
TransmissionLog transmissionLog = new TransmissionLog();
transmissionLog.WriteLogEntry(
transmissionBuilder.CurrentApplicantId,
transmissionBuilder.CurrentPingDocument.ToString(),
transmissionAgent.PingResponse.ToString(),
transmissionBuilder.CurrentLeadDocument.ToString(),
transmissionAgent.LeadResponse.ToString(),
transmissionAgent.ReservationCode,
transmissionAgent.ConfirmationCode,
transmissionAgent.PingReason,
transmissionAgent.LeadReason,
transmissionAgent.PingWasAccepted,
transmissionAgent.LeadWasAccepted);
toolStripProgress.Value += 1;
lblMessage.Text = ++leadCount + " out of " + transmissionBuilder.Count.ToString() + " have been processed...";
Application.DoEvents();
if (!processIsRunning)
{
lblMessage.Text += " after " + leadCount.ToString() + " leads.";
toolStripProgress.Value = 0;
break;
}
}
transmissionBuilder.Dispose();
toolStripStart.Enabled = true;
toolStripProgress.Value = 0;
if (leadCount == 1)
lblMessage.Text = "1 lead was processed.";
else if (leadCount > 1)
lblMessage.Text = leadCount.ToString() + " leads were processed.";
else
lblMessage.Text = "Process is waiting for leads to send...";
}
catch (Exception e)
{
Utilities.LogError((long)transmissionBuilder.CurrentApplicantId, e.Message + e.StackTrace);
Utilities.WriteToFile(e.Message + "-----" + e.StackTrace);
lblMessage.Text = "Error while connecting with ACE Server. Retrying...";
}
finally
{
lblActive.BackColor = Color.Green;
tmrProcess.Start();
Application.DoEvents();
}
}
it gave me error at these lines:
TransmissionBuilder transmissionBuilder = new TransmissionBuilder();
TransmissionAgent transmissionAgent = new TransmissionAgent();
The error is:
A transport level error has been occured when receiving result from the server.(provider: TCP provider, error: 0 -The semaphore timeout period has expired)
I try to put try-catch but when network is disconnect I get error message as a loop like 1000 times till network connected and the program resume working after. How I can prevent it from giving me this error message?
Why not use a Flag before the loop and set to true when there is an error, like:
Boolean hasShownMessage = false;
foreach (XDocument document in transmissionBuilder)
{
// On catch change it
catch (Exception e)
{
if (!hasShownMessage)
{
Utilities.LogError((long)transmissionBuilder.CurrentApplicantId, e.Message + e.StackTrace);
Utilities.WriteToFile(e.Message + "-----" + e.StackTrace);
lblMessage.Text = "Error while connecting with ACE Server. Retrying...";
}
hasShownMessage = True; // Set the flag to True
}
}

Why doesn't my disconnect button work?

I am working on this GUI for serial port application. I recently added stop and wait protocols to the application. Surprisingly my disconnect button stopped working. I have thought through the logic and I have not been able to find the problem.
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public bool packetreceived = false;
private SerialPort sp = null; //<---- serial port at form level
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//delegate variable to disconnect
public AddDataDelegate disconnectDelegate = null;
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
}
/**
* Takes byte array and returns a string representation
*
*/
public String parseUARTData(byte[] data)
{
if (data.Length == 11)
{
String rv = "";
DataFields d = new DataFields();
if (!packetreceived)
{
d = mainLogic.parseData(data);
packetreceived = true;
}
//TODO
System.Threading.Thread.Sleep(5000);
if (d.sequence == 0)
{
sp.Write("1\r\n");
}
else
{
sp.Write("0\r\n");
}
packetreceived = false;
//now display it as a string
rv += STR_OPCODE + " = " + d.opcode + "\n";
rv += STR_CRC + " = " + d.crc + "\n";
rv += STR_SEQ + " = " + d.sequence + "\n";
rv += STR_FLAGS + " = " + d.flags + "\n";
rv += STR_TEMP + " = " + d.temperature + "\n";
rv += STR_HUMID + " = " + d.humidity + "\n";
rv += STR_PH + " = " + d.ph + "\n";
return rv + "\n\n";
}
else
{
return Encoding.ASCII.GetString(data);
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s = sp.ReadExisting();
if (disconnectDelegate != null)
{
disconnectDelegate.Invoke(s);
}
richTextBox1.Invoke(this.myDelegate, new Object[] { parseUARTData(Encoding.ASCII.GetBytes(s)) });
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
//sp.PortName = this.comboBox1.SelectedItem.ToString();
sp.Open();
}
// send data to port
sp.Write("####,###########\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (sp.IsOpen)
{
// send data to port
sp.Write("+++\r\n");
//add the delegate
disconnectDelegate = new AddDataDelegate(onDisconnect);
//sp.WriteTimeout = 500;
// sp.Write("####,0\r\n");
}
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (string port in ports)
//{
// comboBoxSerialPorts.Items.Add(port);
//}
}
private void onDisconnect(string msg)
{
string trimmedMsg = msg.Trim();
if (trimmedMsg.Equals("OK"))
{
//send the second time
sp.Write("##,0\r\n");
//null the object
disconnectDelegate = null;
}
}
private void comPort_Click(object sender, EventArgs e)
{
try
{
if (sp.IsOpen)
{
//send data to port
sp.Write("1\r\n");
MessageBox.Show("bluetooth is transmitting data...");
//message box telling user that you are asking for data.
}
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}

C# Getting Serial Port In use error and can't understand why

Basically I need to communicate with a COM serial printer. There are 2 timers, one will print one ticket at time, and the others will hang up checking for errors and resuming the printing when the errors are gone.
For example: Printer is printing but if I press the pause button an error (read in the buffer) will get some booleans to 1 and after I read them I am able to tell what the error is and stop the printing.
My problem is in the method ErrorTimer_Elapsed() which is the timer elapsed event and probably is linked to the ErrorCheck and SendToCom (which is the printing method). The problem is that program detects errors well, but when in ErrorTimer_Elapsed() I try to repeatdly check for error status changes, I get IO errors like:
-Can't acces COM PORT
-The resource you required is in use
and so on.
Can you help me? Thanks, here's the code (about 180 lines), I'm bumping my head on this since 3 days :( :
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
#region Variabili di istanza
private ArrayList _filesToPrint = new ArrayList();
private static SerialPort _serialPort1 = new SerialPort();
private string _portName = ConfigurationSettings.AppSettings["COM"];
private string FilesPath = ConfigurationSettings.AppSettings["Path"];
private System.Timers.Timer PrintTimer = new System.Timers.Timer(2000);
private System.Timers.Timer ErrorTimer = new System.Timers.Timer(3500);
private bool PrintTimerIsActive = true;
private string HsCOMerrorStrings, PrintErrors;
#endregion
public Form1()
{
_serialPort1.PortName = _portName;
_serialPort1.ReadTimeout = 1000;
_IfFileExistsPrint();
}
private void _IfFileExistsPrint()
{
foreach (string file in Directory.GetFiles(FilesPath))
_filesToPrint.Add(file);
FileSystemWatcher SysWatch = new FileSystemWatcher(FilesPath, "*.*");
SysWatch.Created += new FileSystemEventHandler(SysWatch_Created);
SysWatch.EnableRaisingEvents = true;
PrintTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
PrintTimer.Start();
ErrorTimer.Elapsed += new System.Timers.ElapsedEventHandler(ErrorTimer_Elapsed);
}
private void SysWatch_Created(object Sender, FileSystemEventArgs w)
{
_filesToPrint.Add(w.FullPath);
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_filesToPrint.Count > 0 && PrintTimerIsActive)
{
PrintTimer.Stop();
SendFilesToCom(_filesToPrint[0].ToString());
MessageBox.Show("Printing file :" + _filesToPrint[0].ToString());
File.Delete(_filesToPrint[0].ToString());
_filesToPrint.RemoveAt(0);
_filesToPrint.TrimToSize();
Console.Write(HsCOMerrorStrings);
PrintTimer.Start();
PrintErrors = ErrorCheck(HsCOMerrorStrings);
}
}
private void ErrorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs d)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
}
try
{
HsCOMerrorStrings = _serialPort1.ReadExisting();
_serialPort1.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
Console.WriteLine(ErrorCheck(HsCOMerrorStrings));
}
private string ErrorCheck(string COMHostStatusReturn)
{
string ErrorsReturn = System.String.Empty;
string[] COMCode = COMHostStatusReturn.Split(',');
if (COMCode[1] == "1") { ErrorsReturn += "Carta Esaurita" + Environment.NewLine; }
if (COMCode[2] == "1") { ErrorsReturn += "Stampante in Pausa" + Environment.NewLine; }
if (COMCode[5] == "1") { ErrorsReturn += "Memoria Stampante Esaurita" + Environment.NewLine; }
if (COMCode[9] == "1") { ErrorsReturn += "Memoria RAM corrotta" + Environment.NewLine; }
if (COMCode[10] == "1") { ErrorsReturn += "Temperatura troppo bassa" + Environment.NewLine; }
if (COMCode[11] == "1") { ErrorsReturn += "Temperatura troppo alta" + Environment.NewLine; }
if (COMCode[7] == "1") { ErrorsReturn += "Partial Format Flag" + Environment.NewLine; }
if (ErrorsReturn != System.String.Empty)
{
if (PrintTimerIsActive == true)
{
PrintTimer.Stop();
if (!ErrorTimer.Enabled)
ErrorTimer.Start();
MessageBox.Show(ErrorsReturn);
}
PrintTimerIsActive = false;
}
else
{
if (PrintTimerIsActive == false)
{
ErrorTimer.Stop();
PrintTimer.Start();
PrintTimerIsActive = true;
}
}
return ErrorsReturn;
}
private void SendFilesToCom(string filePath)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
}
}
try
{
using (System.IO.TextReader reader = File.OpenText(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_serialPort1.WriteLine(line);
}
HsCOMerrorStrings = _serialPort1.ReadLine();
reader.Close();
_serialPort1.Close();
}
}
catch (Exception ex)
{
}
}
}
}

Categories

Resources