I have been trying to log exceptions to a file. I can get the exception with all its details and when I step through the class the StreamWriter logWriter doesn't seem to do what I thought it would do.
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
StreamWriter logWriter;
if (File.Exists(logfile))
{
logWriter = File.AppendText(logfile);
}
else
{
logWriter = File.CreateText(logfile);
logWriter.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
logWriter.Close();
throw exception;
}
}
catch (Exception e)
{
throw;
}
}
I would of thought the logWriter would of written the exception details to the File.AppendText(logfile)but it doesn't and just jumps straight out the if statement. All the details of the exception are in the else statement, I have tried to put this in theif` condition but throws an exception!
How can I write the exception to the file. I got the code from CodeProject. Everything thing works fine except writing the exception to the file.
Try it correctly and throw the exception outside of the method:
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
if(File.Exists(logfile))
{
using(var writer = new StreamWriter(logfile, true))
{
writer.WriteLine(
"=>{0} An Error occurred: {1} Message: {2}{3}",
DateTime.Now,
exception.StackTrace,
exception.Message,
Environment.NewLine
);
}
}
}
catch(Exception e)
{
throw;
}
}
Throw it outside:
catch(Exception e)
{
Write(e);
throw;
}
This snippet works to write into a file
public static bool WriteResult(string result)
{
using (StreamWriter sr = File.AppendText("result.txt"))
{
sr.WriteLine(result);
sr.Flush();
return true;
}
return false;
}
For you, you have to adapt it a bit to meet your requirments :
public static void Write(Exception exception) {
try {
using(StreamWriter sr = File.AppendText("result.txt")) //new StreamWriter("result.txt", Encoding. ))
{
sr.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
sr.Flush();
}
catch (Exception e) {
throw;
}
}
A nice template method i wrote goes with every project.
private static void AddLog(string strMsg)
{
#region logfolder creation
if (!System.IO.Directory.Exists("C:\\appname"))
{
System.IO.Directory.CreateDirectory("C:\\appname");
if (!System.IO.Directory.Exists("C:\\appname\\Logs"))
{
System.IO.Directory.CreateDirectory("C:\\appname\\Logs");
}
}
#endregion
#region logfile creation
FileStream fsc;
logFileName = "C:\\appname\\Logs\\appnameLog_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
if (!System.IO.File.Exists(logFileName))
{
fsc = new FileStream(logFileName, FileMode.Create, FileAccess.Write);
fsc.Close();
}
#endregion
#region logging
using (FileStream fs = new FileStream(logFileName, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fs))
{
try
{
sr.WriteLine(strMsg);
}
catch (Exception exc)
{
EventLogEntry(exc.ToString().Trim(), EventLogEntryType.Error, 7700);
}
}
}
#endregion
}
Related
When using the back ground worker class to call a method within a try catch statement, and a try catch statement is in the method, which one catches the exception?
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
Do();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
}
}
And:
private void Do ()
{
try
{
//Do something, open a file etc.
FileStream fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
catch (Exception e)
{
System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
}
}
Called with: backgroundWorker1.RunWorkerAsync();
Is there a way to make sure the exception is handled within the method? so the backgroundworker doesn't break?
The inner one since this catch is "closer" to the "error"
this one :
private void Do ()
{
try
{
//Do something, open a file etc.
FileStream fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
catch (Exception e)
{
System.Windows.MessageBox.Show("Error:" + e.Result + ex.Message);
}
}
In my project i need to create an excel file in users desktop. Code written in my visual studio is.
string sPathTestData1 = "\\AdaptiveModulations.xls";
string sPathTestData = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations" + sPathTestData1;
string sheet = "Sheet1";
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
ExcelUtils.createExcelFile(sPathTestData,sheet);
}
else
{
ExcelUtils.setExcelFile(sPathTestData,sheet);
}
This code is working perfectly in my system and creating folder with excel file but when i copied the exe from C:\Visual Studio 2015\Projects\AMCalculator\AMCalculator\bin\Debug folder and saved in another machine it showing error can anyone help on this
I have added try/catch blocks in my classes
In ExcelUtils Class :
public static void createExcelFile(String filepath, String sheetName)
{
try
{
using (FileStream stream = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite))
{
workBook = new HSSFWorkbook();
workSheet = workBook.CreateSheet(sheetName);
workBook.Write(stream);
stream.Close();
}
}
catch (Exception e) {
Console.WriteLine("Unable to Create File. Exception is : " + e);
}
}
public static void setExcelFile(string filepath, string sheetName)
{
try
{
Console.WriteLine("File Path is : " + filepath);
workBook = WorkbookFactory.Create(new FileStream(
Path.GetFullPath(filepath),
FileMode.Open, FileAccess.Read,
FileShare.ReadWrite));
workSheet = workBook.GetSheet(sheetName);
}
catch (Exception e)
{
Console.WriteLine("Unable to Load File. Exception is : " + e);
}
}
In My main class :
if (!File.Exists(sPathTestData))
{
Directory.CreateDirectory(path);
try
{
ExcelUtils.createExcelFile(sPathTestData, sheet);
}
catch (FileNotFoundException fe)
{
Console.WriteLine("Unable to Create File. Exception is : " + fe);
}
}
else
{
try
{
ExcelUtils.setExcelFile(sPathTestData, sheet);
}
catch (FileNotFoundException fe)
{
Console.WriteLine("Unable to Load File. Exception is : " + fe);
}
}
I have a Windows service that exits or crashed because of internet outage. Is there a simple way to monitor it to make sure it gets restarted automatically if it crashes?
Update
Here is the exception that we often got from the service.
An error has occured with the myservice:
Exception Message: The operation has timed out
Inner Exception:
Date Time: 11/13/2015 8:03:09 PM
Stack Trace: at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at myservice.CrmSdk.CrmService.Delete(String entityName, Guid id)
at myservice.myservice.timer1_Elapsed(Object sender, ElapsedEventArgs e)
Here is what going on into the service.
public partial class myservice : ServiceBase
{
public myservice() {
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("myservice Source"))
{
System.Diagnostics.EventLog.CreateEventSource("myservice Source", "myservice Log");
}
eventLog1.Source = "myservice Source";
eventLog1.Log = "myservice Log";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("myservice service started on " + DateTime.Now.ToString());
//timer1.Interval = 60000;
//timer1.Start();
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
int intProcessHour = Convert.ToInt32(ProcessHour);
DateTime dtNow = DateTime.Now;
if (dtNow.Hour < intProcessHour){
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}else{
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}
}
protected override void OnStop(){
eventLog1.WriteEntry("myservice service stopped on " + DateTime.Now.ToString());
}
public string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
public int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
public string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
public bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
eventLog1.WriteEntry("myservice timer1_Elapsed begin on " + DateTime.Now.ToString());
/* Create audit if not exists*/
}
catch (Exception ex)
{
eventLog1.WriteEntry("myservice - Exception Notice.\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Stack Trace: " + ex.StackTrace);
eventLog1.WriteEntry("Exception. myservice timer1_Elapsed ended on " + DateTime.Now.ToString());
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
DateTime dtStartDateTime = DateTime.Today.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now.ToString() + "\n\n" +
"Stack Trace: " + ex.StackTrace);
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]);
client.Send(message);
}
}
private void eventLog1_EntryWritten(object sender, EntryWrittenEventArgs e)
{
}
}
If you have access to the source code of the service, you should try to fix the service by adding proper error handling etc. If you do not have access to the source, you may try this.
1) Go to services
2) Right click on the service
3) Goto recovery tab
4) Select "Restart service" for first failure, 2nd failure and subsequent failures. Then click apply/ok.
Rewrite your code like this;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Mail;
using System.ServiceProcess;
using System.Timers;
namespace WindowsService1
{
public partial class myservice : ServiceBase
{
private EventLog _eventLog1;
private Timer _timer1;
public myservice()
{
InitializeComponent();
}
private void InitialiseService()
{
try
{
const string source = "myservice Source";
const string name = "myservice Log";
_eventLog1 = new EventLog();
if (!EventLog.SourceExists(source))
{
EventLog.CreateEventSource(source, name);
}
_eventLog1.Source = source;
_eventLog1.Log = name;
WriteLog("myservice service started on " + DateTime.Now);
int intProcessHour;
string processHour = ConfigurationManager.AppSettings["ProcessHour"];
var interval = (int.TryParse(processHour, out intProcessHour) && intProcessHour > 0 &&
intProcessHour < 24
? intProcessHour
: 1) * 60 * 60 * 1000;
_timer1 = new Timer(interval);
_timer1.Elapsed +=timer1_Elapsed;
_timer1.Start();
// Process(); //enable this if you want to process immidiately. Else the timer will process when it elapsed.
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void Process()
{
try
{
GetParentAccountID("xxx");
GetAuditGrade("yyyy");
GetAuditID("tttt", "45354345");
AuditRecordExists("rrrr", DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
SendEmail(ex);
}
}
private string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
private int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
private string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
private bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
WriteLog("myservice timer1_Elapsed started at " + DateTime.Now);
Process();
WriteLog("myservice timer1_Elapsed finished at " + DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
private void SendEmail(Exception ex)
{
try
{
using (SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]))
{
using (MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now + "\n\n" +
"Stack Trace: " + ex.StackTrace))
{
client.Send(message);
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
private void WriteLog(string logEntry)
{
try
{
if (!string.IsNullOrEmpty(logEntry) && _eventLog1 != null)
_eventLog1.WriteEntry(logEntry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStart(string[] args)
{
try
{
InitialiseService();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStop()
{
try
{
_timer1.Stop();
_timer1.Elapsed -= timer1_Elapsed;
WriteLog("myservice service stopped on " + DateTime.Now);
_eventLog1.Close();
_eventLog1.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
I need to access TextBoxes in my WPF application from another thread and I've got an exception. I know, there is a property Dispatcher in every UI control and a method BeginInvoke , but I don't know how to get values from TextBoxes.
So, here is the code:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
try
{
var task = new Task(() => TryConnect());
task.Start();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void TryConnect()
{
try
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text +
";Database=hospital;Uid=" + login.Text +
";Pwd=" + password.Text + ";";
using (MySqlConnection mcon = new MySqlConnection(con_str))
{
mcon.Open();
MessageBox.Show("Connection is OK!");
mcon.Close();
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ErrorCode.ToString() + " " + ex.Message);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
If you create a copy of the values you need, then you should be able to access them:
string username = login.Text, password = password.Text, ip = Ip.Text, port = Port.Text;
var task = new Task(() => TryConnect(username, password, ip, port));
And:
void TryConnect(string username, string password, string ip, string port)
{
// ...
}
Copying the values locally like this means you don't need to access UI elements from your background thread.
To answer your question, move the connection string build out of the task action:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
try
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text + ";Database=hospital;Uid=" + login.Text + ";Pwd=" + password.Text + ";";
var task = new Task(() => TryConnect(con_str));
task.Start();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void TryConnect(string con_str)
{
try
{
using (MySqlConnection mcon = new MySqlConnection(con_str))
{
mcon.Open();
MessageBox.Show("Connection is OK!");
mcon.Close();
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ErrorCode.ToString() + " " + ex.Message);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
But you have a lot of issues in this code.
Code behind in WPF is not "Best practice"
Try and have a look at this:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MessageBox on another thread can cause a lot of pain.
you are trying to catch an exception around the task creation, this will not catch exceptions thrown inside the action.
Try this instead:
private void TestConnection_Click(object sender, RoutedEventArgs e)
{
string con_str = "Server=" + Ip.Text + ";Port=" + Port.Text + ";Database=hospital;Uid=" + login.Text + ";Pwd=" + password.Text + ";";
var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
var task = new Task(() => TryConnect(con_str));
task.ContinueWith(task1 =>
{
//TODO Handle exception
System.Diagnostics.Trace.WriteLine(task1.Exception);
//or if you really want an messageBox, pass it back to the ui thread
dispatcher.Invoke(() => MessageBox.Show(task1.Exception.Message));
}, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
}
My Service read from com port and save the info in DB.It works perfectly fine for a while,but sometimes the error window is appeared for getting an exception,and if I don't click 'no' buttun , it doesn't read from com port.When I check in event viewer,I see some exception number 7034,7031 on my service.I log every where in my code and I use try,catch .I don't have ant catch in my log file,so I can't understand what is the problem?
public partial class Service1 : ServiceBase
{
string _fileName = #"c:\logSensor\log.ini";
internal delegate void StringDelegate(string data);
ArrayList lines = new ArrayList();
BL.EnterDatas eData = new BL.EnterDatas();
private class Line
{
public string Str;
public Line(string str)
{
Str = str;
}
}
public Service1()
{
InitializeComponent();
CommPort com = CommPort.Instance;
com.Open();
com.StatusChanged += OnStatusChanged;
com.DataReceived += OnDataReceived;
timer1.Enabled = true;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() +
" . " + "Step1:Load ");
writer.Flush();
}
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "timer1_Elapsed:Stop Timer ");
writer.Flush();
}
ReadLog();
StreamReader sr = new StreamReader(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\path.txt");
string _logPath = sr.ReadLine();
FileStream fs = new FileStream(_logPath, FileMode.Open);
fs.SetLength(0);
fs.Close();
}
catch (Exception ex)
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "Catch:timer1_Elapsed " + ex.Message);
writer.Flush();
}
}
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(_fileName, true))
{
writer.WriteLine(PublicVariable.DateShamsi() + " " + PublicVariable.Nowtime() + "final:timer1_Elapsed ");
writer.Flush();
}
timer1.Start();
}
#region Functions...
...
}