Creating Your First Visual Studio VSIX Package
If you need a new VSIX Package for Visual Studio, but can't find one in the market place, read this article to learn step-by-step how to create your own.
Join the DZone community and get the full member experience.
Join For Freeintroduction
visual studio extensibility features are not new in .net. it’s just that they are not very commonly used which, to me, is a surprise. visual studio extensibility features are in themselves so powerful that it gives a new definition to customization. customization of your ide, customization of the desired features that every developer would love to have, and even customization on the ide that could eventually result in a whole new product altogether, i.e. a custom visual studio with one’s own extensions and features. when discussing extensibility, i simply mean adding some more features or customizing the existing implementations of any product to fulfill your needs.
in this "three article" series of visual studio extensibility, we’ll learn how to create a new visual studio package, deploy that on a staging server and git via continuous integration setup, and at the end create a visual studio isolated shell application with that embedded package. due to the fact that this is a very rare topic and it's hard to find enough study material on this topic over the web, this article explains how to work with it - step by step. msdn contains good content but it's very generic and to the point. in my article, i'll try to explain each and every small part step by step, so that one can learn while coding.
vsix packages
vsix visual studio packages give us the flexibility to customize visual studio as per our need and requirement. as a developer, one always wants the ide on which one is working to have certain features apart from the inbuilt one. you can read more about theoretical aspects and the finer details of vsix packages here . the following is a small definition from the same msdn link.
“a vsix package is a .vsix file that contains one or more visual studio extensions, that, together with the metadata visual studio, is used to classify and install the extensions. that metadata is contained in the vsix manifest and the [content_types].xml file. a vsix package may also contain one or more extension.vsixlangpack files to provide localized setup text, and may contain additional vsix packages to install dependencies. the vsix package format follows the open packaging conventions (opc) standard. the package contains binaries and supporting files, together with a [content_types].xml file and a .vsix manifest file. one vsix package may contain the output of multiple projects or even multiple packages that have their own manifests. ”
the power that visual studio extensibility gives us is the opportunity to create our own extensions and packages that we can build on top of existing visual studios and even distribute/sell those over the visual studio market place . for example, i could not find an option in visual studio to compare two files. so, i created my own visual studio extension to compare two files within visual studio. the extension can be downloaded here .
in this article, i will explain how we can create an extension in visual studio to open the selected file in windows explorer. you must have seen that we already have a feature to open the selected project folder in windows explorer directly from visual studio, but wouldn't it be cool to get the feature by right-clicking on the file so that it opens the selected file in windows explorer as well? this allows us to create the extensions for ourselves, or we can create an extension for our team members or as per our project’s requirements and needs, or even just to have some fun and explore the technology.
roadmap
let’s get more segregated and define a roadmap to achieve a proper working customized isolated shell application from visual studio. the series will be divided into three articles as enumerated below. we’ll focus more on practical implementations and hands-on rather than go into much theory.
- visual studio extensibility (day 1): creating your first visual studio vsix package.
- visual studio extensibility (day 2): deploying the vsix package on the staging server and git via continuous integration.
- visual studio extensibility (day 3): embedding vsix package in visual studio isolated shell.
prerequisites
there are certain prerequisites that we need to take care of while working on extensibility projects. if you have visual studio 2015 installed, go to control panel >> programs and features and search for visual studio 2015. then, right-click on it to select “change” option.
here, we need to enable visual studio extensibility feature to work on this project type. on the next screen, click on “modify.” a list of all selected/unselected features would be available now and all we need to do is to select "visual studio extensibility tools update 3" in the features-> common tools, as shown in the following image.
now, press the update button and let visual studio update its extensibility features, after which we are good to go. before we actually start, i need the readers to download and install extensibility tools written by mads kristensen from here .
this series is highly inspired by mads kristensen’s speech at build 2016 and his work on visual studio extensibility.
create a vsix package
now, we can create our own vsix package inside visual studio. we’ll go step by step, therefore capturing every minor step and taking that into account. as i mentioned earlier, we’ll try to create an extension that allows us to open the selected visual studio file in windows explorer, something like shown in below image.
step 1: create a vsix project
open your visual studio. i am using visual studio 2015 enterprise edition and would recommend you to use at least visual studio 2015 for this tutorial.
create a new project like we create in every other project in visual studio. select file->new->project.
now, in the templates, navigate to extensibility and select vsix project. note that these templates are shown here because we modified visual studio configuration to use visual studio extensibility. select 'vsix project' and give it a name. for example, i gave it the name “loctatefolder.”
as soon as the new project is created, a “getting started” page is displayed with a lot of information and updates on visual studio extensibility. these are links to msdn and useful resources that you can explore to learn more and almost everything about extensibility.
we got our project with a default structure to start with, which includes an html file, a css file, and a vsixmanifest file. the manifest file, as the name suggests, keeps all the information related to the vsix project, and this file actually can be called a manifest to the extension created in the project.
we can clearly see that the “getting started” page that we see here comes from this index.html file which uses stylesheet.css. so, in our project, we really don’t need these files and we can remove these files.
and now, we are left only with the manifest file. so technically speaking, our step one has been accomplished, and we have created a vsix project.
step 2: configure the manifest file
when we open the manifest file, we see certain kinds of related information for the type of project that we added. we can modify this manifest file as per our choice for our extension. for example, in the productid, we can remove the text that is prefixed to the guid and only keeps the guid. note that guid is necessary as all the linking of items is done via guid in vsix projects. we’ll see this in more details later.
similarly, we can add a meaningful description in the "description box" like “helps to locate files and folder in windows explorer.” this description is necessary as it tells what your extension is for.
and if you look at the code of the manifest file by selecting the file, right click and view code or just press f7 on the designer opened to view code. you’ll see an xml file that is created in the background and all this information is saved in a well-defined xml format.
<?xml version="1.0" encoding="utf-8"?>
<packagemanifest version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<metadata>
<identity id="106f5189-471d-40ab-9de2-687c0a3d98e4" version="1.0" language="en-us" publisher="akhil mittal" />
<displayname>locatefolder</displayname>
<description xml:space="preserve">helps to locate files and folder in windows explorer.helps </description>
<tags>file locator, folder locator, open file in explorer</tags>ption>
</metadata>
<installation>
<installationtarget id="microsoft.visualstudio.community" version="[14.0]" />
</installation>
<dependencies>
<dependency id="microsoft.framework.ndp" displayname="microsoft .net framework" d:source="manual" version="[4.5,)" />
</dependencies>
</packagemanifest>
step 3: add custom command
we have successfully added a new project and configured its manifest file, but the real job is still pending - writing an extension to locate the file. for that, we need to add a new item to our project, so just right click on the project and select to add a new item from the items template.
as soon as you open the item templates, you’ll see an option to add a new custom command under visual c# items - > extensibility. the custom commands act as a button in vsix extensions. these buttons help us to bind an action and to its click event, so we can add our desired functionality to this button/command. name the custom command you added. for example, i gave it the name “locatefoldercommand” and then press "add" as shown in the image below.
once the command is added, we can see a lot of changes happening to our existing project. like adding some required nugget packages, a resources folder with an icon and an image, a .vsct file, a .resx file, and a command along with commandpackage.cs file.
each of the files has its own significance here. we’ll cover all these details. when we open the locatefoldercommandpackage.vsct file, we again see an xml file.
and when you remove all the comments to make it more readable, you’ll get a file something like what's shown below.
<?xml version="1.0" encoding="utf-8"?>
<commandtable xmlns="http://schemas.microsoft.com/visualstudio/2005-10-18/commandtable" xmlns:xs="http://www.w3.org/2001/xmlschema">
<extern href="stdidcmd.h" />
<extern href="vsshlids.h" />
<commands package="guidlocatefoldercommandpackage">
<groups>
<group guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" priority="0x0600">
<parent guid="guidshlmainmenu" id="idm_vs_menu_tools" />
</group>
</groups>
<buttons>
<button guid="guidlocatefoldercommandpackagecmdset" id="locatefoldercommandid" priority="0x0100" type="button">
<parent guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" />
<icon guid="guidimages" id="bmppic1" />
<strings>
<buttontext>invoke locatefoldercommand</buttontext>
</strings>
</button>
</buttons>
<bitmaps>
<bitmap guid="guidimages" href="resources\locatefoldercommand.png" usedlist="bmppic1, bmppic2, bmppicsearch, bmppicx, bmppicarrows, bmppicstrikethrough" />
</bitmaps>
</commands>
<symbols>
<guidsymbol name="guidlocatefoldercommandpackage" value="{a7836cc5-740b-4d5a-8a94-dc9bbc4f7db1}" />
<guidsymbol name="guidlocatefoldercommandpackagecmdset" value="{031046af-15f9-44ab-9b2a-3f6cad1a89e3}">
<idsymbol name="mymenugroup" value="0x1020" />
<idsymbol name="locatefoldercommandid" value="0x0100" />
</guidsymbol>
<guidsymbol name="guidimages" value="{8ac8d2e1-5ef5-4ad7-8aa6-84da2268566a}">
<idsymbol name="bmppic1" value="1" />
<idsymbol name="bmppic2" value="2" />
<idsymbol name="bmppicsearch" value="3" />
<idsymbol name="bmppicx" value="4" />
<idsymbol name="bmppicarrows" value="5" />
<idsymbol name="bmppicstrikethrough" value="6" />
</guidsymbol>
</symbols>
</commandtable>
so, primarily the file contains groups, buttons (that are commands lying in that group), button text, and some idsymbol, and image options.
when we talk about “groups”, it is the grouping of commands that is shown in visual studio. like in the below image, when in visual studio and you click on debug, you see various commands like windows, graphics, start debugging, etc.
some are separated by horizontal lines as well. these separated horizontal lines are groups. so a group is something that holds commands and acts as a logical separation between commands. in vsix project, we can create a new custom command and also define the groups to which it will associate. we can create new groups as well or extend existing groups like shown in the .vsct xml file.
step 4: configure custom command
so, first, open the vsct file and let us decide where our command will be placed. we basically want our command to be visible when we right click on any file in solution explorer. for that, in the .vsct file, you can specify the parent of your command, since it is an item node, we can choose idm_vs_ctxt_itemnode.
you can check all the available locations at the following link . similarly, we can also create menus, sub menus, and sub items, but for now, we’ll stick to our objective and place our command to item node.
similarly, we can also define the position at which our command will be shown. set the priority in the group, by default it is shown in the 6 th position as shown in the below image, but you can always change it. for example, i changed the priority to 0x0200 so as to see my command at the top level of the second position.
you can also change the default button text to “open in file explorer” and finally, after all the modifications, our xml looks as shown below.
“<?xml version="1.0" encoding="utf-8"?>
<commandtable xmlns="http://schemas.microsoft.com/visualstudio/2005-10-18/commandtable" xmlns:xs="http://www.w3.org/2001/xmlschema">
<extern href="stdidcmd.h"/>
<extern href="vsshlids.h"/>
<commands package="guidlocatefoldercommandpackage">
<groups>
<group guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" priority="0x0200">
<parent guid="guidshlmainmenu" id="idm_vs_ctxt_itemnode"/>
</group>
</groups>
<buttons>
<button guid="guidlocatefoldercommandpackagecmdset" id="locatefoldercommandid" priority="0x0100" type="button">
<parent guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" />
<icon guid="guidimages" id="bmppic1" />
<strings>
<buttontext>open in file explorer</buttontext>
</strings>
</button>
</buttons>
<bitmaps>
<bitmap guid="guidimages" href="resources\locatefoldercommand.png" usedlist="bmppic1, bmppic2, bmppicsearch, bmppicx, bmppicarrows, bmppicstrikethrough"/>
</bitmaps>
</commands>
<symbols>
<guidsymbol name="guidlocatefoldercommandpackage" value="{a7836cc5-740b-4d5a-8a94-dc9bbc4f7db1}" />
<guidsymbol name="guidlocatefoldercommandpackagecmdset" value="{031046af-15f9-44ab-9b2a-3f6cad1a89e3}">
<idsymbol name="mymenugroup" value="0x1020" />
<idsymbol name="locatefoldercommandid" value="0x0100" />
</guidsymbol>
<guidsymbol name="guidimages" value="{8ac8d2e1-5ef5-4ad7-8aa6-84da2268566a}" >
<idsymbol name="bmppic1" value="1" />
<idsymbol name="bmppic2" value="2" />
<idsymbol name="bmppicsearch" value="3" />
<idsymbol name="bmppicx" value="4" />
<idsymbol name="bmppicarrows" value="5" />
<idsymbol name="bmppicstrikethrough" value="6" />
</guidsymbol>
</symbols>
</commandtable>
when we open the locatefoldercommand.cs, that’s the actual place where we need to put our logic. in vs extensibility project/command, everything is handled and connected via guids. here, we see in the below image that a command set is created with a new guid.
now, when you scroll down, you see in the private constructor, we retrieve the command service that is fetched from the current service provider. this service is responsible for adding the command, provided that the command has a valid menucommandid with defined commandset and commandid.
we also see that there is a callback method bound to the command. this is the same callback method that's called when the command is invoked, and that is the best place to put our logic. by default, this call back method comes with a default implementation of showing a message box that proves the command is actually invoked.
let’s keep the default implementation for now and try to test the application. we can add business logic to open the file in windows explorer.
step 5: test custom command with default implementation
one may wonder how to test the default implementation. i would say, just compile and run the application. as soon as the application is run via f5, a new window will be launched that is similar to visual studio, as shown below.
note that we are creating an extension for visual studio, so ideally it should be tested in visual studio itself, on how it should look and how it should work. a new visual studio instance is launched to test the command. note that this instance of visual studio is called "experimental instance." as the name suggests, this is for testing our implementation, basically checking how the things will work and look like.
in the launched experimental instance, add a new project like we add in normal visual studio. note that all the features in this experimental instance can be configured and switched to "on" and "off" on an as needed basis. we can cover the details in my third article, i.e. when we discuss visual studio isolated shell.
to be simple, choose a new console application and name it whatever you'd like. i named it ‘sample.”
when the project is added to solution explorer, we see a common project structure. remember, our functionality was to add a command to the selected file in visual studio solution explorer. now, we can test our implementation: just right-click on any file and you can see the “open in file explorer” command in a new group in the context menu as shown in the following image.
the text comes from the text that we defined for our command in vsct file.
before you click on the command, place a breakpoint on the menuitemcallback method in the command file. so, when the command is clicked, you can see the menuitemcallback method is invoked.
since this method contains the code to show a message box, just press f5 and you see a message box with a defined title, as shown in the following image.
this proves that our command works, and we just need to put the correct logic here. we can certainly take a break and celebrate at this point.
step 6: add actual implementation
so now, this is the time to add our actual implementation. we already know the place, we just need to code. for actual implementation, i have added a new folder to the project and named it utilities and added a class to that folder and named it locatefile.cs with the following implementation.
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.runtime.compilerservices;
using system.runtime.interopservices;
using system.runtime.interopservices.comtypes;
namespace locatefolder.utilities
{
internal static class locatefile
{
private static guid iid_ishellfolder = typeof(ishellfolder).guid;
private static int pointersize = marshal.sizeof(typeof(intptr));
public static void fileorfolder(string path, bool edit = false)
{
if (path == null)
{
throw new argumentnullexception("path");
}
intptr pidlfolder = pathtoabsolutepidl(path);
try
{
shopenfolderandselectitems(pidlfolder, null, edit);
}
finally
{
nativemethods.ilfree(pidlfolder);
}
}
public static void filesorfolders(ienumerable<filesysteminfo> paths)
{
if (paths == null)
{
throw new argumentnullexception("paths");
}
if (paths.count<filesysteminfo>() != 0)
{
foreach (
igrouping<string, filesysteminfo> grouping in
from p in paths group p by path.getdirectoryname(p.fullname))
{
filesorfolders(path.getdirectoryname(grouping.first<filesysteminfo>().fullname),
(from fsi in grouping select fsi.name).tolist<string>());
}
}
}
public static void filesorfolders(ienumerable<string> paths)
{
filesorfolders(pathtofilesysteminfo(paths));
}
public static void filesorfolders(params string[] paths)
{
filesorfolders((ienumerable<string>)paths);
}
public static void filesorfolders(string parentdirectory, icollection<string> filenames)
{
if (filenames == null)
{
throw new argumentnullexception("filenames");
}
if (filenames.count != 0)
{
intptr pidl = pathtoabsolutepidl(parentdirectory);
try
{
ishellfolder parentfolder = pidltoshellfolder(pidl);
list<intptr> list = new list<intptr>(filenames.count);
foreach (string str in filenames)
{
list.add(getshellfolderchildrenrelativepidl(parentfolder, str));
}
try
{
shopenfolderandselectitems(pidl, list.toarray(), false);
}
finally
{
using (list<intptr>.enumerator enumerator2 = list.getenumerator())
{
while (enumerator2.movenext())
{
nativemethods.ilfree(enumerator2.current);
}
}
}
}
finally
{
nativemethods.ilfree(pidl);
}
}
}
private static intptr getshellfolderchildrenrelativepidl(ishellfolder parentfolder, string displayname)
{
uint num;
intptr ptr;
nativemethods.createbindctx();
parentfolder.parsedisplayname(intptr.zero, null, displayname, out num, out ptr, 0);
return ptr;
}
private static intptr pathtoabsolutepidl(string path) =>
getshellfolderchildrenrelativepidl(nativemethods.shgetdesktopfolder(), path);
private static ienumerable<filesysteminfo> pathtofilesysteminfo(ienumerable<string> paths)
{
foreach (string iteratorvariable0 in paths)
{
string path = iteratorvariable0;
if (path.endswith(path.directoryseparatorchar.tostring()) ||
path.endswith(path.altdirectoryseparatorchar.tostring()))
{
path = path.remove(path.length - 1);
}
if (directory.exists(path))
{
yield return new directoryinfo(path);
}
else
{
if (!file.exists(path))
{
throw new filenotfoundexception("the specified file or folder doesn't exists : " + path, path);
}
yield return new fileinfo(path);
}
}
}
private static ishellfolder pidltoshellfolder(intptr pidl) =>
pidltoshellfolder(nativemethods.shgetdesktopfolder(), pidl);
private static ishellfolder pidltoshellfolder(ishellfolder parent, intptr pidl)
{
ishellfolder folder;
marshal.throwexceptionforhr(parent.bindtoobject(pidl, null, ref iid_ishellfolder, out folder));
return folder;
}
private static void shopenfolderandselectitems(intptr pidlfolder, intptr[] apidl, bool edit)
{
nativemethods.shopenfolderandselectitems(pidlfolder, apidl, edit ? 1 : 0);
}
[comimport, guid("000214f2-0000-0000-c000-000000000046"), interfacetype(cominterfacetype.interfaceisiunknown)]
internal interface ienumidlist
{
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int next(uint celt, intptr rgelt, out uint pceltfetched);
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int skip([in] uint celt);
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int reset();
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int clone([marshalas(unmanagedtype.interface)] out ienumidlist ppenum);
}
[comimport, guid("000214e6-0000-0000-c000-000000000046"), interfacetype(cominterfacetype.interfaceisiunknown),
comconversionloss]
internal interface ishellfolder
{
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void parsedisplayname(intptr hwnd, [in, marshalas(unmanagedtype.interface)] ibindctx pbc,
[in, marshalas(unmanagedtype.lpwstr)] string pszdisplayname, out uint pcheaten, out intptr ppidl,
[in, out] ref uint pdwattributes);
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int enumobjects([in] intptr hwnd, [in] shcont grfflags,
[marshalas(unmanagedtype.interface)] out ienumidlist ppenumidlist);
[preservesig, methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
int bindtoobject([in] intptr pidl, [in, marshalas(unmanagedtype.interface)] ibindctx pbc, [in] ref guid riid,
[marshalas(unmanagedtype.interface)] out ishellfolder ppv);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void bindtostorage([in] ref intptr pidl, [in, marshalas(unmanagedtype.interface)] ibindctx pbc,
[in] ref guid riid,
out intptr ppv);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void compareids([in] intptr lparam, [in] ref intptr pidl1, [in] ref intptr pidl2);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void createviewobject([in] intptr hwndowner, [in] ref guid riid, out intptr ppv);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void getattributesof([in] uint cidl, [in] intptr apidl, [in, out] ref uint rgfinout);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void getuiobjectof([in] intptr hwndowner, [in] uint cidl, [in] intptr apidl, [in] ref guid riid,
[in, out] ref uint rgfreserved, out intptr ppv);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void getdisplaynameof([in] ref intptr pidl, [in] uint uflags, out intptr pname);
[methodimpl(methodimploptions.internalcall, methodcodetype = methodcodetype.runtime)]
void setnameof([in] intptr hwnd, [in] ref intptr pidl, [in, marshalas(unmanagedtype.lpwstr)] string pszname,
[in] uint uflags, [out] intptr ppidlout);
}
private class nativemethods
{
private static readonly int pointersize = marshal.sizeof(typeof(intptr));
public static ibindctx createbindctx()
{
ibindctx ctx;
marshal.throwexceptionforhr(createbindctx_(0, out ctx));
return ctx;
}
[dllimport("ole32.dll", entrypoint = "createbindctx")]
public static extern int createbindctx_(int reserved, out ibindctx ppbc);
[dllimport("shell32.dll", charset = charset.unicode)]
public static extern intptr ilcreatefrompath([in, marshalas(unmanagedtype.lpwstr)] string pszpath);
[dllimport("shell32.dll")]
public static extern void ilfree([in] intptr pidl);
public static ishellfolder shgetdesktopfolder()
{
ishellfolder folder;
marshal.throwexceptionforhr(shgetdesktopfolder_(out folder));
return folder;
}
[dllimport("shell32.dll", entrypoint = "shgetdesktopfolder", charset = charset.unicode, setlasterror = true)
]
private static extern int shgetdesktopfolder_(
[marshalas(unmanagedtype.interface)] out ishellfolder ppshf);
public static void shopenfolderandselectitems(intptr pidlfolder, intptr[] apidl, int dwflags)
{
uint cidl = (apidl != null) ? ((uint)apidl.length) : 0;
marshal.throwexceptionforhr(shopenfolderandselectitems_(pidlfolder, cidl, apidl, dwflags));
}
[dllimport("shell32.dll", entrypoint = "shopenfolderandselectitems")]
private static extern int shopenfolderandselectitems_([in] intptr pidlfolder, uint cidl,
[in, optional, marshalas(unmanagedtype.lparray)] intptr[] apidl, int dwflags);
}
[flags]
internal enum shcont : ushort
{
shcontf_checking_for_children = 0x10,
shcontf_enable_async = 0x8000,
shcontf_fastitems = 0x2000,
shcontf_flatlist = 0x4000,
shcontf_folders = 0x20,
shcontf_includehidden = 0x80,
shcontf_init_on_first_next = 0x100,
shcontf_navigation_enum = 0x1000,
shcontf_netprintersrch = 0x200,
shcontf_nonfolders = 0x40,
shcontf_shareable = 0x400,
shcontf_storage = 0x800
}
}
}
this class contains the business logic, primarily methods that take file path as a parameter and work with the shell to open this file in explorer. i’ll not go into details of this class but focus more on how we can invoke this functionality.
now, in the menuitemcallback method, put the following code to invoke the method of our utility class.
private void menuitemcallback(object sender, eventargs e)
{
var selecteditems = ((uihierarchy)((dte2)this.serviceprovider.getservice(typeof(dte))).windows.item("{3ae79031-e1bc-11d0-8f78-00a0c9110057}").object).selecteditems as object[];
if (selecteditems != null)
{
locatefile.filesorfolders((ienumerable<string>)(from t in selecteditems
where (t as uihierarchyitem)?.object is projectitem
select ((projectitem)((uihierarchyitem)t).object).filenames[1]));
}
}
this method now first fetches all the selected items using dte object. with dte objects, you can do all the transactions and manipulations in visual studio components. read more about the power of dte objects here .
after getting the selected items, we invoke the filesorfolders method of the utility class and pass the file path as a parameter; job done. now, again, launch the experimental instance and check the functionality.
step 7: test the actual implementation
launch an experimental instance, add a new or existing project, and right-click on any file followed by invoking the command.
as soon as you invoke the command, you’ll see that the folder is opened in windows explorer with that file selected, as shown below.
this functionality also works for the linked files in visual studio. let’s check that. add a new item in the project opened in an experimental instance and add a file as a link, as shown in the following image.
you only need to select “add as link” while adding the file. this file would then be shown in visual studio with a different icon, showing that this is a linked file. now, select the actual visual studio file and the linked file in visual studio and invoke the command now.
when the command is invoked, you can see two folders opened with both the files selected at their own location.
not only this, we have created this extension in the extensions and updates. in this experimental instance, you can search for this extension and you’ll get it installed in your visual studio, as shown in the following image.
now it’s time to celebrate again.
step 8: optimizing the package
our job is nearly done, but there are a few more important things that we need to take care of. we need to make this package more appealing, add some image/icons to the extension, and optimize the project structure to make it more readable and understandable.
remember, when we started this tutorial, i mentioned you should download and install vs extensibility tools. vs extensibility tools provide some cool features that you can really leverage. for example, it allows you to export all the available images in visual studio. we can use these images to make our icon and default image for the extension. to start with, in visual studio where your code was written, go to “tools >> export image moniker…”
a window will open so you can search for the image you need to choose. search for “open”, and you’ll get the same image as shown in the context menu of the project to open the project in windows explorer.
we’ll use this image only for our extension. give it a size 16*16 and click "export." save that in your "resources" folder of the project. replace the already existing "locatefoldercommand.png" file with this file and give this new exported file the same name. since in the .vsct file, it was defined that the prior image sprint has to be used with the first icon, so we always got to see 1x beside the custom command text, but we need a good looking meaningful image now. so, we exported this “open in explorer” image.
now, go to .vsct file. in the bitmaps, first, delete all the image names in the list except bmppic1 from the usedlist and in the guidsymbol, delete all idsymbol except bmppic1. we do not need to change the href link in bitmap node because we replaced the existing image with the newly exported image with the same name. we did this because we are not using that old default image spirit, but we are now using our newly exported image.
in that case, the locatefoldercommandpackage.vsct file would look like this.
<?xml version="1.0" encoding="utf-8"?>
<commandtable xmlns="http://schemas.microsoft.com/visualstudio/2005-10-18/commandtable" xmlns:xs="http://www.w3.org/2001/xmlschema">
<extern href="stdidcmd.h" />
<extern href="vsshlids.h" />
<commands package="guidlocatefoldercommandpackage">
<groups>
<group guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" priority="0x0200">
<parent guid="guidshlmainmenu" id="idm_vs_ctxt_itemnode" />
</group>
</groups>
<buttons>
<button guid="guidlocatefoldercommandpackagecmdset" id="locatefoldercommandid" priority="0x0100" type="button">
<parent guid="guidlocatefoldercommandpackagecmdset" id="mymenugroup" />
<icon guid="guidimages" id="bmppic1" />
<strings>
<buttontext>open in file explorer</buttontext>
</strings>
</button>
</buttons>
<bitmaps>
<bitmap guid="guidimages" href="resources\locatefoldercommand.png" usedlist="bmppic1" />
</bitmaps>
</commands>
<symbols>
<guidsymbol name="guidlocatefoldercommandpackage" value="{a7836cc5-740b-4d5a-8a94-dc9bbc4f7db1}" />
<guidsymbol name="guidlocatefoldercommandpackagecmdset" value="{031046af-15f9-44ab-9b2a-3f6cad1a89e3}">
<idsymbol name="mymenugroup" value="0x1020" />
<idsymbol name="locatefoldercommandid" value="0x0100" />
</guidsymbol>
<guidsymbol name="guidimages" value="{8ac8d2e1-5ef5-4ad7-8aa6-84da2268566a}">
<idsymbol name="bmppic1" value="1" />
</guidsymbol>
</symbols>
</commandtable>
the next step is to set an extension image and a preview image that would be shown for the extension in visual studio gallery and visual studio marketplace. these images will represent the extension everywhere.
so, follow the same routine of exporting an image from image monikor. note that you can also use your own custom images for all the image/icon related operations.
open the image moniker as i explained earlier and search for locateall, then export two images, one for icon (90 x 90):
and one for preview (175 x 175):
export both the images with the name icon.png and preview.png respectively in the resources folder. then, in the solution explorer, include those two images in the project, as shown below.
now, in the source.extension.vsixmanifest file, set the icon and preview images to the same exported images as shown in the following image.
step 9: test the final package
again, it’s time to test the implementation with new images and icons. so compile the project, press f5, and the experimental instance will launch. add a new or existing project and right-click on any project file to see your custom command.
so now we have the icon that we selected earlier from the image moniker for this custom command. since we have not touched the functionality, it should work as before.
now go to extensions and updates and search for the installed extension “locatefolder.” you’ll see a beautiful image before your extension, this is the same image with dimensions 90x90 and in the right side panel, you can see the enlarged 175x175 preview image.
now we can certainly celebrate as the task is completely accomplished.
conclusion
this detailed article focused on how a visual studio extension could be created. in the next article, i’ll explain how the project structure could be optimized to make it more readable and understandable and how to deploy the extension to visual studio market place via continuous integration and git. the basic idea would be to optimize the structure, push the code to git, push the extension to visual studio gallery via continuous integration through appveyor , and push the extension to vs marketplace. i hope, this article helped you understand the visual studio extensibility. feel free to share your feedback, ratings, and comments.
references
- https://channel9.msdn.com/events/build/2016/b886
- https://blogs.msdn.microsoft.com/quanto/2009/05/26/what-is-a-vsix
- https://msdn.microsoft.com/en-us/library/dd997148.aspx
complete source code
https://github.com/akhilmittal/locatefileinwindowsexplorer
extension at marketplace
https://marketplace.visualstudio.com/items?itemname=vs-publisher-457497.locatefolder
read more
Published at DZone with permission of Akhil Mittal. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments