How to Use the Linqpad Dump() Extension Method in Visual Studio

How do I use the LINQPad Dump() extension method in Visual Studio?

Look here (your path may vary):

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper

LINQPad in Visual Studio

It's not a dll for LINQPad - you need to reference the LINQPad.exe itself.

Right-click your project in Visual Studio -> Add Reference -> Browse to the exe binary file location, typically found in its install directory C:\Program Files\LINQPad\ --> select LINQPad.exe.

Once done, then you can add a "using directive" for it in your file:

using System.Diagnostics;
using System.IO;
using LINQPad;

The method LINQPad.Util.CreateXhtmlWriter will now be available for you to use.

LINQPad [extension] methods

LINQPad defines two extension methods (in LINQPad.Extensions), namely Dump() and Disassemble(). Dump() writes to the output window using LINQPad's output formatter and is overloaded to let you specify a heading:

typeof (int).Assembly.Dump ();
typeof (int).Assembly.Dump ("mscorlib");

You can also specify a maximum recursion depth to override the default of 5 levels:

typeof (int).Assembly.Dump (1);              // Dump just one level deep
typeof (int).Assembly.Dump (7); // Dump 7 levels deep
typeof (int).Assembly.Dump ("mscorlib", 7); // Dump 7 levels deep with heading

Disassemble() disassembles any method to IL, returning the output in a string:

typeof (Uri).GetMethod ("GetHashCode").Disassemble().Dump();

In addition to those two extension methods, there are some useful static methods in LINQPad.Util. These are documented in autocompletion, and include:

  • Cmd - executes a shell command or external program
  • CreateXhtmlWriter - creates a text writer that uses LINQPad's Dump() formatter
  • SqlOutputWriter - returns the text writer that writes to the SQL output window
  • GetMyQueries, GetSamples - returns a collection of objects representing your saved queries / samples (for an example, execute a search using Edit | Search All)
  • Highlight - wraps an object so that it will highlight in yellow when Dumped
  • HorizontalRun - lets you Dump a series of objects on the same line

LINQPad also provides the HyperLinq class. This has two purposes: the first is to display ordinary hyperlinks:

new Hyperlinq ("www.linqpad.net").Dump();
new Hyperlinq ("www.linqpad.net", "Web site").Dump();
new Hyperlinq ("mailto:user@domain.example", "Email").Dump();

You can combine this with Util.HorizontalRun:

Util.HorizontalRun (true,
"Check out",
new Hyperlinq ("http://stackoverflow.com", "this site"),
"for answers to programming questions.").Dump();

Result:

Check out this site for answers to programming questions.

The second purpose of HyperLinq is to dynamically build queries:

// Dynamically build simple expression:
new Hyperlinq (QueryLanguage.Expression, "123 * 234").Dump();

// Dynamically build query:
new Hyperlinq (QueryLanguage.Expression, @"from c in Customers
where c.Name.Length > 3
select c.Name", "Click to run!").Dump();

You can also write your own extension methods in LINQPad. Go to 'My Queries' and click the query called 'My Extensions'. Any types/methods that define here are accessible to all queries:

void Main()
{
"hello".Pascal().Dump();
}

public static class MyExtensions
{
public static string Pascal (this string s)
{
return char.ToLower (s[0]) + s.Substring(1);
}
}

In 4.46(.02) new classes and methods have been introduced:

  • DumpContainer (class)
  • OnDemand (extension method)
  • Util.ProgressBar (class)

Additionally, the Hyperlinq class now supports an Action delegate that will be called when you click the link, allowing you to react to it in code and not just link to external webpages.

DumpContainer is a class that adds a block into the output window that can have its contents replaced.

NOTE! Remember to .Dump() the DumpContainer itself in the appropriate spot.

To use:

var dc = new DumpContainer();
dc.Content = "Test";
// further down in the code
dc.Content = "Another test";

OnDemand is an extension method that will not output the contents of its parameter to the output window, but instead add a clickable link, that when clicked will replace the link with the .Dump()ed contents of the parameter. This is great for sometimes-needed data structures that is costly or takes up a lot of space.

NOTE! Remember to .Dump() the results of calling OnDemand in the appropriate spot.

To use it:

Customers.OnDemand("Customers").Dump(); // description is optional

Util.ProgressBar is a class that can show a graphical progressbar inside the output window, that can be changed as the code moves on.

NOTE! Remember to .Dump() the Util.ProgressBar object in the appropriate spot.

To use it:

var pb = new Util.ProgressBar("Analyzing data");
pb.Dump();
for (int index = 0; index <= 100; index++)
{
pb.Percent = index;
Thread.Sleep(100);
}

Is there a library that provides a formatted Dump( ) function like LinqPad?

This is what I've been using:

Special thanks to this thread (especially Pat Kujawa's & anunay's comments)

C# (Straight from Pat Kujawa's comment (though I made it return itself so that it chains like linqpad's version does)):

public static T Dump<T>(this T o) {
var localUrl = Path.GetTempFileName() + ".html";
using (var writer = LINQPad.Util.CreateXhtmlWriter(true))
{
writer.Write(o);
File.WriteAllText(localUrl, writer.ToString());
}
Process.Start(localUrl);
return o;
}

VB (my conversion since I needed it in a VB app):

Public Module LinqDebugging
<System.Runtime.CompilerServices.Extension()>
Public Function Dump(Of T)(ByVal o As T) As T
Dim localUrl = Path.GetTempFileName() + ".html"
Using writer = LINQPad.Util.CreateXhtmlWriter(True)
writer.Write(o)
File.WriteAllText(localUrl, writer.ToString())
End Using
Process.Start(localUrl)
Return o
End Function
End Module

You will need to add the linqpad executable as a reference in your project as well as System.IO and System.Diagnostics

This launches your default web browser showing the exact output that linqpad would generate.

LinqPad Dump from DLL

Thanks to Joe Albahari, adding LinqPad.exe as reference allows us to use Dump function from the library so no implementation is needed.

What is the Dump extension used for, and why is it so popular?

If you are just working with an expression, there is no reason to call Dump—it's called automatically. But, in the language selection box, LINQPad allows allows the selection of Statements and Program. Once you select one of those, you don't get any Dump output unless you call it.

With Statements or Programs, you might want to call Dump on multiple times. In those cases, it is handy to pass the Description parameters so you can distinguish the output.

There are also other parameters you can use to shape the output, such as depth, which limits the substructure details.

Simple example (Language=C# Statements):

var integers = Enumerable.Range(1,10);

integers.Select(i => new { i, v = i * i}).Dump("Squares");
integers.Select(i => new { i, v = i * i * i}).Dump("Cubes");

var output = "λ is awesome";
Encoding.UTF8.GetBytes(output)
.Dump("UTF-8");
Encoding.GetEncoding("Windows-1252").GetBytes(output)
.Dump("Windows-1252 (lossy)");

Apply method to literal

The issue is not that you cannot call a method on a literal. The issue is you cannot begin a line of code with a literal, much as you cannot begin a line of code with the New keyword. If you do this:

Dim x = "Hello".Split("l"c)
Dim y = 2.ToString()

it works without issue. If you do this:

"Hello".Split("l"c)
2.ToString()

you get two errors and, in both cases, mousing over the issue tells you:

Only member access expression can start an invocation statement.

Just as if you wanted to start a line with a constructor, you can use the Call keyword to effectively do what you want:

Call "Hello".Split("l"c)
Call 2.ToString()


Related Topics



Leave a reply



Submit