C# console application - c#

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.

Related

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

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

Windows Service not working when installed, works fine in Debug mode; crashes on Moving/deleting files

I created a windows service which watches a directory. When a file is dumped into it, it takes the data and puts it into a database. Then this file is moved to another directory and deleted. It works fine in debug mode. But when i install it on my computer it stops after throwing the data into the database and the file in question is neither moved or deleted. I suspect a permission issue is involved. I tried to create a event log:
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
So i have three questions.
(1) What could be causing my service to work as described in debug but fail when installed on my computer.(2) I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method.(3) Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools? stored as a file on some directory?
Here is edit to this post in lieu of the grateful advice given below.
try
{
File.Move(e.FullPath, finalString);
File.Delete(e.FullPath);
}
catch(Exception q)
{
EventLog.WriteEntry("MySource", q.ToString(), EventLogEntryType.Error);
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["fmd"], true))
{
w.Write(DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss"));
w.Write(q.ToString());
}
}
As per suggestion i put a try-catch around the file move and delete plus i added a OnShutdown method:
protected override void OnShutdown()
{
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["ond"], true))
{
w.Write("stop OnShutdown");
}
//EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
}
I do not know how to pass any system error message to the shutdown method, so any advice appreciated. When i installed my modified code as a service, it again stopped before moving or deleting the files. Neither of my two logs accessed by a stream recorded anything. Plus the event viewer showed nothing either?
You can write as following,
if (!EventLog.SourceExists("MySource"))
EventLog.CreateEventSource("MySource", "Application");
EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
to view the event log messages, Goto Administrator Tools -> Event Viewer and look for the source you have created. or Just simply type eventvwr in run window.
When Services installed, it works under SYSTEM User account where service might not have access to some resources. Please put logs and see where exactly the issue is.
If you service installed in your development machine, use attach to process option under DEBUG Menu in Visual Studio to find out.
What could be causing my service to work as described in debug but fail when installed on my computer?
Permissions. The service is likely running under LocalSystem or Network Service if you didn't provide a different identity.
I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method?
Yes, you're assumption is correct.
Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools?
Just hit Windows Key+R to get the Run dialog and type eventvwr.
Well i found the reason for all the commotion. I eventually found some logs in the event viewer. They were listed in Administrative events in custom logs. There were three error logs: .Net runtime; Application error & Service Control Manager. In '.Net Runtime' the stack showed a unhandled exception for system.windows.forms. I stupidly included a pop up box in my release version. But even when i commented this away; i got a error. So i went back and found other message boxes, primarily in try catch statements. Removed these and solved the issue.

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.

Silverlight 4 Getting full exceptions

I have a silverlight application elevated trust deployed at my company and some errors I get the "debugging resource strings are unavailable" I was wondering if there was any way currently for silverlight 4 to get the full error message without installing the developer version of silverlight on every single machine.
Thanks in advance
Hope this article helps u... Check this
By default, the full exception strings are not enabled in silverlight. You need to enable it in the slr.dll.managed_manifest file.
I would wrap the code giving the exception in try/catch brackets and then use MessageBox.Show to display the error message;
try
{
// Code that crashes
}
catch (Exception e)
{
MessageBox.Show("Error: " + e);
}
Exception also contains some other useful variables.
Hope this helps.

Categories

Resources