65.9K
CodeProject is changing. Read more.
Home

Using Built-in Visual Studio Diff Tool in VS Extension

starIconstarIconstarIconstarIconstarIcon

5.00/5 (10 votes)

Jan 5, 2015

CPOL
viewsIcon

28510

An approach to call built-in Visual Studio commands from within Visual Studio extensions

Background

Once when I was reinventing the wheel (writing a custom JSON viewer/comparer), I encountered the following issue: I wanted to compare JSON data within a Visual Studio extension but I did not want to write my own comparer. I decided to use a built-in Visual Studio tool.

The tool is well known; you can call DiffFiles command in the Command window:

Tools.DiffFiles c:\file1 c:\file2

However, it was a puzzle for me how to execute this command from a Visual Studio extension without the Command window and without creation of another instance of Visual Studio. After spending few hours searching the Internet and making a number of tests, I came up with a simple solution which I'd like to describe here.

Solution

The main window of Visual Studio extensions having UI is inherited from Microsoft.VisualStudio.Shell.ToolWindowPane. This object has Package property which implements System.IServiceProvider interface. This interface provides access to the root object in Visual Studio COM. Here is the refined and simplified code to demonstrate the solution:

public void CompareJsonData(IServiceProvider serviceProvider, string data1, string data2)
{
    var tempFolder = Path.GetTempPath();

    var tempFile1 = Path.Combine(tempFolder, Guid.NewGuid().ToString());
    File.WriteAllText(tempFile1, data1);

    var tempFile2 = Path.Combine(tempFolder, Guid.NewGuid().ToString());
    File.WriteAllText(tempFile2, data2);

    DTE dte = (DTE)serviceProvider.GetService(typeof(DTE));
    dte.ExecuteCommand("Tools.DiffFiles", 
    string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", tempFile1, tempFile2, 
    "1st JSON data", "2nd JSON data"));
}