I have a hierarchical model of five object levels. So each object level contains a list of sub-level objects. when I seat a break point and step over with debugger to read the data from the last level object, I get question marks for each property value and the application instantly closes (doesn't crash). If I try to use these property values somewhere else in the application, then I get the stack overflow exception. So these data definitely can't accessed, but I just don't know why. Has anyone had similar problem?
I had a similar problem once.
It was the object ToString() method raising an exception trying to access a null value and making everything crash.
With so little information it's actually hard to tell, just look if it's also your case
Related
There is a simulator. In this simulator we have to pass a corridor. In the corridor there is a door and a puzzle, the solution of which opens this door. As soon as we solve the puzzle, the value of the boolean attribute of the class (something like isOpen) changes to true
This corridor needs to be traversed several times. The corridor itself doesn't change, but the puzzle is random each time.
So, I decided to create a macro application that reaches the puzzle and waits until I solve it
And since the simulation has the boolean variable I need, I was wondering: can I get it, in order to then create a delay in the macro until it is true?
The main problem here is that the two programs are not connected in any way.
I also want to note that I have an understanding that all variables lose their names after compilation, and that variable values subsequently occupy a random place in memory
Also, I have experience with programs like CheatEngine, which is to find the address of a value by its value
But I may just not know all the details, thinking that it's impossible, even if in reality there are ways to do it.
For this reason, I would appreciate it if you could explain to me how this can be done, or, if it is not possible, explain why.
Also, I wouldn't mind a response like "Read this "
I understand that you want to inspect one or more properties of an instance of an object at runtime and this can be achieved by using the so-called Reflection.
The latter provides functionalities that allow you to examine objects at runtime, get their Type, read their properties and invoke their methods. It should be used carefully.
Using reflection you can do
// retrieves the value of the property "NameOfProperty" for the instance of object myobj
bool myFlag = myobj.GetType().GetProperty("NameOfProperty").GetValue(myobj, null);
Trying to find a nasty issue in my code (Unity project).
Basically I create a list; with 10 elements with a custom class. I later use this list, but when I try to access it, all 10 elements became null.
I did something wrong, which is evident, but I can't track down where the elements of the list are set to null; so I was wondering if Visual studio has a way to mark a variable, and can let me run the debug while attached to Unity, so when that list is touched, it will actually stop execution like with a breakpoint, so I can actually see what did call the code that set the elements to null.
Is this possible or do I have to follow my code piece to piece?
OK, I did find somehow a solution.
In visual studio, on the bottom ther eis a panel, which show "error list", "output" and "find symbol". If I place a breakpoint somewhere in the code, that area change, and the area tabs change in "Autos", "Locals", "Threads", "Modules" and "Watch1".
The last tab allow you to type an object in it, which will be then watched while the debugger is on. I did add my object that contain the list that get set to null, and I was able to follow the changes in that object (although it happens only while you are stepping through the code, so it works only if you step through the code from the scripts, in Unity).
Thanks for the help everyone
You could try to use code contracts and place an invariant on the count of elements, and include non null condition for each element as well.
Code contracts engine will re-write your code, and place appropriate validations into every place that modifies state, that could potentially break the invariant.
So, hopefully, you will get an error as soon as your elements become null, so you will be able to see when exactly that happens, and perhaps that will help you to solve the problem.
Use "Find All References" for finding all locations where selected variable/method is using.
With this you can set conditional break point, which will break only if variable is null.
Visual Studio's debugger sometimes gets into a state where it is unable to evaluate expressions. This prevents it from displaying property values. For example, if you're looking at a thread where the top of the stack reports [Managed to Native Transition], and you look at any properties through, say, the this reference in the Locals window, they will all report Cannot evaluate expression because a native frame is on top of the call stack.
You can still inspect fields when the debugger is in this state, because that does not require the ability to execute code. (The reason properties become unavailable is that the debugger actually runs the getter to retrieve the value. It can't do that if the thread you're on is buried in some unmanaged code.)
Unfortunately, the compiler-generated fields that stored the value for C# auto properties don't show up in the debugger. (These are the fields with names like <MyProperty>__BackingField.)
I've tried enabling the "Show raw structure of objects in variables window" setting in the debugger options, but that doesn't appear to help with these hidden fields.
Is there some way to get the debugger to show me fields that the compiler has hidden?
Or alternatively, is there some other way I can discover the value of an auto property's backing field when the usual property evaluation is unavailable?
Note: rewriting the code to use a manually implemented property isn't an option in this case, because the property whose value I want to know is in a Microsoft library. (Specifically, the Open XML SDK.) It's an auto property, and I can't change that.
Also note: simply allowing the code execution to proceed a little so that it can return from the native code transition isn't an option because for some reason, the code has entered some sort of tight busy loop - it's consuming a CPU core, and never returns. (I'm trying to diagnose that problem which is why I'm trying to find out what the object's property values are - I'm trying to get an accurate picture of how it gets into this state.)
One more note: this is not a duplicate of Acessing the backing field in an auto property - my question is very specifically about reading the value while debugging.
Also, in case it's relevant, I'm debugging the code remotely as it runs on an Azure worker role. The problem only occurs in that environment. This rules out native debugging as far as I can tell, so I can't even go and look at the bit of code that's stuck in a loop - I'm having to try an infer what it was up to by looking at the managed code that was running immediately before it disappeared off into that rabbit hole.
Say you have a class with a property you want to watch in a debugger:
public class C
{
// ...
public int I { get; set; }
// ...
}
I believe the following watch expression will work (c is an instance of class C):
c.GetType().GetField("<I>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic).GetValue(c)
Not very convenient, I know, but better than nothing.
I find the C# exceptions very annoying, because they provide so less information. What is the reason for this?
NullReferenceException or KeyNotFoundExceptions are hard to debug and sometimes you donĀ“t get a linenumber in the stacktrace. Why can the exception itself not provide more informations?
For example:
private Dictionary<string, object> Properties = null;
public void Process(string key)
{
var item = this.Properties[key];
....
}
When "Properties"is null I get a NullReferenceException:
"System.NullReferenceException: Object reference not set to an instance to an object"
Why I do not get:
"System.NullReferenceException: Object reference 'Properties' not set to an instance to an object"
This would be more usefull and the CLR does know, which reference is null.
The same when I pass a non existent key e.g. Process("dummy"):
"System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary"
Why I do not get:
"System.Collections.Generic.KeyNotFoundException: The key 'dummy' was not present in the dictionary"
The CLR knows, which key was passed and not found.
I try to debug such errors (which illegal keys are passed) in an productive environment
and made the code more robust like:
private Dictionary<string, object> Properties = null;
public void Process(string key)
{
if (this.Properties != null)
{
if (this.Properties.ContainsKey(key))
{
var item = this.Properties[key];
...
}
else
{
throw new KeyNotFoundException(string.Format("The key '{0}' was not found.", key));
}
}
else
{
throw new NullReferenceException(string.Format("The object 'Properties' is null."));
}
}
But why I have to do this, normally the CLR could tell me what was going wrong in detail. I cannot wrap all codepieces like this to get more informations when an exception happens.
For your KeyNotFoundExceptions, you can create your own dictionary class that throws more meaningful messages (I recommend you try to extend KeyNotFoundException and throw that), or you can use TryGetValue and throw a meaningful exception.
The NullReferenceException one, however, is much more complicated: you assume that the CLR knows that the thing is called Properties, but it's not so simple: consider this.GetSomething(abc).DoSomething(), where GetSomething(abc) returns null. What is the object that's null? It doesn't have a name. And sometimes, especially in Release-optimized code, names for variables or other things that might be null are generated.
You should be debugging with test cases, Asserts, breakpoints, and other debug-mode code, not expecting that you can always get a good enough exception message to debug production code. E.g. even if you know that the key "dummy" was passed in, you might not have enough information to know why that key was bad, or was passed in.
Question: Why do exceptions provide less information than available?
Answer: Possible performance issues.
To produce a nice KeyNotFoundException, you need to call ToString(). This can take considerable time. For example, if I create Dictionary<StringBuilder, int>, failing to find a key would cause a (possibly huge) new memory block to be allocated and filled with data (in .NET 4.5 implementation). Furthermore, this can cause exception message to contain a few megabytes of text.
Question: Why not make exception messages more detailed in Debug mode?
Answer: Inconsistency is bad.
It is extremely difficult to fix bugs which can only be reproduced in Release mode. Getting string representation of keys only in Debug mode will cause diferent behavior:
ToString can throw exceptions.
Lazy programmers can preform checks on exception messages.
Question: But there are suggestions on UserVoice to improve the messages.
Answer: If you like them, vote for them.
I guess that meaningful NullReferenceException in a.b.c.d.e.f.g.h() chain is not top priority. It is annoying, but it has an easy workaround. If you think it is one of the most important problems, then go vote for it. But you may look around and find more interesting stuff to vote for.
In general, code which throws an exception doesn't know what's going to be done with the message. Conceptually, it might have been possible for an exception to include both Message and a DeveloperPrivateMessage properties, and specify that exceptions should refrain from placing in Message any information which could compromise security if revealed to the general public, and code receiving exceptions should refrain from persisting DeveloperPrivateMessage in any fashion which would expose it to untrusted personnel, but that would have complicated things. Instead, code that throws exceptions is expected to simply refrain from including any confidential data. Since dictionaries have no way of knowing whether keys might be used to store confidential data, that implies that keys should not be included in exception messages.
As for NullReferenceException, that's generally caught by a trap handler which may be able to determine that code was trying to execute a mov eax,[esi+8] when the ESI register was zero, but the trap handler would have no way of knowing where the value in ESI came from. If one says meh = Foo.Bar.Boom, and the Bar property returns null only after modifying Foo so that the next call won't return null, then by the time the system tries to access null.Boom, Foo.Bar won't be null. The best the system could do would be to say that "member Bar of some object was null", but that may not be very helpful.
Then you should add special handling to get this information. Remember everything comes at some cost. The more bloated you make exception handling (that shouldn't occur in the first place) - the larger the framework would have to be for every single case like this.
You really should consider these "Last chance exceptions" since you should never see them if coded correctly. Between the exception message and the stack trace that is provided - that should be enough information for your.
The responsibility of checking for null or if the key is missing is on you, the developer. The reason for this is optimization; if the default exceptions were more detailed like you would like, then the compiler would not be able to optimize as efficiently.
It's a trade-off. Adding null checks can be annoying, but it's how the language is designed.
I've seen something like this too many times:
try
{
//something
}
catch (FileNotFoundException e)
{
e.Data.Clear(); // <- WTF?
}
and as far as I know this is useless voodoo, but please correct me if I'm wrong.
Exceptions in .Net allow you to associate arbitrary data with them by putting it into the Data member of Exception. It's essentially a weakly typed dictionary which makes minimal checks to ensure the stored information is serializable.
This particular function is simply clearing out all of the custom associated data. Why is a bit of a mystery since the developer left no comments.
As to whether or not this is useless. In all likely hood yes. The one specific case where this could be useful is if the creator of the FileNotFoundException both added an object reference to the Data bag and is itself holding onto a reference of the FileNotFoundException instance. In that specific case calling Clear could prevent a memory leak by removing a reference to an object which should be short lived. I find it very unlikely that this is the case though. My instinct would be to file a bug / delete it .