[C#]How to write log in runtime error situation? - c#

How to write log in Runtime Error situation?
I want to know where the error occurred at source code.(When I execute .exe file)
(I don't use Serial debugging)

You can use print the exception using Debug.WriteLine
catch (Exception ex)
{
Debug.Writeline(ex.ToString());
}
There is a catch in using for Compact framework, it wont have the same behaviour. But you can try this.
On Windows CE, any information passed to Debug.Write is displayed in a
temporary console window on the device. The console window
automatically opens on the fist call to Debug.Write and closes
immediately after the application exits. The console window can be
kept open by placing a breakpoint at the end of the application's
Main() function, to prevent the application from completely exiting.
More details - https://msdn.microsoft.com/en-us/library/aa446495.aspx

Related

The process cannot acces the file as it is being used by another process C#

I have a .Net console application. I would like to catch any exceptions occur during the execution and write it to a text file. If there is any entry on the file before, I am getting
The process cannot acces the file as it is being used by another process.
I tried closing the connections as well below but still it's showing the same error.
catch (Exception ex)
{
using (System.IO.StreamWriter writeerror = new System.IO.StreamWriter(_txtError))
{
writeerror.WriteLine(ex.Message);
writeerror.Flush();
writeerror.Close();
}
}
Note: At the start of the program execution I am deleting the file and regenerate if any error occurs.
Finally I found where was the issue. At the end of all the functions I had a send e-mail function which send the log file as attachment to a group. The problem is from my workstation I can't send emails. Once the deploy the code in server, e-mail task will function as it's supposed to do. I had a similar catch stmt for Send email task and when it fails it tries to write the same error file I'm ATTACHING in the email task. Once i removed the catch logic the issue is resolved. Whew!! I know.. It's a stupid mistake! :( Learnt something from this mistake

Catching exceptions in console application C#

I have a console application written in C#. This application runs as automation to test a web service.
Flow:
Log in to network share (impersonate user)
copy mp3 file to local disc
convert mp3 to wav
downsample
trim wave
extract some useful data from wav
send http request
delete local files
write out some stuff to tsv
The application will run great for several hours (usually takes about 24 hours to complete the test). but every once and a while I will get this message: "The application has stopped working. I have been running this is VS 2012 in debug mode so, I can see what line throws any error. problem is, that I have not been able to catch the line (or method) that is throwing the error. I originally thought that the Domain controller was causing this issue due to power settings.
How can I capture exactly what error is bubbling its way up the stack?
Does all that run in a loop of some kind? Or on a timer?
Perhaps put a try-catch around the body of the loop or the method that runs all your code, add a logging framework of your choice (log4net or nlog seem good) and then in the catch log the exception. Most logging frameworks allow you to include the exception and will include stacktrace, etc.
Putting debug logging throughout the process can also help to narrow down where it's happening.
You can go to the Event Viewer on the operating system the console application is running on and then click on "Application". Event viewer logs and displays all exceptions thrown on any application running on the operating system.
try
{
// your code
}
catch (Exception e)
{
System.IO.File.WriteAllText(#"Z:\err.txt", e.ToString());
}
Note that access to windows drives are denied for non administrators so replace Z: with your choice.
I recommend you using a logging framework.
I use log4net in almost all applications. Its very simple to use and configure.
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
// do whatever
}
catch(Exception ex)
{
// Log an error with an exception
log.Error("Exception thrown", ex);
}
By using these kind of libraries you can get your log data output to file, database or even written to the windows event-viewer for instance.
It looks like the exception code you are getting happens when you try to use something that is already been garbage collected. Are you using anything after it is disposed?
Knowledge Base Article for 0xc0000005

Not able to run the .exe file created from c#

I have created a Windows form application using C# in visual studio 2010 connecting the database in SQL server . After all my development is done i copy the exe file generated in my machine and pasted in another machine and try to execute it but it is not working .
i can see the process started in task manager but it was closed after 5 seconds . I even tried creating the setup for this application and installed in that machine still i am facing the same issue .
But in my machine it is working perfectly in the both the ways . can any one help me in finding where i went wrong .
Thanks in advance
As you don't provide the error, the answers and comments you are getting are educated guesses.
You should check the event viewer for errors...
This will let you learn what is going on. If you can't fix it, add this info to your question.
As you are not posting exception message, probably you re not properly catching exceptions. Just to be sure surround your main function in a Try/Catch.
In Catch, write some code to dump message exception into a file, or even better use Log4Net. For simplicity just add some code to write to a file now. Something like:
static void Main()
{
try
{
//Your code
}
catch (Exception ex)
{
//Write ex.Message to a file
using (StreamWriter outfile = new StreamWriter(#".\error.txt"))
{
outfile.Write(ex.Message.ToString());
}
}
}
PS: If it is a console application you can survive with Console.Write
Perhaps you have some referenced assemblies that you did not copy along with the application itself.
OR, the connection string is not valid when run from that other machine (if you worked with a local SQL db, or on a network or whatever and it's not accesible on that other machine)
OR, you don't have rights to run it on that other machine.

Permanently running executable

I created a winform (monitoring) application using VS 2005 (c#), and now, I have a problem when this application crashes for some reason, I have to be sure that it will be restarted automatically.
How can I resolve this? (maybe by using windows services application?)
Thanks
Yes, a creating a Windows Service would work as you can set it to automatically restart if it crashes but a better way would be to prevent it crashing in the first place! Is there a specific reason it crashes?
With good error handling and reporting you can write it so that it simply reports any errors that occur and carries on, which IMHO would be the best route to go
Consider this:
http://msdn.microsoft.com/en-us/library/cc303699.aspx
[DllImport("kernel32.dll")]
public static extern int RegisterApplicationRestart(
[MarshalAs(UnmanagedType.BStr)] string commandLineArgs,
int flags);
Minimum supported server
Windows Server 2008
http://msdn.microsoft.com/en-us/library/aa373347(VS.85).aspx
Creating a Windows service is a very good idea for any long-running background process for many reasons, however re-starting a crashed application is not one of them!
You should work out why the application is crashing and prevent it from happening.
By all means, also convert your application to a Windows service - you will see many benefits, however the correct way to solve your problem is to fix the application crash in the first place.
For*strong text* a watcher app.
You should create a timer on the windows service and code something like this in the timer tick event:
Process[] procs = Process.GetProcessesByName("you app name");
if (procs.Length == 0)
Process.Start("your app filename");
if you really cant do anything about the crash problem i would recommend a try-catch instead of a watcher. (Dont forget to re-throw handled major exceptions)
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
catch(Exception ex)
{
//log the exception here
Application.Restart();
}
}
Since you say that you use a Windows Forms application you cannot use a Windows Service for that, since a Windows Service is not allowed to have a GUI.
What I would do it that I would create an invisible "watchdog" application which monitors the process and automatically restarts it when it crashes.
Thanks you all, the solution I choose is : in the main program I add an exception events (UnhandledExceptionEventHandler & ThreadExceptionEventHandler see above) in these events I restart the program (also putting log & email to trace errors). And for the reboot problem I add registry key in [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] with my application path to be sure that my application will be restarted after the windows reboot ;)
You can put a try catch block around the code that is most likely causing the crash. Then write the exception message to a log file. You can also set a debug point in the catch block to see other details like call stack, etc.

C# console application

I have sample exe say console.exe on "programfiles\myAppFolder" .It serves the purpose of logging the message to eventviewer
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234);
I need to call this exe on un-install of appcn from NSIS script .However it gives me an error always that "thisappConsole has encountered a problem and needs to close. We are sorry for the inconvenience."
Even browsing to the path "programfiles\myAppFolder\thisappConsole.exe" and manually clicking on it to execute even throws the same error. I do have admin access to m/c.
Can anyone help me with this.
If I put any other simple console app without any additional "using statements". it works fine ..
Press F5.
This will run the programme in the debugger, and you the unhandled exception will be displayed on screen. It will give a exception type, message, and line number.
Sounds to me like your event log application is throwing an unhandled exception, quite ironic considering it is an application for logging events!
I would put my money on it being a permissions issue as the event log needs to access the registry. As a work-around try running your application as an Admin. Would be handy to handle the AppDomain.UnhandledException event and log the exception.
you could try
Try
{
your app code here
}
Catch (Exception ex)
{
//Logg ex.ToString()
}
Try
{
your code here
}
Catch (Exception ex)
{
ex.message="";
}
finally
{}
Check to be sure you have the same version of the .Net framework installed on that machine, and also any referenced .dll's are in the same folder as the .exe.

Categories

Resources