Exception error message with incorrect line number - c#

When an exception is thrown in an Asp.Net web page, an error message is displayed with the complete stack trace.
Example below:
Stack Trace:
IndexOutOfRangeException: Index was outside the bounds of the array.
MyNameSpace.SPAPP.ViewDetailsCodeBehind.LoadView() +5112
MyNameSpace.SPAPP.ViewDetailsCodeBehind.Page_Load(Object sender, EventArgs e) +67
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43
System.Web.UI.Control.OnLoad(EventArgs e) +98
... ...
The problem is that the Line number displayed does not correspond to the line in my code that originated the exception.
In the example above, the stack shows line number 5111, yet my code behind .cs file only has 250 lines!
The aspx page is stored in a SharePoint site and the Assembly with the code behind has been deployed to GAC. Also, I've compiled in Debug mode.
Given the settings above, how can I find out what line in my code caused the Exception?
Clarification as pointed out by strelokstrelok:
In Release mode the number in front of the exception is NOT the line of code. Instead it's an offset to the native compiled code, which doesn't have any meaning to humans. More about this here: http://odetocode.com/Blogs/scott/archive/2005/01/24/963.aspx
In debug mode the PDB file will automatically map the native code offset to your .cs line in code and the number displayed WILL be the corresponding line in code.

Those numbers are NOT line numbers. In Release mode the stack trace contains the offsets into the native compiled code instead of line numbers. You can read some more about it here:
http://odetocode.com/Blogs/scott/archive/2005/01/24/963.aspx
The only way to get line numbers in a stack trace is if you built you code in debug mode with the PDB files available.

Your code behind file is not the complete class, it's only a portion that is used when the class as a whole is compiled by ASP.NET. To find what is truly on that line, take a look at the compiled class / assembly using a tool like Reflector.

Maybe the running code is not what you see on your screen. Some mate might have refactored it for you. :)

Related

Xamarin Insights with line numbers

I've released an app using Xamarin and Xamarin Insights. Insights now successfully informs me when the app crashed but I only get a very vague stack trace without line numbers which makes it often impossible to track down the error.
Is there any way I can set up release builds so that crashes will contain stack traces including line numbers?
Thank you,
David
Ref: Why don't I have line numbers in my stack trace?
Why don't I have line numbers in my stack trace?
In .NET you need to have the correct debug information (PDB files) alongside your dlls. Currently on iOS, it's not possible to package them, but we're working on a solution to upload them similar to how dSYMs are sent to us. On other platforms, you can bundle the .pdb files to get line numbers. There are also some known issues with getting line numbers when using async. We'll update the FAQ as we make progress on this.
Although not as useful as a proper stack trace with line numbers, you can use the following snippet to collect some line number and file name information yourself by making a simple wrapper for Insights.Report. This uses built-in .NET Callerattributes to tell you where Report was called.
public static void Report (Exception exp,
ReportSeverity severity= ReportSeverity.Error, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
{ Insights.Report (exp, new Dictionary<string,object> { {"Method",memberName},
{"File Name",sourceFilePath},
{"Line Number",sourceLineNumber},
}, severity);
}

Assuredly simple C# file saving issue

We have a custom built web application built on ASP (2.0 it looks like) using C#. We recently moved it from an IIS6 environment to an IIS7. We have run into an issue where a page set up to view images that had been retrieved via a search is throwing an error. The code takes a copy of the image file and puts it into a work directory renaming the copy to the user's name.
bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
I know that the wwwroot is no longer a valid directory in the path so I changed it to...
bmpList[0].Save("c:\\inetpub\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Saved the file, did and IIS restart and cleared my browser cache and still receive an error...
A generic error occurred in GDI+.
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.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Source Error:
Line 180:
Line 181: //bmpList[0].Save("c:\\pi\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 182: bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 183:
Line 184: for (int a = 1; a < numFiles; a++)
Source File: c:\inetpub\Sitename\SiteApp\View.aspx.cs Line: 182
Stack Trace:
[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +615209
View.Page_PreRender(Object sender, EventArgs e) in c:\inetpub\SiteName\SiteApp\View.aspx.cs:182
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnPreRender(EventArgs e) +11056766
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394
It seems like a fairly straightforward thing but for some reason it is not updating (the path in the error remains exactly the same). What am I missing?
Almost all the time (i.e 99.9999% of the times), when using GDI, 'a generic error occured' means that the directory you are trying to save to doesn't have the proper permissions. Typically, you need to make sure that directory is allowing asp.net to modify files. Did you check the permission on the directory you are trying to save the files to?
So oddly enough the answer is actually as simple as it looks... almost.
Changing...
c:\inetpub\wwwroot\SiteName\Work\
to...
c:\inetpub\SiteName\Work\
worked. Why it was continuing to give me the same error from the browser after I changed the code on the .cs file was that the IP that they had bound to the site still belonged to a previous version of the machine so DNS was routing me over to that box instead. All said it ended up I was on the wrong OSI model layer. I only discovered it when I went to build a test version on the same box and went to unbind the IP from the broken site and bind it to my second test site and I found that the IP I wanted wasn't an option (so it must have been manually entered). Live and learn. Thanks for the input and advise.

Refrences break console app from running on other machines

I've made a console application which inserts data into a MySql backend, and reads the serial number from a hard disk
To do this i had to add References to MySql.Data and to System.Managment.
The way im running it is by copying the Debug directory from visual studio (i think this is the problem) and running the .exe file on the other machine.
When i run the application on another machine the stack trace error is:
PhDD >C:\Users\User\File\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object: reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 49
Updated HDD Stats at28/03/2012 18:46:57
Am i correct in thinking this problem is because of the referencing ?
I've checked the methods by recompiling the same code on the other machine and it works, when the references are added through VS.
Can anyone guide me on how to resolve this issue ?
Cheers for reading.
P.S. i tried adding reference paths (by right clicking on the project, selecting options and then choosing Reference Paths and adding the two dll files)
Line 49
bool conversion = int.TryParse(smartData[1].ToString(), out temp);
After adding a fake int value just to make sure conversion isnt the error the new stack trace error is:
PhDD >C:\Users\bborisov\Dropbox\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 53
Updated HDD Stats at28/03/2012 19:00:24
line 53:
DBHandler.insertData(smartData[0].Trim(),
3, smartData[2], file.getKey());
Put code in to check validity of error situations which may be happening on the client pc but not the development one. You can handle the errors by either throwing an exception or handling it gracefully in a better way.
Here is the code which checks for error situations
if (smartData == null)
throw new Exception("Smart data is null; aborting");
if (smartData.Any() == false)
throw new Exception("Smart data instance is valid but has no elements; aborting");
bool conversion = int.TryParse(smartData[1].ToString(), out temp);

stack trace line numbers are wrong with debug=false and compilerOptions="/debug:pdbonly"

I'm using asp.net 3.5
In web.config, I have debug=false and compilerOptions="/debug:pdbonly" to compile with optimizations and still get line numbers in my stack traces. This works for the most part, but I had a bug in a function in my App_Code folder and the stack trace said the error was on a line that couldn't possibly be an error.
I played with my web.config settings a little bit and found that if I set debug=true and compilerOptions=pdbonly, the stack trace says the error is the line directly after the line with the bug. If I remove the compilerOptions=pdbonly, the stack trace reports the correct line as the error.
//the actual bug (only reported when debug=true and no compiler options set)
var dt = new DateTime(-1,-1,-1);
//
//...lots of non-buggy code between
//
//the bug according to the stack trace when
// debug=false and compilerOptions="/debug:pdbonly"
var ts = TimeSpan.Empty;
Is there a way to make this work right?
Compiler optimizations can affect the line numbering reported in the stack trace. You can set the compiler option /optimze- to disable them, then your stack trace line numbers should be correct.
For example: <compiler compilerOptions="/optimze- /debug:pdbonly"/>

Response.BinaryWrite gives error on Production

I'm using localReport to print PDF (SQL REPORTVIEWER). It works fine on localhost. When I move the application to Production (64 bits windows 2008) it gives me an error. (see below)
I put the renderedbytes in a Session in USERCONTROL and I do window.open('Program1.aspx')...
In page load of Program1.aspx I try to retrieve the Session variable and process....
I think this statement cause the error "Response.BinaryWrite (...) etc".
It works on my local pc (Vista 32bits)...
Can someone please what the errors says? and How can I solve this on production??????
thank you..
USERCONTROL1.ASCX
byte[] renderedBytes;
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Session["report"] = Print.RenderReport(listEnt, Language);
PROGRAM2.ASPX
protected void Page_Load(object sender, EventArgs e)
{
string extension = "PDF";
Response.ContentType = "application/pdf";
// set the MIME type here
Response.AddHeader("content-disposition", "inline: filename=Test." + extension);
Response.BinaryWrite((byte[])Session["report"]);
Response.End();
}
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
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:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.HttpResponse.BinaryWrite(Byte[] buffer) +13
ConfederatieBouw.CustomModules.Controle_InhoudingsPlicht.WebForm1.Page_Load(Object sender, EventArgs e) +191
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsync
Are you running a web farm in production? If so, how are you storing session state? The default is InProc, which means the session will only exist on one server in the farm, and if the follow up request goes to another server, that would explain the issue. The fix this scenario, you will need to setup some sort of session state that can be shared across servers (such as a session state server or SQL Server session state).
Here is some info on the various session state providers:
http://msdn.microsoft.com/en-us/library/ms178586.aspx
Session["report"] is null. You're not setting it to renderBytes in the user control.
Also, it's a really bad idea to store this in a Session. Your binary data has to be serialized/encoded and then deserialized/unencoded whenever you set the Session[] value, which performs poorly. Create a property on the user control to accept the report object and write it to the output stream there, or just do it in the page itself. I'm not sure that it makes sense to put this in a user control instead of a regulat class, anyway.

Categories

Resources