128

I'm trying to investigate a bug in a crash dump (so I can not change the code). I have a really complicated object (thousands of lines in the serialized representation) and its state is inconsistent. To investigate its state the Visual Studio debugger view is useless. But the object has a data contract. I'd like to serialize it and then use my favorite text editor to navigate across the object. Is it possible to do the from the debugger?

Phuc Thai
  • 718
  • 7
  • 17
xvorsx
  • 2,322
  • 2
  • 18
  • 19
  • Note, that if you have some custom container class, or some other class what you want to see many times during debug, but the IntelliSense and QuickView cannot figure it out, you can write an extension for VS which helps to show your custom class in debug. – Csaba Toth Sep 13 '13 at 20:34
  • Many good techniques can also be found [here] (http://stackoverflow.com/questions/360277/what-is-the-best-way-to-dump-entire-objects-to-a-log-in-c) – Josh Jul 01 '15 at 19:43

12 Answers12

239

With any luck you have Json.Net in you appdomain already. In which case pop this into your Immediate window:

Newtonsoft.Json.JsonConvert.SerializeObject(someVariable)

mcintyre321
  • 12,996
  • 8
  • 66
  • 103
  • 33
    Wish I could upvote this again, especially compared to the other answers. (Sorry, but I don't need to see another line of XML in my career.) – yzorg Nov 21 '14 at 15:43
  • 1
    After a very long test debug session an exception happened in my program before it could write out thousands of test results to a file, I was on a breakpoint where the exception occurred and could still inspect the results collection. This tip saved me a lot of time! – HAL9000 Dec 01 '15 at 03:10
  • 1
    You might need to actually use Json.Net somewhere else too so that it is loaded when you try to use it in the Immediate window (as opposed to just adding the reference). – Evan Feb 17 '17 at 22:25
  • 1
    I had to add the Newtonsoft.Json package using Nuget, and also add a line of code in the method that I had the breakpoint in to create a dummy Newtonsoft.Json.JsonArrayAttribute() class to get it to work. A most excellent solution! – Richard Moore Jan 17 '18 at 19:47
  • And if you don't have it then you can you load it via the immediate window, see https://stackoverflow.com/a/29834931 for details – yoel halb Jan 28 '20 at 19:30
  • 2
    This is a great answer. I use it with just a tiny change to save me a trip to the beautifier. Newtonsoft.Json.JsonConvert.SerializeObject(someVariable, Newtonsoft.Json.Formatting.Indented) – Jamie Feb 01 '20 at 03:27
  • this answer lets to add this line in watch window itself. very useful, no need to extensions. – Satyam Naolekar Nov 04 '20 at 11:08
  • This is by far the best answer. – David Klempfner Jan 11 '21 at 01:31
  • HOW HAVE I NEVER SEEN THE IMMEDIATE WINDOW??? This is amazing. – noelicus Feb 08 '21 at 11:32
96

Some time ago I wrote this one-liner serializing an object to a file on the disk. Copy/paste it to your Immediate window, and replace obj (it's referenced twice) with your object. It'll save a text.xml file to c:\temp, change it to your liking.

(new System.Xml.Serialization.XmlSerializer(obj.GetType())).Serialize(new System.IO.StreamWriter(@"c:\temp\text.xml"), obj)

Don't expect any magic though, if the object cannot be serialized, it'll throw an exception.

Wyck
  • 10,311
  • 6
  • 39
  • 60
Alexey
  • 1,299
  • 11
  • 10
  • 4
    This worked for me in the immediate window. upvoted, – Pankaj Kumar Feb 16 '16 at 13:40
  • 1
    when I use this on the VS 2015 immediate window, I get this 'error': "Evaluation of native methods in this context is not supported." Ideas? – Vetras Oct 14 '16 at 10:25
  • When I run it, I get the following message: `identifier "System" is undefined` – Rasoul Aug 29 '17 at 08:00
  • Had an old VB.NET project, had to put it like this otherwise I was getting an error about expression syntax, if anyone needs: new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(New System.IO.StreamWriter("C:\temp\temp.txt"), obj) – Liquid Core Jan 16 '18 at 16:26
  • This is spectacular. I had to use a different directory due to write permissions, but it worked like a charm. Import into Excel and it's even pretty. – R-D Mar 19 '19 at 21:18
39

Here is a Visual Studio extension which will let you do exactly that:

https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f

You can output to JSON, XML or C#

Omar Elabd
  • 1,914
  • 1
  • 18
  • 23
  • 4
    That link seems to be broken, but [here](https://github.com/OmarElabd/ObjectExporter) is the github project and you can find it if you search for "Object Exporter" in the "Extensions and Updates..." dialog in Visual Studio. Great extension btw! – Niklas Söderberg May 18 '15 at 06:35
  • 2
    Thank you @Omar The idea is perfect. But it takes too long time and freeze in some cases – Wahid Bitar Feb 22 '17 at 11:47
  • 1
    Agreed with @WahidBitar - Great concept - perfect for setting up unit test data, but the extension seems quite buggy, and takes Visual Studio with it when it crashes! – Dib Mar 22 '18 at 13:47
  • This is really a very useful tool. – Ashutosh Singh Jul 19 '18 at 18:29
  • 7
    [Version for Visual Studio 2019](https://github.com/OmarElabd/ObjectExporter/issues/84#issuecomment-540138520) – MaciejLisCK Sep 24 '20 at 13:57
  • 1
    @OmarElabd, would you mind publishing this for VS 2019 and @022? – FoxDeploy Nov 01 '21 at 13:50
21

Since .NET Core 3.0 you can use System.Text.Json:

System.Text.Json.JsonSerializer.Serialize(obj)
13

Use this in Visual Studio's "Immediate" window, replacing c:\directory\file.json with the full path to the file to which you'd like to write the JSON and myObject with your variable to serialise:

System.IO.File.WriteAllText(@"c:\directory\file.json", Newtonsoft.Json.JsonConvert.SerializeObject(myObject))
Chris Peacock
  • 4,107
  • 3
  • 26
  • 24
3

It might be possible to use the immediate window to serialize it and then copy the content to your favorite editor.

Another option is to override the ToString() method and call it while in debug mode.

You can also write the contents out to a file shortly before the crash, or wrap the code into a try/catch and write the file then. I'm assuming you can identify when it's crashing.

Sergey
  • 1,608
  • 1
  • 27
  • 40
Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
  • Thanks, I tried same from Watch window, but it told me "The function evaluation requires all threads to run." Immediate window solve it – xvorsx Sep 13 '13 at 20:04
3

I have an extension method I use:

public static void ToSerializedObjectForDebugging(this object o, FileInfo saveTo)
{
    Type t = o.GetType();
    XmlSerializer s = new XmlSerializer(t);
    using (FileStream fs = saveTo.Create())
    {
        s.Serialize(fs, o);
    }
}

I overload it with a string for saveTo and call it from the immediate window:

public static void ToSerializedObjectForDebugging(this object o, string saveTo)
{
    ToSerializedObjectForDebugging(o, new FileInfo(saveTo));
}
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
2

In case you have a circular reference, run this in the immediate Window:

Newtonsoft.Json.JsonConvert.SerializeObject(app, Newtonsoft.Json.Formatting.Indented,
new Newtonsoft.Json.JsonSerializerSettings
{
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize
});
SQL Police
  • 4,127
  • 1
  • 25
  • 54
InGeek
  • 2,532
  • 2
  • 26
  • 36
  • 1
    It's a nice sample, containing full namespaces is a big advantage. Changing "ReferenceLoopHandling.Serialize" as "ReferenceLoopHandling.Ignore" could be a faster and "errorless" alternative for many cases. – Furkan Ekinci Dec 07 '22 at 08:38
2

I've been using ObjectDumper.Net.

It works well, especially if you have live unit testing. I can easily view a variable's value in the console when a test runs, saving me from debugging manually.

This may help if you're using XUnit.

DharmaTurtle
  • 6,858
  • 6
  • 38
  • 52
1

A variation on the answer from Omar Elabd --

It's not free, but there's a free trial for OzCode
(https://marketplace.visualstudio.com/items?itemName=CodeValueLtd.OzCode).

There's built-in exporting to JSON within the context/hover menu there, and it works a bit better than the Object Export extension (the trade-off for it not being free).

http://o.oz-code.com/features#export (demo)

I know this is a few years after the fact, but I'm leaving an answer here because this worked for me, and someone else may find it useful.

Michael Armes
  • 1,056
  • 2
  • 17
  • 31
1

Object Dumper is a free and open source extension for Visual Studio and Visual Studio Code.

"Dump as" commands are available via context menu in the Code and Immediate windows.

It's exporting objects to:

  • C# object initialization code,
  • JSON,
  • Visual Basic object initialization code,
  • XML,
  • YAML.

I believe that combined with the Diff tool it can be helpful.

I'm the author of this tool.

Yevhen Cherkes
  • 626
  • 7
  • 10
0

A variation on Alexey's answer. Slightly more complicated but doesn't involve writing to a text file:

1) In the Immediate Window enter:

System.IO.StringWriter stringWriter = new System.IO.StringWriter();  

2) In the Watch Window enter two watches:

a.  stringWriter

b.  new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(stringWriter, obj) 

After you enter the second watch (the Serialize one) the stringWriter watch value will be set to obj serialized to XML. Copy and paste it. Note that the XML will be enclosed in curly braces, {...}, so you'll need to remove them if you want to use the XML for anything.

Simon Elms
  • 17,832
  • 21
  • 87
  • 103