I'm having problems working with EntityFramework. While below peace of code works fine on my PC, when it's transported to a VPS (with everything properly preinstalled), it gives me a Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object, but the message box that is supposed to catch this does not show up. Any suggestions?
Thank you in advance.
var cc = new CopierContext();
try
{
MessageBox.Show(cc.Database.Connection.ConnectionString.ToString());
var matchingProviders2 = cc.Providers.Where(prov => prov.Login == "batman");
}
catch (Exception e)
{
MessageBox.Show(e.InnerException.Message);
}
Update:
I finally got to the core of the problem. The reason is: I've had .NET 4 on VPS, while application was developed using .NET 4.5. Installing the latter one removed all problems. Thank you for all your help.
I don't know how you are running it on your VPS, but if it is not launched under the interactive user account, your message boxes will not show up.
Well from the docs on the Exception.InnerException Property
The InnerException property returns the same value as was passed into
the constructor, or a null reference
Since you're catching any old exception catch (Exception e) its quite possible that the exception that's being thrown isn't the exception you were expecting and doesn't have a InnerException. This means your catch block may be raising an exception.
There are several actions you could take.
Do not catch System.Exception exception in anything but a top level exception handler. Only catch exceptions you know what to do with. Which leads to...
Set up a top level exception handler
Finally when logging or displaying exception messages at least make sure you have an inner exception before you try and use it.
MessageBox.Show( (e.InnerException != null ? e.InnerException : e).Message );
Don't use a MessageBox as it is a service; log them to disk instead such that you can recall them, or perhaps automatically mail them to you such that you are up to date on problems occuring.
You will also want to add e.InnerException.StackTrace to the log.
My bet is that you did not configure something (or did not configure it correctly) and cc.Database.Connection.ConnectionString is null. Calling .ToString() causes the NullReferenceException. That's why you don't see the message box. As other people said - using MessageBox for this kind of debugging is not a good idea. In the catch you should print not message but e.ToString() it will show the stack trace that should point to the place where the problem is.
Related
I have log4net successfully setup for my C# application. Everything works fine, except when I do this:
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("test", ex);
}
All I get is the message "test", I do not get the exception at all. Then, when I do this:
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error(ex);
}
I get the exception as desired, stack trace and everything. This works, but ideally I'd like to have both the message and the exception.
Why does the exact same code (no configuration changes) not work in the first example but it does in the second example? Am I reading the docs wrong for the Error() method?
The first overload you are using is the one that you want: Error(string, Exception). If the exception is actually written depends on your appender and / or the layout you choose. Here is explained how to disable printing of the stacktrace: https://stackoverflow.com/a/3660529/106567
I need to see your configuration in order to tell why the exception is not printed.
The code that "works" is not really what you should do: log.Error(ex) seems to do what you want since log4net treats the exception as the message object and simply calls toString() on it. Any appender / layout that specifically deals with exceptions would be unable to process the exception properly. The same happens if you use one of the ErrorFormat overloads (actually I never quite understood, why you cannot use a formatted string and an exception at the same time).
The solution was not relevant in the code I posted, but I was not fixing the flags correctly. The eventual solution was already found in this stack overflow post
Try
log.ErrorFormat("test: {0}", ex);
Iam a newbie who needs help. When saving to a database, i get the following error:
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in (name of my application)
Please help me with steps to solve this one. Thank you in advance.
First chances exceptions will be shown if you have your Visual Studio settings set so that every CLR exceptions gets reported. This will include exceptions you actually handle.
In Visual Studio's menu, go to Debug > Exceptions and uncheck the Thrown option for Common Language Runtime Exceptions.
Of course that won't make the actual exception go away but you'll be allowed to handle it as you want:
try
{
// do your query
// commit current transaction if possible/necessary
}
catch (SqlCeException ex)
{
// handle exception here and rollback current transaction if possible/necessary
}
finally
{
// ensure proper disposal of any commands and connections you have
}
It goes without saying that you must ensure your query is properly written and that the server objects it tries to work with exists. You generally won't want to handle cases where a comma is missing or a field is not found, for instance. Exception handling must be for exceptional situations your code cannot control, like a faulted connection, a server malfunction, etc.
First of all you might want to check whehter your SQL query is syntactically correct.
Secondly you might want to read about how to handle exceptions in MSDN http://msdn.microsoft.com/en-us/library/0yd65esw.aspx with try-catch statement.
A small example looks like this.
try
{
// ... code which throws exception
}
catch (SqlCeException e)
{
// ... exception handling, e.g. logging, rolling back data,
// telling the user something went wrong, you name it
}
Last but not least you might want to debug your application step by step to see what is causing the error and what the actual SQL Query is throwing the exception.
I am using a library that doesn't seem to document the exceptions. This library is used to communicate with a product the company makes. I want to be able to differentiate between the exceptions that get thrown but I don't know the names of the exceptions (for example between a communication timeout or under-voltage condition).
All of their examples only use catch(Exception ex). How can can I find what I need to use to catch the individual errors? When I do ex.toString() I get something like this:
System.Exception: Timeout
at CMLCOMLib.EcatObj.Initialize()
at copley_cmo_test.MainWindow.btnConnect_Click(Object sender, RoutedEventArgs e)
in c:\Users\adam.siembida\Desktop\copley_cmo_test\copley_cmo_test\MainWindow.xaml.cs:line 41
This:
System.Exception: Timeout
shows that they're just throwing a bare System.Exception, e.g.
if (weHaveNoApiDesignSkills)
{
throw new Exception("Timeout");
}
It's possible that there are some exceptions which are better designed, but the one you've shown isn't promising :(
Unfortunately unless you start using the message in the exception to differentiate between them (which is almost always a bad idea) you're stuck. It may be worth asking the authors of the library to see if they can improve matters for a future release.
Catch it with a catch-all construct such as catch(Exception ex), then examine the Type returned by ex.GetType(). If it's equal to typeof(Exception), it means that they aren't throwing anything more specific than Exception.
By the way, if you're stopped when the exception has been caught (ie, in a catch block), if you enter $exception in the watch window, you will see the entire exception.
When the API in library which you are using is not documented properly , you should catch the base exception and log it not only by the message instead whole exception by converting the exception to string . Eg.
try
{
//api call which throws exception.
}
catch(Exception ex)
{
//log ex.ToString();
}
use a decompiler for example:
http://www.jetbrains.com/decompiler/
in .net there's no explicit exception declaration like in java so as i see it it's the only way.
I have developed a project which uses an external dll as FTPServer, I have created the FTP Server on my project like this:
private ClsFTPServer _ClsFTPServer;
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
The Code above creates an instance of FTP server class, the class starts the FTPserver on it's constructor, it works fine independently as a module while the clients send their request correctly, but when an incorrect request comes to FTP server it throws an exception and cause my application to crash.
How can I handle the exception thrown by the external dll to prevent my application from crashing?
I recently answered a similar (ish) question which may prove useful -
Catch completely unexpected error
EDIT. I have to agree with Hans' comment above - might be an idea to find another FTP server.
Just for completeness, here's the appdomain/thread exception setup from - http://msdn.microsoft.com/en-GB/library/system.windows.forms.application.threadexception.aspx
Application.ThreadException += new ThreadExceptionEventHandler (ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
In case of using external unmanaged\unsafe code, .NET (above .net 4) by default cannot handle Memory Access Violation exceptions that happens inside of dll code.
in order to catch these kind of exceptions, there is three things to do. I did them and it worked for me:
Add these Attributes to the method that exception occurred inside of it :
(the method that calls the method of the unmanaged code.)
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
Add this tag to App.Config file below runtime tag :
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
<!-- other tags -->
</runtime>
Catch these kind of exception by using System.AccessViolationException exception type :
try{
//Method call that cause Memory Access violation Exeption
}
catch (System.AccessViolationException exception)
{
//Handle the exception here
}
What i said is just the cure for these type of exception. for more information about this exception's ego and how this approach works, see System.AccessViolationException
You've probably already tried this, but just in case, have you tried wrapping it in a try catch?
try
{
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
...
}
catch(Exception e)
{
...
}
By putting a try...catch block around every call into the object and its methods.
Something like:
try
{
// use the DLL in some way
}
catch (Exception e)
{
// Handle the exception, maybe display a warning, log an event, etc.)
}
Also note that while running under Visual Studio, if you go to the "Debug" menu and select "Exceptions..." it will allow the debugger to break on ALL exceptions if you start your program under the debugger, and not just unhandled exceptions. Just click the 'Thrown' checkbox next to "Common Language Runtime Exceptions".
I read a lot about how bad catching base Exceptions is and I have to confess that I did it also:
try{
...
}
catch (Exception exception){
MessageBox.Show(exception.Message, "Error!");
MyLogger.Log(exception.Message);
}
Now I would like to do it right and have some questions about it:
Which exceptions should I catch (for example FileNotExists for file manipulation, but what for TableAdapter or ReportClass (CrystalReports))
Where can I see a list of exceptions, that an objects can throw (for example TableAdapter)
Where in Windows Forms Application can I set a static method, which will log any exception to a file for example
Any other suggestions?
Catch whichever exceptions you can reasonably handle. For example, if you're trying to open a file for writing, you should expect that maybe the file is marked read-only, so that would throw an exception. But in the same situation you wouldn't try to catch a null argument exception, because that would be due to programmer error.
They should be found in the function reference in MSDN (you'll have to look it up on each one). For user-defined functions, you'll have to go digging, unless there is additional documentation or summary commentary.
3, 4. Consider using a logging library for .NET
I have one thing to add. If you just want to log an exception without affecting program flow you can always do this:
try
{
...
}
catch (Exception exception)
{
MyLogger.Log(exception.Message);
throw;
}
That's up to you to decide which exceptions your application logic can reasonably expect to recover from.
Exceptions are thrown by method invocations, not objects. In Visual Studio, Intellisense explanations will tell you which exceptions are thrown by an object (provided that the XML documentation describes which exceptions a method throws.
Rather than use a static method, respond to the Application.ThreadException event. The link provided has examples.
MSDN
You can set an event for unhandled exceptions in application events file
(got a VB sample here but i hope you get the point)
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
End Sub
You can find the application events in the options of you project.
You should only catch exceptions you can do something about, really.
That's the rule of thumb. I typically have a try/catch around my Program.Main just in case an exception bubbles right to the top and needs logging. You can also handle the CurrentDomain_UnhandledException event, in case exceptions are thrown in other threads than the UI thread (assuming you are multithreading).
In response to "4. Any other suggestions?":
In your example code, a message box is displayed before logging the exception. I would recommend logging the exception before displaying the message, just in case the user sees the error message, panics, and goes on vacation without clicking "OK". It's a minor thing, but message boxes block the program indefinitely and should be used with discretion!