Is possible to get usefull exceptions in xamarin.forms + F#? - exception

I'm testing the viability of use Xamarin.Forms + F# for a side project. When things work, is great. But when the code have a problem, ALWAYS I get this exception:
System.TypeInitializationException: An exception was thrown by the type initializer for <StartupCode$BestSellerPOS>.$Forms
And not matter why the error happened. So, I need to step-by-step each line, from the start, just to see what happened.
This time this is the full exception (This have happened several times, but I don't record earlier errors to see if is the same exact backtrace... only remember that is the same initial exception):
System.TypeInitializationException: An exception was thrown by the type initializer for <StartupCode$BestSellerPOS>.$Forms ---> System.Exception: Missing or incorrect header for method .cctor
--- End of inner exception stack trace ---
at BestSellerPOS.Forms.get_mainForm () [0x00000] in <filename unknown>:0
at BestSellerPOS.App.get_FormDocs () [0x00000] in /Users/mamcx/Proyectos/BestSeller/BestSellerNET/Core/App.fs:7
at BestSellerPOS.AppDelegate.FinishedLaunching (UIKit.UIApplication app, Foundation.NSDictionary options) [0x0001c] in /Users/mamcx/Proyectos/BestSeller/BestSellerNET/iOS/AppDelegate.fs:16
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, IntPtr principal, IntPtr delegate) [0x00005] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:62
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:46
at BestSellerPOS.Main.main (System.String[] args) [0x00000] in /Users/mamcx/Proyectos/BestSeller/BestSellerNET/iOS/AppDelegate.fs:23
I have the last versions of everything, on yosemite.
P.D:
I have setup a blank solution with minimal coding, and force in the startup a divide by zero error. Still not get that error, instead a generic message.
Then create another black solution, this time, without the shared project, exactly as provide by the xamarin ios template. This give a good exception, and point to the exact location!

In F#, you get TypeInitializationException, when an exception occurs during module intialization. This suggests, that somewhere a let-bound value explodes. Without seeing the code, it will be difficult to say exactly where it happens.
But the solution usually means changing from a let bound value that is executed during initialization, to a function by adding say () on a few crucial places and deferring the execution until a more meaningful time where you can handle the exception as needed. Alternatively, you can declare your value as lazy and defer execution using that.
Generally, I'd advise against exceptions during module initialization, as the moment when the module initialization happens is not simple to predict.

Related

Exception 'System.OutOfMemoryException' was thrown

We currently have a site on IIS where the outside can go on and make payments, and the payment goes through an API to a third party and payment can be seen there. We also have a database that is on a different server than the site.
We have been getting an error "Exception of type 'System.OutOfMemoryException' was thrown" when payments try to come in and it seems to keep fixing by itself without us doing anything other than logging in to the server and sometimes restarting the server. For example, when customers try to make a transaction online, they will get this error sometimes. If they try again later, then it may go through successfully without error.
Is anyone familiar with this error and know where to look or begin?
Thank you
Exception of type 'System.OutOfMemoryException' was thrown.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method) +0
System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType, Object target) +41
System.Linq.Expressions.Expression`1.Compile() +187
System.Data.Common.Internal.Materialization.Translator.Compile(Expression body) +154
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
System.Data.Common.Internal.Materialization.Translator.Compile(Type resultType, Expression body) +237
System.Data.Common.Internal.Materialization.ReplacementExpressionVisitor.Visit(Expression expression) +222
System.Linq.Expressions.EntityExpressionVisitor.VisitExpressionList(ReadOnlyCollection`1 original) +155
System.Linq.Expressions.E
This is a common error when the application does not make proper use of server resources. Search for memory leaks in the code and other bad practices that could be affecting the performance. In the mean time you could just recycle the app pool several times a day, Its better than restarting the IIS process and cause less troubles to the clients.
You can checkout this link for more info

Exceptions in Lablgtk callbacks

In Lablgtk, whenever there is an exception in a callback, the exception is automatically caught and an error message is printed in the console, such as:
(prog:12345) LablGTK-CRITICAL **: gtk_tree_model_foreach_func:
callback raised an exception
This gives no stack trace and no details about the exception, and because it is caught I cannot retrieve this information myself.
Can I enable more detailed logging information for this case? Or prevent the exception from being caught automatically?
I guess the best way to do so is to catch your exception manually and handle it yourself.
let callback_print_exn f () =
try f () with
e -> my_exn_printer e
Assuming val my_exn_printer : exn -> unit is your custom exception printer, you can simply print your callbacks exceptions by replacing ~callback:f by ~callback:(callback_print_exn f) in your code.
Of course, you can also with that method send that exception to another
thread, register a "callback id" that would be passed along with your exception...
About the stack trace, I'm not sure you can retrieve it easily. As it's launched as a callback, you probably want to know the signal used and that can be stored in your callback handler.
I had another similar issue, but this time it was harder to find where to put the calls to intercept the exception.
Fortunately, this time there was a very specific error message coming from the Glib C code:
GLib-CRITICAL **: Source ID ... was not found when attempting to remove it`
Stack Overflow + grep led me to the actual C function, but I could not find which of the several Lablgtk functions bound to this code was the culprit.
So I downloaded the Glib source, added an explicit segmentation fault to the code, compiled it and used LD_LIBRARY_PATH to force my modified Glib version to be loaded.
Then I ran the OCaml binary with gdb, and I got my stack trace, with the precise line number where the Lablgtk function was being called. And from there it was a quick 3-line patch.
Hacks like this one (which was still faster than trying to find where to intercept the call) could be avoided by having a "strict mode" preventing exceptions from being automatically caught. I still believe such a switch should be available for Lablgtk users, and hope it will eventually be available.

Async exception not caught by debugger

I'm working on an MVC5 project in VS2013. I seem to be finding that most (but not all) of my exceptions are being ignored by the debugger and as a result I end up with the exception and stack trace simply being written to the browser, precluding any examination of the objects involved in the exception.
For instance - I deliberately code an exception to prove the point:
<Authorize(Roles:="IdentityAdmin")>
Public Async Function Import(model As RegisterViewModel) As Task(Of ActionResult)
Dim a As Object = "he"
Dim b As Integer = a
Clearly the last line will throw a 'type mismatch' exception which I think should result in the debugger halting execution, highlighting the error in the VS2013 UI to enable me to examine the various objects and determine the problem.
Instead I simply find myself with the browser detailing the exception and VS2013 unresponsive:
Server Error in '/' Application.
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a
correct format.
Source Error:
Line 291: If Db.Users.Find(acct.username) Is Nothing Then
Line 292: Dim a As Object = "he"
Line 293: Dim b As Integer = a
When I insert the same exception-generating code into a non-async part of the code the VS debugger does catch the exception - so I am guessing this is an issue with debugging async code. Is it really the case that the VS debugger can't catch these exceptions?
UPDATE
After further searching I came across a suggestion to disable 'Just My Code' and manually enable various types of exception. There was the expected hailstorm of First Chance Exceptions most of which I could tune out by disabling certain exceptions. But this DID 'fix' the behaviour described above. It seems that the debugger is regarding my child async threads as 'Not My Code'. Slightly baffled but I guess this could be an answer of sorts?
As per the update above, the problematic behaviour detailed in the question seems to be fixed by a combination of:
Turn off 'Just My Code' in the debugger options.
Enable certain classes of exceptions in Debug/Exceptions.. - in my case Common Language Runtime Exceptions and Managed Debugging Assistants seemed to ensure that the debugger caught all my exceptions (async or otherwise).
Disable thrown (but unremarkable) exceptions which cause most grief (wrong globalisation etc).
The last two stages were happened upon somewhat by trial and error and I suspect I should ultimately chase down most of these non-breaking exceptions when I clean the project up.
Disabling Just My Code should not make a difference in this case, enabling "Break when an exception is thrown" is what you want to make the debugger stop at the correct place.
The issue is that when you make the method Async, it runs in a background Task. The Task will catch any exceptions that occur in the code it is executing and re-throw that exception to whatever uses the result of the Task. So for example if you have the following MVC code
Async Function Index() As Task(Of ActionResult)
Dim n as Integer = Await Method1()
Return View()
End Function
Async Function Method1() As Task(Of Integer)
Dim a As Integer = 0
Dim b As Integer = 1 / b
Return b
End Function
The Task executing the code inside of Method1 will catch the exception, and throw it in Index since it is using the result of Method1, then the Task executing Index will catch that exception and re-throw it to the MVC framework code that is using the result of Index, and then the MVC framework handles the exception and displays the error page.
When Just My Code is enabled and methods are executing synchronously the debugger will stop when an exception propagates out of user code with the message that it was "user unhandled". In the case above if an exception propagates from Index to the MVC framework which is not your code, the debugger will stop when JMC is enabled. Since in the case of an asynchronous method the exception is not unhandled but caught by the Task, it does not cross out of user code so disabling Just My code will not make a difference.
The reverse of this is, if an exception occurs in your synchronous method and you have disabled Just My Code, the debugger would not stop anyway, because there is no notion of "User Unhandled" when JMC is disabled and the MVC framework will ultimately handle that exception.

async void, await, and exceptions - why do exceptions thrown after 'await' from the GUI thread require AsyncVoidMethodBuilder for marshaling?

In C# 5.0 In A Nutshell, pg 590, the following example is given:
async void ButtonClick (object sender, RoutedEventArgs args)
{
await Task.Delay(1000);
throw new Exception ("Will this be ignored?");
}
The book states that the Exception will not be caught because the function will imediately return to the message loop at the await line, and when the exception is thrown one second later it will not be caught by the try/catch in the message loop.
The book goes on to state that AsyncVoidMethodBuilder has to encapsulate the continuation within another function so that it can build another try/catch block and forward any caught exceptions to the synchronization context if it is present.
This confuses me because I thought that, since the Task.Delay was being called from the GUI thread, the presence of the syncronization context would cause the continuation from Task.Delay to execute on the GUI thread already. I would have thought that it could therefore continue exeuction directly from the message loop inside a try/catch clause and still get caught without needing to be encapsulated in another function.
What am I missing?
Your understanding is correct; the exception will be re-raised directly on the UI SynchronizationContext and be caught by the message loop. From there it will pass to the UI application-wide handler.
What the book actually says is that the exception cannot be caught after the async method returns, and this is why the AsyncVoidMethodBuilder will re-raise the exception on the appropriate SynchronizationContext.
This is important because an async void method may "leave" its UI context, e.g., by using ConfigureAwait(false). But if an exception happens after that point, it must re-sync to the original SynchronizationContext, not necessarily the context at the point the exception is thrown.

Microsoft.Web.Services3.ResponseProcessingException

I deployed a web service that used WSE 3.0 to a test server. I am getting the cryptic error below. Have any idea what this means and how to fix it? Thanks in advance!
Microsoft.Web.Services3.ResponseProcessingException: WSE910: An error happened during the processing of a response message, and you can find the error in the inner exception. You can also find the response message in the Response property. ---> System.Xml.XmlException: 'wsse' is an undeclared namespace. Line 1, position 97.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg, Int32 lineNo, Int32 linePos)
at System.Xml.XmlTextReaderImpl.LookupNamespace(NodeData node)
at System.Xml.XmlTextReaderImpl.ElementNamespaceLookup()
at System.Xml.XmlTextReaderImpl.ParseAttributes()
at System.Xml.XmlTextReaderImpl.ParseElement()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at Microsoft.Web.Services3.Xml.XmlSkipDTDReader.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at Microsoft.Web.Services3.SoapEnvelope.Load(Stream inStream)
at Microsoft.Web.Services3.Xml.SoapEnvelopeReaderWrapper..ctor(SoapClientMessage message, String messageContentType)
--- End of inner exception stack trace ---
at Microsoft.Web.Services3.Xml.SoapEnvelopeReaderWrapper..ctor(SoapClientMessage message, String messageContentType)
at Microsoft.Web.Services3.WebServicesClientProtocol.GetReaderForMessage(SoapClientMessage message, Int32 bufferSize)
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
I found a solution. Since the dll was working when I called it from a windows client but was failing when called from a web service I suspected that the problem might be permissions related. I set the web service to impersonate a user with sufficient permissions. See http://support.microsoft.com/kb/306158 for how to information. Now it works. Hope this helps someone else, Dan
System.Xml.XmlException: 'wsse' is an undeclared namespace. Line 1, position 97.
Well if this statement is true then you have the wrong namespace. Check out your solution files to make sure they're under the write ns'es.
I got the same problem and it was a problem of date time synchronization between the server and the client. After setting the same time in the client and server, the error was fixed.