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"));
}