Debug Async MVC Action Controller with nested Async Methods - asp.net-mvc-4

I am calling a ASYNC method in an MVC4 application. This method has to call a dozen or so other methods, which are nested. My issue is that if any of these nested methods break, it passes the error to the parent method. Since they are all nested, it just keeps passing up the chain returning to the HTTP context the generic error message.
Since I have so many nested methods, I have no clue how to find more information on the error. Even a simple line that broke would be extremely helpful.
Right now I am resorting to breaking every line to see which ran last before it stop responding. This Method alone, with it's nested methods, are over 2000 lines of code. As you can tell, this is a very un-effective way at debugging.
Any help at a better way of finding out where a ASYNC method actually broke, when in nested methods, would be extremely helpful. I really want to avoid doing a Try/Catch on every method I have.
-- Edit --
This has been answered. I put my solution below and will mark it as answered in two days, per StackOverflow restrictions.

Apparently if I put a Try/Catch on the first call inside my Action Method it at least gives me the line in the stack trace. Once noting this, I added ELMAH and inspected my error log when throwing a generic exception. It appears that the line gets passed back to ELMAH also.
While this is not nearly as nice as normal exception breaking in visual studio, it allows me to easily put a breakpoint on that exact line to see what is happening.

Unfortunately, asynchronous "stack traces" do not work very well out of the box.
You can do your own tracing using a technique I describe in this blog post. Or you could try installing my async diagnostics package which adds the asynchronous "stack trace" to the exception's Data property (note: not logged by default in ELMAH). However, this package is not yet production-ready, so I recommend uninstalling before deploying.

Related

Generate a Mock object with a Method which raises an event

I am working on a VB.NET project which requires the extensive used of Unit Tests but am having problems mocking on of the classes.
Here is a breakdown of the issue:
Using NUnit and Rhino Mock 3.6
VS2010 & VB.NET
I have an interface which contains a number of methods and an Event.
The class which implements that Interface raises the event when one of the methods is called.
When I mock the object in my tests I can stub methods and create/assert expectations on the methods with no problems.
How do I configure the mock object so that when a method is called the event is raised so that I can assert that is was raised?
I have found numerous posts using C# which suggest code like this
mockObject.MyEvent += null...
When I try this 'MyEvent' does not appear in Intellisense.
I'm obviously not configuring my test/mock correctly but with so few VB.NET examples out there I'm drawing a blank.
Sorry for my lack of VB syntax; I'm a C# guy. Also, I think you should be congratulated for writing tests at all, regardless of test first or test last.
I think your code needs refactoring. It sounds like you have an interface that requires implementations to contain an event, and then another class (which you're testing) depends on this interface. The code under test then executes the event when certain things happen.
The question in my mind is, "Why is it a publically exposed event?" Why not just a method that implementations can define? I suppose the event could have multiple delegates being added to it dynamically somewhere, but if that's something you really need, then the implementation should figure out how that works. You could replace the event with a pair of methods: HandleEvent([event parameters]) and AddEventListener(TheDelegateType listener). I think the meaning and usage of those should be obvious enough. If the implementation wants to use events internally, it can, but I feel like that's an implementation detail that users of the interface should not care about. All they should care about is adding their listener and that all the listeners get called. Then you can just assert that HandleEvent or AddEventListener were called. This is probably the simplest way to make this more testable.
If you really need to keep the event, then see here for information on mocking delegates. My advice would be to mock a delegate, add it to the event during set up, and then assert it was called. This might also be useful if you need to test that things are added to the event.
Also, I wouldn't rely on Intellisense too much. Mocking is done via some crafty IL code, I believe. I wouldn't count on Intellisense to keep up with members of its objects, especially when you start getting beyond normal methods.

What is the main use of NSAssert Vs. NSException

What is the main use of NSAssert Vs. NSException. What is more recommended and when?
Assertions are generally used during development only and are compiled-out of the app when in release mode (this is controlled by NS_BLOCK_ASSERTIONS). Exceptions, on the other hand, can be used at all times.
When an exception is thrown, it travels back up the call chain, until it is either caught (and reported, ignored, or another exception is thrown) or it reaches the top, in which case it will cause the app to crash. It can be considered part of the contract of a class method and needs to be documented so the caller can handle this correctly.
Assertions are really a runtime developer check that ensure that something (generally a instance variable) is in a certain state and if it's not then abort() in order to bring the issue to the developers attention. It's a developer sanity check to check that something is in the state the developer expects it to be.
Assertions are used to find things that should never happen under any circumstances if your code is working the way you think it should be. If they are happening, there is a bug in your code and you want to know about it, at least if it happens during testing. (Most people turn off assertions in released code.)
In contrast, exceptions are used to find things that have gone wrong over which you have no control. For example, if your application is dependent on a database server and that database server is unavailable, that might raise an exception in your code. (Do not make the mistake of using exceptions for things like user input validation. If it's regular program flow--the user forgot to enter a field or whatever--that's not an exception. Exceptions should be exceptional.)

Error while doing GetComponentParts in MEF

While doing GetComponentParts I am getting following error, to be specific it reporoduces while i do import in continuous loop while handling multiple messages in my WCF application
The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) The composition failed because it did not complete within '100' iterations. This is most likely caused by a cycle in the dependency graph of a part which is marked with a non-shared creation policy.
One more thing I cant locate CompositionException.Errors to find the root cause.
Please suggest what workaround possible, as i am not getting a single thread on the net suggesting any way...
Many Thanks
Since this is working most of the time, it is probably a threading issue which is corrupting MEF's internal state and causing this error.
When using a CompositionContainer from multiple threads, you need to create it with the isThreadSafe parameter set to true, and avoid calling methods which modify what is available - such as Compose, ComposeParts, or AddExportedValue.
Methods which are safe to call are the GetExport and SatisfyImports methods.

Which Error Handling Model Is More Robust?

I'm kind of torn between these two error-handling models:
Create a boolean Error and a string ErrorMessage property for your object. Catch all exceptions internally in the object's methods and pass the messages along using conditional logic from the caller, ie:
Dim o As New MyObject
o.SomeMethod()
If Not o.Error Then
'Do stuff'
Else
Dim msg As String = o.ErrorMessage
'do something with message'
End If
Throw exceptions in your object and handle them on the outside with Try Catch logic:
Dim o As New MyObject
Try
o.SomeMethod()
'Do stuff'
Catch ex As Exception
Dim msg As String = ex.ErrorMessage
'do something with message'
End Try
To me, it seems like the same amount of code either way, except that you have property code for the Error and ErrorMessage properties. However, you also can tell when an error occurs without having to check for exceptions. Which pattern should I go with?
I have decided to go with throwing exceptions instead of using error/return codes. I just recently looked really hard into this.
The #1 reason to throw exceptions is there is a possibility you can forget to check the error code. If you don't check it, then you will continue working while the error exists. With exceptions though, if you forget to handle them, then the exception will raise to the top and stop all processing. It is better for this to happen than to continue after unknown errors have occurred.
For more info check out the Exception chapter in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, Second Edition by Addison-Wesley.
Joel Spolsky actually prefers error/return codes over exceptions but a lot of people disagree with him. Joel's post in favor of return codes can be found here. Check out this blog post and all of the comments with some good discussion regarding this subject.
Prefer #2. For details, see this excerpt on Exception Throwing from the development of Microsoft's excellent Framework Design Guidelines, as Dennis mentioned. Note especially the section on Exceptions and Performance.
Short version:
Do not return error codes.
Do report execution failures by throwing exceptions.
Do not use exceptions for normal flow of control.
I highly recommend reading the book for a full discussion, complete with commentary from a number of the Microsoft luminaries.
Exceptions should be used when something exceptional has happened.
e.g. you are passed a null (nothing) object when you expect one.
Uncle Bob recommends Exceptions over Error codes in his book Clean code.
He says
The problem with these [error codes] approaches is that they clutter the caller. The caller must check for errors immediately after the call. Unfortunately it's easy to forget. For this reason it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.
The biggest issue I have with the first one is that it's passive, easily overlooked and not very standardized. How will a programmer know to check that property? Or which properties / methods can possible set an error? Or which property / method access caused the error to be set?
For example. In your first sample code if o.Error is True, it's unclear whether the initialization of the object or the call to SomeMethod caused the flag to be set.
The exception model is an unignorable way of telling your users that an error occurred. It cannot be avoided without explicit code to handle the situation.
They are both accepted forms of error handling, however the preferred choice for .NET languages is to use exceptions.
There are a few problems with using return codes (either numeric or boolean), the two biggest being:
Easily overlooked/ignored by programmers.
Can't be used in all situations. What happens if your constructor fails? It's not possible for you to return a value explicitly from a constructor.
For these reasons alone, you should use exceptions. Exceptions provide a clean, standardized way to indicate and any failure no matter where it arises.
You will also end up with less code overall as you should only catch exceptions when and where you can safely and appropriately handle that exception.
I recommend using both.
Why?
"Use the right tool for the job"
The "problem" with return codes is that people often forget to handle them. However, exceptions don't solve this problem! People still don't handle exceptions (they don't realise a certain exception needs to be handled, they assume somebody up the stack will handle it, or they use a catch() and squash all errors).
While an unhandled return code might mean the code is in an unstable state, an unhandled exception often guarantees that the program will crash. Is this better?
While a return code is easily identifiable when writing code, it is often impossible (or just tediously time-consuming) to determine what exceptions might be thrown by a method you are calling. This typically results in a lot of very poor exception handling.
Exceptions are supposed to be used for "errors". Therein lies the difficulty. If a file is not found when you try to open it, is that an "error", or an "expected situation"? Only the caller knows. Using exceptions everywhere essentially elevates every piece of status information into an error.
Ultimately, error handling is something a programmer has to work at. This problem exists in both return codes and exceptions.
Thus, I use return codes for passing status information (including "warnings"), and exceptions for "serious errors". (and yes, sometimes it's hard to judge which category something falls under)
Example case from .net:
Int32.Parse throws exceptions (even though none of its exceptions are errors - it is up to the caller to verify the results and decide for themselves if the result is valid). And it's simply a pain (and a performance hit) to have to enclose every call to it in a try/catch. And if you forget to use a try/catch, a simple blank text entry field can crash your program.
Thus, Int32.TryParse() was born. This does the same thing, but returns an error code instead of an exception, so that you can simply ignore errors (accepting a default value of 0 for any illegal inputs). In many real life situations this is much cleaner, faster, easier and safer to use than Int32.Parse().
"TryParse" uses a naming convention to make it clear to the caller that errors might occur, that should be correctly handled. Another approach (to force programmers to handle errors better) is to make the return code into an out or ref parameter, so that the caller is explicitly made aware of the need to handle returned errors.

Best way to implement try catch in php4

What is the closest you can get to a try-catch block in php4?
I'm in the middle of a callback during an xmlrpc request and it's required to return a specifically structured array no matter what.
I have to error check all accesses to external resources, resulting in a deep stack of nested if-else blocks, ugly.
Late answer, I realise, sorry. I hope this is still relevant for you:
First, I'm echoing the comments your got in response to your post. PHP5 is the way to go.
However:
I'm in the middle of a callback during
an xmlrpc request and it's required to
return a specifically structured array
no matter what.
If you can vouch for that the program cannot possibly continue without getting a structured array back, and you absolutely have to work with PHP4, then an exit() or die() with detailed error information will get you much the same effect as a fatal exception would.
That's far removed from being graceful, of course. If you want something catchable, then return values and if-checking the result are your best bet, unfortunately. There are some standard ways of passing back specific error objects, but it's still the same thing - return the error object, if-check whether the result was an error object, react.
Still, take a look at PEAR's error object.