How to identify the line nr. where the exception has occured and show a piece of code around the exception?
I would like to implement a custom exception handler page which would display the stack trace, and I'm looking for the easiest way to accomplish the above. While most of the information is available through the Exception object, the source code information is not available there.
You need to use the StackTrace class.
For example:
var st = new StackTrace(exception, true);
var sourceFrame = Enumerable.Range(0, st.FrameCount).FirstOrDefault(i => st.GetFrame(i).GetFileLineNumber() > 0);
This code will find the first frame which has line number information available, or null, if none of the frames have line numbers.
You can then call the methods of the StackFrame object to get more information. Note that source information is usually only available in debug builds.
Related
the mAuth and mCallbacks object is giving red-font-error. How to resolve this?
Do I need to make the object outside of the codeblock?
here is the code block in which the red-font errors are showing up:
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
If you keep following the documentation on implementing phone authentication on Android, you'll see that the mCallbacks object is defined in the next step, right under the code you have above. It is explained as:
When you call PhoneAuthProvider.verifyPhoneNumber, you must also provide an instance ofOnVerificationStateChangedCallbacks, which contains implementations of the callback functions that handle the results of the request.
Under that explanation is a code sample, and then an explanation of each individual callback and its purpose.
I recommend reading the entire page first, so that you understand the complete flow, and only then starting to copy/paste the relevant code snippets.
I am working on an asp.net mvc-5 web application and i am using ap.net version 4.5.
Inside my web application I am executing some power-shell scripts to get some hardware info about some servers and VMs, and get back the results inside my code, as follows:
var shell = PowerShell.Create();
string PsCmd =
"add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '"
+ vCenterName.Trim() + "';$vCenterAdmin = '" + vCenterUsername.Trim()
+ "' ;$vCenterPassword = '" + vCenterPassword + "';"
+ System.Environment.NewLine;
PsCmd += "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;
PsCmd += "Get-VMHost " + System.Environment.NewLine;
shell.Commands.AddScript(PsCmd);
dynamic results = shell.Invoke();
var temp_result = results[0].BaseObject == null ? results[0] : results[0].BaseObject;
var otherIdentityInfo = temp_result.ExtensionData.Hardware.SystemInfo.OtherIdentifyingInfo;
now currently when i run this inside my Visual Studio 2012 professional , i will get the following exception :-
System.StackOverflowException was unhandled
An unhandled exception of type 'System.StackOverflowException' occurred in VimService55.XmlSerializers.dll
on
var otherIdentityInfo = temp_result.ExtensionData.Hardware.SystemInfo.OtherIdentifyingInfo;
So can anyone adivce on this? I know that in general a "StackOverflowException" exception is related to the fact that too many data exists inside the stack, but in my case I do not have control over this data as I am scanning VM server information. So can anyone advice on this please?
EDIT
I am not sure what is really raising the error (the debugger OR the code)? because when i try calling this code on the hosted application inside IIS (not inside Visual Studio) I will get null value for the otherIdentityInfo variable, rather than getting an exception. However, when i debug the code inside Visual Studio using Autos i will get the exception, so as #JmaesP mentioned the exception is being raised by the debugger, but not sure how i can debug this value to see why i am getting null??
A stack overflow exception from an XML serializer might indicate an issue with one of you serializable types. If the type declaration by itself is somewhat recursice, the default XML serializer will end up in inifite recursion. Consider this example:
[Serializable()]
public class Foo : IEnumerable<Foo>
{
public Foo()
{
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
public IEnumerator<Foo> GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(Foo item)
{
throw new NotImplementedException();
}
}
The default XML serializer first tries to figure out how to (de-)serialize an instance of Foo, then it tries to figure out how to (de-)serialize an IEnumerable<Foo>, and to do that it tries to figure out how to (de-)serialize a Foo — resulting in infinite recursion. Typically, a solution to this would to use a custom serializer as described here.
However, in your case the serializer is provided by the third-party component. The exception likely occurs during the serialization/deserialization that is happening when objects are passed from the PowerShell session to your process. So what you could to is to change the object that is returned from the PowerShell script. Instead of returning a VMHost object (requiring to serialize the entire object tree of the VMHost object), you could just return the SystemInfo or OtherIdentifyingInfo.
Large recursions can cause out-of-stack errors.
Your problem is likely that your program is attempting to consume an infinite amount /very large amount of stack.
Without seeing your stack trace, it's a bit difficult to provide a definitive answer, but I think sticking to the basics leads me to believe the source of your StackOverflow is the PsCmd += which continuously adding the data into the stack and results in StackOverflowException.
You can increase the stack size by using the below code:
Editbin.exe /Stack:14000000 "$(TargetDir)MyProject.exe"
Have you analyzed your code to find out that how deep your recursion goes on average? Does it always hit a StackOverflow? Try hardcoding a single entity and see the result.
Since 64 bit code can up more stack space than equivalent 32 bit code, large recursions can cause out-of-stack errors to occur earlier.
In that case, making the stack larger is not a good idea either. Instead we should find the deeply recursive algorithm and make it into an iterative one.
For Stack-Trace;
You can read up this property: Environment.StackTrace.
If the stacktrace exceded a specific threshold that you preset, you can return the function.
Note: From .Net 2.0 and above, you cannot get a StackOverflowException object using a try-catch block.
Let me know if at all it helps you.
I'm having a strange experience with moq/mocking.
Im trying to mock the data going into a method so that i dont have to have adatabase available at test time.
So im loading in some data ive previously seralised.
Loading it into a dataTable, then creating a data reader from there, because my business layer method expects a data reader.
Then creating a mock for my data layer. and setting the return value for a particular method to my new datareader.
I am then setting (injecting) my mock data layer into my business layer so it can do the work of returning the data when the time comes..
var dataTable = DataSerialisation.GetDataTable("C:\\data.xml");
IDataReader reader = dataTable.CreateDataReader();
var mock = new Mock<IRetailerDal>();
mock.Setup(x => x.ReadRetailerDetails("00")).Returns(reader);
retailersBusinessLayer.RetailerDal = mock.Object;
var r = retailersBusinessLayer.GetRetailerDetail("00");
Now.. when the "GetRetailerDetail" is called is basically gets to "while(data.Read())" and crashes out but only sometimes.
I get the exception:
System.InvalidOperationException : DataTableReader is invalid for current DataTable 'Table1'.
Othertimes it move past that and can read some columns data, but other columns dont exist. (which must be to do with my serialisation method)
Well, this isnt exactly a satisfactory answer, but the code works now..
its similar to this.. in that no reason was found.
here
Anyway... as stated above the issue was ocuring inside my GetRetailerDetail method, where the code hits while(data.Read()) it throws the error..
The fix.. change the name of the data reader variable.. i.e. its was "data" and its now "data2".. thats all i changed.
For debugging purposes I store exception's stack trace to log file in my ASP.NET application. But in most of cases it contains a looot of redundant information: stack trace of ASP.NET's core before my routines and System calls after.
Is there any way to trim this unrelevant, not in my assembly information from StackTrace object I create from Exception? I'm interested only in chunk of frames inside of whole trace.
Thank you.
Denis.
One way would be to create a StackTrace object, get the frames from it and loop through them, checking whether each frame was created for a method in one of your assemblies.
I don't think you really should do this though. You chould rather focus on getting less error messages in your logs than shortening them (which will likely make things more difficult to debug).
I ended up parsing ex.ToString() and removing unwanted entries with Regex. It's not a universal solution, you have to specify each excluded entry manually, but it helps reduce size of logs and improve log readability. It's also fairly maintainable. Something like this:
private static string TrimStackTrace(Exception ex)
{
var sb = new StringBuilder();
string[] lines = ex.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
var excludeRegex = new Regex(#"^\s+at (Microsoft.AspNetCore|lambda_)");
foreach (string line in lines)
{
if (excludeRegex.IsMatch(line))
{
continue;
}
sb.AppendLine(line);
}
return sb.ToString();
}
You can of course make excluded entries part of your app config.
I'm getting error while running a game I created with flex.
I know there has been some question about this, but my case is quite weird. I created a simple typing game that is running OK on my computer, but when I tried to deploy it online to facebook, I got those errors. I used code from the tutorial from adobe here http://www.adobe.com/devnet/facebook/articles/flex_fbgraph_pt4.html to deploy my flex game to facebook
This is the error message:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FacebookUserStatusWeb/init()
at FacebookUserStatusWeb/___FacebookUserStatusWeb_Application1_creationComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()
at mx.core::UIComponent/set initialized()
at mx.managers::LayoutManager/doPhasedInstantiation()
at mx.managers::LayoutManager/doPhasedInstantiationCallback()
And here is snippet of the init() function:
protected var text1:String="Text to be typed"; //hard-coded temporarily
protected const TIMER_INTERVAL:int = 10;
protected var t:Timer = new Timer(TIMER_INTERVAL);
protected var topURL:String=ExternalInterface.call('top.location.toString');
protected function init():void
{
t.addEventListener(TimerEvent.TIMER, updateTimer);
ProblemText.text = new String(text1);
Facebook.init("<my app id>",loginHandler);
currentState = (topURL) ? "loggedout": "loggedoutonfacebook";
}
Some notes:
1.my app id is my facebook app id which I prefer not to show
2.ProblemText is a richtext which I placed the paragraph to be typed by the player.
3.I have deleted the method Application1_creationComplete() but it still appears at the error listing
And also I am curious about the errors other than the first two. What do they mean?
Ah, and if it is helpful, I can post some more of the code
First: You're only seeing one error. Everything you see below the #1009 error is your stack trace, not additional errors.
The stack trace basically tells you the series of things that happened prior to the error occurring, with the most recent at the top. This is useful because often things which happen prior to the actual error you see will contribute to said error.
Second: The null object reference is occurring because something in your init() function tried to access a property in an object that doesn't exist, or an object that doesn't exist. One (slightly messy but effective) way to debug this would be to drop some trace statements in the code to see how far it gets before barfing with the error -- the idea being to isolate the specific line that's causing the problem. Once you've done that, you need to work backwards to figure out why the object or property you're trying to use is null. It could be something simple, like a typo, or it could be more complex. You'll have to sleuth it out, one way or another =)
Good luck!
Finally got the bug. Just in case people have the same case with me, what exactly happened is at my computer I simulated the game with just one state, but when I'm deploying to facebook I have several states (loggedin,loggedout,etc). In the init() I tried to access ProblemText Label that is not present in the current state.