I am responsible for an F# WPF application. It emails me when an unhandled exception occurs. Most of the time, I'm able to identify the source of the exception from the error message and stack trace. However, I occasionally get a message like the following, which does not include any of my code in the stack trace.
Summary:
Object reference not set to an instance of an object.
--------------
Details:
System.NullReferenceException:
Object reference not set to an instance of an object.
at Microsoft.FSharp.Control.CancellationTokenOps.Start#1234-1.Invoke(Exception e)
at <StartupCode$FSharp-Core>.$Control.loop#435-40(Trampoline this, FSharpFunc`2 action)
at Microsoft.FSharp.Control.Trampoline.ExecuteAction(FSharpFunc`2 firstAction)
at Microsoft.FSharp.Control.TrampolineHolder.Protect(FSharpFunc`2 firstAction)
at <StartupCode$FSharp-Core>.$Control.-ctor#520-1.Invoke(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
What clues are available in this stack trace that might help me identify the source of this exception?
For example, I'm assuming the original exception is being thrown within an async computation. (The majority of my async code is based on F# async blocks.) Could my NullReferenceException have occurred anywhere in an async block? I notice that the exception occurred within a Start() method. Or is it? That Start() method takes an Exception instance so perhaps the exception was thrown before that. Does that tell me anything? I wonder if someone is familiar enough with the Microsoft.FSharp.Control.Trampoline to point me in the right direction.
By the way, in my error handling code, I am careful about checking all the InnerExceptions and handling AggregateExceptions. So I think this is all the information available in the Exception instance, but I could be wrong.
I did a quick test. The following Console program generates the identical stack trace.
[<EntryPoint>]
let main argv =
async { printfn "Inside async block."
let o = null
o.GetType() |> ignore
} |> Async.Start
System.Console.ReadKey(true) |> ignore
0 // return an integer exit code
That tells me the following:
The mystery exception is happening within an async block.
It could occur anywhere in the async block.
The only way to diagnose is to improve the error handling around async blocks (perhaps with Async.Catch) and redeploy a new version of the application and wait for it to happen again.
Related
I am programming a fullstack application which is used on festivals to monitor their inventory on bars (how many bottles of gin they have for instance). It allows for creating an transfer request to get more stuff to specific bar and looking up those requests. The problem arises when the connection is slow enough to cause a timeout (by my testing at 1KB/s upload/download throttle it took approx 10s) but still send the data to the API.
My method which handles writing the data to the database looks like this:
public IActionResult WriteStorageTransfer([FromBody] StorageTransfer transfer)
{
Console.WriteLine("Started the execution of method");
var transferId = database.CreateNewDoc(transfer);
foreach (var item in transfer.items)
{
var sql = #$"insert into sklpohyb(idsklkarta, iddoc, datum, pohyb, typp, cenamj, idakce, idbar, idpackage, isinbaseunit)
values ({item.id}, {transferId}, current_timestamp, {packMj}, {transfer.typ}, {item.prodejnicena}, {transfer.idakce}, {transfer.idbar}, case when {pack.idbaleni} = -1 then NULL else {pack.idbaleni} end, {pack.isinbaseunit})";
database.ExecuteQueryAsTransmitter(sql);
}
return Ok(transferId); // transferId is then used by frontend to display the created transfer request.
}
This would be all nice and all, but the frontend appears to send the data to the API, API processes it and writes it to the database, but then timeout occurs on the HttpRequest, crashing the method, thus never returning a HttpResponse to the frontend (or returning code 0: 'Unknown error').
The exception thrown by the API:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.IO.IOException: The request stream was aborted.
---> Microsoft.AspNetCore.Connections.ConnectionAbortedException: The HTTP/2 connection faulted.
--- End of inner exception stack trace ---
at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
at System.IO.Pipelines.Pipe.GetReadAsyncResult()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2MessageBody.ReadAsync(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 destination, CancellationToken cancellationToken)
at System.Text.Json.JsonSerializer.ReadFromStreamAsync(Stream utf8Json, ReadBufferState bufferState, CancellationToken cancellationToken)
at System.Text.Json.JsonSerializer.ReadAllAsync[TValue](Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object valu
e, Object container)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location ---
The size of the JSON sent to API is usually ~10 KB, nothing too serious like 100MB so I don't think the size is the problem
This leaves the frontend hanging and the users tend to click the button again, possibly writing multiple duplicates to the database as he does not know if the invoice has been processed or if there is an error in the app.
Interestingly the Console.Write("Started execution of the method") does not get triggered as I do not see it in the console window, yet the data gets written into the database after manually checking it.
Perfect thing would be if I could notify the user that something went wrong in the creation of the transfer request, and prevented the creation of it in the database. I tried using try catch block targeted on IOException
Thanks a lot in advance, anything goes at this point
The problem arises when the connection is slow enough to cause a timeout but still send the data to the API.
Back to the drawing board (or time to give us more details). If your POS app (which I assume this is) wants to report a sale to the back-end, why would the user have to wait for this? And why would the user be able to report one sale twice?
Instead have the client generate a unique transaction ID locally and store them in local storage, and (after each sale, and periodically, but most importantly: on the background) have the client try to synchronize their transactions to the server. The server can then reject duplicate transactions so it won't record the same sale twice, and your app can handle periods without or with spotty internet access.
As for your error: the timeout probably is a minute or so, which may be too long for this use case anyway. The client will ultimately throw an exception if it doesn't get an HTTP response, but do you want your bar person to wait on the POS for a minute? They are going to call it a POS then.
We have a website in production (ASP.NET v4), where on the login page we are occasionally catching the exception 'Input string was not in a correct format'.
This is being caught within Application_Error which logs its details
The exception is taken from Server.GetLastError().GetBaseException(). However, the stack trace is only reported as the following:
Stack Trace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String Value)
The web page doesn't have any need to try and convert input (as it only takes a username), nor does it seem to call any VB functions which do.
How can I track down this intermittent error?
ServiceStack version 5.0.2
I wondered if anyone could give me a pointer to a possible cause of the error shown in the stack trace below. (I am a junior developer, so I am very new to all this.)
We have an ASP.net MVC application which has some ServiceStack.Mvc integration in it. (I suspect we are using ServiceStack's auth provider functionality to handle authentication on MVC controller action requests).
Today we witnessed errors appearing when trying to login to our Web Application. Below is the stack trace of one of the errors that appeared.
The Index action on "MyController" has an 'Authenticate' attribute on it.
[Authenticate]
public class MyController : ServiceStackController<AuthUserSession>
All I can deduct from the stack trace is that after the MVC controller action is invoked, the service stack ServiceRunner tries to execute a service (I have no idea which one) and there is somekind of null reference within the execute method which is throwing an exception.
I wondered if Myths or anyone else had ever seen this before, or could shed any light whatsoever on what service the service runner may have been trying to execute or any information on a possible cause.
The issue disappeared after the web server was rebooted
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
Stack trace: at ServiceStack.DtoUtils.CreateErrorResponse(Object request, Exception ex)
at ServiceStack.Host.ServiceRunner`1.HandleException(IRequest request, TRequest requestDto, Exception ex)
at ServiceStack.Host.ServiceRunner`1.Execute(IRequest request, Object instance, TRequest requestDto)
at ServiceStack.Host.ServiceRunner`1.Process(IRequest requestContext, Object instance, Object request)
at ServiceStack.Host.ServiceExec`1.Execute(IRequest request, Object instance, Object requestDto, String requestName)
at ServiceStack.Host.ServiceRequestExec`2.Execute(IRequest requestContext, Object instance, Object request)
at ServiceStack.Host.ServiceController.ManagedServiceExec(ServiceExecFn serviceExec, IService service, IRequest request, Object requestDto)
at ServiceStack.Host.ServiceController.<>c__DisplayClass36_0.<RegisterServiceExecutor>b__0(IRequest req, Object dto)
at ServiceStack.Host.ServiceController.Execute(Object requestDto, IRequest req)
at ServiceStack.InProcessServiceGateway.ExecSync[TResponse](Object request)
at ServiceStack.InProcessServiceGateway.Send[TResponse](Object requestDto)
at MyApplication.Controllers.MyController.Index()
I've not seen this error before, but the StackTrace originated from your MyController.Index() Action.
The ServiceStackController doesn't use the Gateway, neither does the ExecuteServiceStackFilters which executes the AuthenticateAttribute on your MVC Controller. So I'd say it's something in your MyController.Index() implementation that's causing it.
I am new to Biztalk, I have consumed a WCF service and created my own schema and orchestration.
Then published the WCF service, all things went well , but when I am running the published service from SOAP UI I am getting this exception in Biztalk server administrator
xlang/s engine event log entry: Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'BizTalkEmployeeInfo.BizTalk_Orchestration1(8e85552e-b611-e6a6-655f-b3b58002a88d)'.
The service instance will remain suspended until administratively resumed or terminated.
If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
InstanceId: eb2b7522-db03-40f0-9cfa-28509fea03b0
Shape name:
ShapeId:
Exception thrown from: segment -1, progress -1
Inner exception: Received unexpected message type 'http://schemas.xmlsoap.org/soap/envelope/#Fault' does not match expected type 'http://tempuri.org/#EmployeeDetailsFormattedResponse'.
Exception type: UnexpectedMessageTypeException
Source: Microsoft.XLANGs.Engine
Target Site: Void VerifyMessage(Microsoft.XLANGs.Core.Envelope, System.String, Microsoft.XLANGs.Core.Context, Microsoft.XLANGs.Core.OperationInfo)
The following is a stack trace that identifies the location where the exception occured at Microsoft.XLANGs.Core.PortBinding.VerifyMessage(Envelope env, String typeName, Context cxt, OperationInfo op)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBinding.VerifyMessage(Envelope env, String typeName, Context cxt, OperationInfo op)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXLogicalPortBinding.VerifyMessage(Envelope env, String typeName, Context cxt, OperationInfo op)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBase.VerifyTransport(Envelope env, Int32 operationId, Context ctx)
at Microsoft.XLANGs.Core.Subscription.Receive(Segment s, Context ctx, Envelope& env, Boolean topOnly)
at Microsoft.XLANGs.Core.PortBase.GetMessageId(Subscription subscription, Segment currentSegment, Context cxt, Envelope& env, CachedObject location)
at BizTalkEmployeeInfo.BizTalk_Orchestration1.segment1(StopConditions stopOn)
at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)
Can someone help please here.
Your web service throws an exception - that is a message of the http://schemas.xmlsoap.org/soap/envelope/#Fault type, but BizTalk messaging/orchestration engine has no idea what to do with it. You need to configure your send port and orchestration to deal with the soap exceptions. See here for more details:
https://blogs.msdn.microsoft.com/biztalknotes/2013/02/12/how-to-handle-fault-message-in-biztalk-server/
A very handy way to debug these is to use fiddler. In your send port set fiddler to be the proxy. The communication from biztalk goes through, and is logged by, fiddler when it acts as a proxy. You can easily view the response that the BizTalk failure is hiding.
Before asking a separate question I've done lots of googling about it and added a comment in the already existing stackoverflow question.
I have a SignalR Hub (tried both v. 1.1.3 and 2.0.0-rc) in my server with the below code:
[HubName("TestHub")]
public class TestHub : Hub
{
[Authorize]
public void TestMethod(string test)
{
//some stuff here
Clients.Caller.NotifyOnTestCompleted();
}
}
The problem persists if I remove the Authorize attribute.
And in my iOS client I try to call it with the below code:
SRHubConnection *hubConnection = [SRHubConnection connectionWithURL:_baseURL];
SRHubProxy *hubProxy = [hubConnection createHubProxy:#"TestHub"];
[hubProxy on:#"NotifyOnTestCompleted" perform:self selector:#selector(stopConnection)];
hubConnection.started = ^{
[hubProxy invoke:#"TestMethod" withArgs:#[#"test"]];
};
//received, error handling
[hubConnection start];
When the app starts the user is not logged in and there is no open SignalR connection. The users logs in by calling a Login service in the server which makes use of WebSecurity.Login method. If the login service returns success I then make the above call to SignalR Hub and I get the server error 500 with description "The ConnectionId is in the incorrect format.".
The full server stacktrace is the following:
Exception information:
Exception type: InvalidOperationException
Exception message: The ConnectionId is in the incorrect format.
at Microsoft.AspNet.SignalR.PersistentConnection.GetConnectionId(HostContext context, String connectionToken)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment)
at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request information:
Request URL: http://myserverip/signalr/signalr/connect?transport=webSockets&connectionToken=axJs EQMZxpmUopL36owSUkdhNs85E0fyB2XvV5R5znZfXYI/CiPbTRQ3kASc3 mq60cLkZU7coYo1P fbC0U1LR2rI6WIvCNIMOmv/mHut/Unt9mX3XFkQb053DmWgCan5zHA==&connectionData=[{"Name":"testhub"}]
Request path: /signalr/signalr/connect
User host address:
User:
Is authenticated: False
Authentication Type:
Thread account name: IIS APPPOOL\DefaultAppPool
Thread information:
Thread ID: 14
Thread account name: IIS APPPOOL\DefaultAppPool
Is impersonating: True
Stack trace: at Microsoft.AspNet.SignalR.PersistentConnection.GetConnectionId(HostContext context, String connectionToken)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context)
at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment)
at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I understand this is some kind of authentication and user identity mismatching but up to now I have found no way of solving it. All other questions suggest stoping the opened connection when the user identity changes but as I mentioned above I have no open connection before the user logs in successfully.
Any help would be much appreciated.
Thank you.
Here is what I found, I am trying to create a Flex/AS3 client for signalR. It only uses websockets but for my work I control both ends of the system so I know my backend will support it.
Anyway, the trick to getting around this for me was encoding the connectionToken. The server side signalR code is trying to parse out the connection ID from the token. When you get the token from the server it comes as part of the negotiation handshake, when you try to send it back you must make sure to remove the "/" and "+" symbols and encode them as %2F and %2B respectively. In AS3 the escape or other equivalent url encoding methods left the slash presumably because it is a valid url character, but since the value is passed in the querystring it needs to be encoded.
Once I did this I stopped getting a server 500 error (The ConnectionId is in the incorrect format) and the socket opened and I received messages.
Hope this helps.
Jason
Looks like you are using https://github.com/DyKnow/SignalR-ObjC be sure to use the feature-2.0.0.beta1 branch until it is pulled into master.
We had a similar problem.
Turning off the crypto functions for the connection tokens fixed it.
Sorry I can't help further, as I'm working the iOS end not the .net end.