| Comments

A few weeks ago I had the great pleasure of being in front of you, our developer customers (and friends) at the Microsoft BUILD conference. (I never know how to write “build” in a sentence and refuse to use the “//” in front of it.) These are things that I LOVE doing and wish I could do it more. I had the privilege of introducing an overview of what was new in the XAML UI framework for Windows 8.1. All the sessions are recorded so please go view mine and review it how you think so they might invite me back!

In my session I gave some preview of some of the great new XAML tooling that is introduced for developer productivity in Visual Studio 2013 which, as of this writing, is currently in preview form and available for download. My colleague Unni followed my session with one specifically about XAML tooling enhancements with a whirlwind tour of all the new features. Please go check out his session: What’s New in Blend and Visual Studio for XAML Developers for the complete details.

One of the things I showed was the introduction of Visual Studio (VS) code snippets for the XAML editor. This was one of the customer requests for a while for the XAML editor and is now available in the VS 2013 preview! In my presentation I showed a common task that I do which is to have many elements and wrap them in a StackPanel. I’ve gotten lazy and wanted a quick ‘refactor’ way to do this and now I can! A few have emailed me asking where the snippet I used was as nothing was working in the preview for them. As of this writing, the functionality was in the preview, however no default XAML code snippets are provided. I’ve responded to a few on an MSDN forum thread offering to share my snippets and someone suggested I post more details, so here it is!

Anatomy of a Code Snippet

Code Snippets in VS are basically XML files that sit in a special location (one of two locations, global or user). These code snippets can apply to many things including languages (C#, VB, etc.) as well as ‘markup’ languages (CSS and now XAML). You can read more in-depth data about VS Code Snippets here. The basics that I think you want to know are the two main types of snippets: Expansion and SurroundWith.

An Expansion snippet is one that you invoke and it gives you placeholders for stuff to fill out. My most widely used one is ‘foreach’ in C#. You start typing foreach, then hit tab-tab and you are presented with a template, more or less, to complete. A SurroundWith snippet is one that surrounds (duh!) the selected content in the editor surface with your template. An example of this is the #region snippet which puts the begin/end region tags around selected code. It is important to note that these can be used exclusively or together. That is to say I can have a SurroundWith snippet that is also an Expansion. In fact, the #region one is a good example: it surrounds the selected code and also gives you a field to complete for the region name. The Code Snippet structure is the same for most languages with the difference being that in the Code node of the snippet definition it defines which language it applies to for the editors.

NOTE: Creating Code Snippets is a very manual process. At the time of this writing there was no really great tool to “extract” a chunk of code and turn it into a code snippet. There are a few attempts out there, but most have been abandoned and not all working.

Once you have these XML files (.snippet files for VS), you place them in well-known locations or can use the Code Snippets manager in VS (more on that later).

XAML Code Snippets

As noted above the XAML code snippets are the same structure as the C# snippets with the difference being the Language attribute on the Code node in the definition. In my demo I used a StackPanel SurroundWith snippet with the following definition:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
    <Title>Vertical StackPanel</Title>
    <Author>Tim Heuer</Author>
    <Description>XAML snippet for surrounding content in a vertical StackPanel</Description>
    <HelpUrl>
    </HelpUrl>
    <Shortcut>vsp</Shortcut>
  </Header>
  <Snippet>
    <Code Language="XAML"><![CDATA[<StackPanel>$selected$$end$</StackPanel>]]></Code>
  </Snippet>
</CodeSnippet>

Notice the <Code> element and how it has the Language=”XAML”? That is the only difference between this and a C# one. There are keywords for certain things like selected (which is a marker for selected content) and end (which is where you want the cursor to be at the completion of the snippet) that you can use and are in the documentation. Here is another example of an Expansion XAML snippet for an AppBarButton:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>AppBarButton</Title>
            <Shortcut>abb</Shortcut>
            <Description>Code snippet for XAML AppBarButton</Description>
            <Author>Tim Heuer</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>icon</ID>
                    <ToolTip>The Icon value to use for the visual</ToolTip>
                    <Default>Emoji</Default>
                </Literal>
                <Literal>
                    <ID>label</ID>
                    <ToolTip>The text label for the button</ToolTip>
                    <Default>My Label</Default>
                </Literal>
                <Literal>
                    <ID>uniqueid</ID>
                    <ToolTip>The unique ID for the button</ToolTip>
                    <Default>MyAppBarButton</Default>
                </Literal>
            </Declarations>
            <Code Language="XAML"><![CDATA[<AppBarButton x:Uid="$uniqueid$" x:Name="$uniqueid$" Label="$label$" Icon="$icon$" />$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

As you can see they are pretty simple to use!

Adding Code Snippets to VS

There are two ways to distribute snippets: as raw .snippet files or with an installer. You can send someone a .snippet file and they can use the Code Snippets Manager tool to import it into their environment. This is a per-user method. From VS you would use the Tools menu and choose the Code Snippets manager:

<pic>

From here you would navigate to the XAML folder, then choose Import and select your .snippet files. These would then import them into your local profile (Documents\Visual Studio 2013\Code Snippets) and be ready for immediate use. Another way is through an installer. Now up until VS 2013 there was the VSI installer (as documented here on MSDN) which has since been eclipsed by the VSIX extensibility method. Right now there doesn’t appear to be much documentation on this method, but you *can* distribute code snippets via the VSIX installer. VSIX is basically a ZIP file format with a manifest and content. For this purpose the manifest describes the targets and the package definition for the VSPackage we are installing, which is in this case a folder of snippets. This is a little tricky method to get VSIX to use as an installer for snippets, but works. I won’t detail out the entire process here, but leave you with a few screenshots and you can download the file and look at the contents to see how it works…again it is a regular ZIP file so just rename and explore.

Contents of VSIX:

Contents of VSIX package

Installer dialog:

VSIX installer dialog

Once installed your VSIX-deployed snippets show up in the Extension Manager:

Extension manager listing

And there you have it! A simple way to distribute your code snippets. This VSIX can be put on VS gallery as well so that you can update it there and anyone who installed it can get updates from within VS itself!

To actually use the code snippets, from within the XAML editor use the shortcuts CTRL+K,S (for surround snippets):

Surround code snippet

or CTRL+K,X (for expansion snippets):

Expansion snippet

Expansion snippet completed

Summary

Code snippets can be a powerful productivity tool for VS. You probably use them daily (like foreach) and maybe didn’t even realize it! Now that this concept is extended to XAML there are some great opportunities to increase your markup productivity by encapsulating some things that you do often into a XAML code snippet. Right now the VS gallery doesn’t support uploading the method for VSIX that I have described so you can download my VSIX for some code snippets examples here for now.

Hope this helps!

| Comments

While working on some plugins for the new Seesmic Desktop Platform I got sick of copying and pasting some boiler plate code over and over.  I had created some helper templates for myself so that I could say File…New Seesmic Desktop Plugin and get everything I needed initially.  This weekend I had some time and formalized those templates into an easy-to-use installer for anyone to consume. 

NOTE: It is likely that Seesmic themselves will create developer project/item templates…these were for my own use and I shared them on the Seesmic Desktop Platform developer forum for anyone to benefit from (or ignore).  They are not the official templates from Seesmic.

Prior to VS2010 you could create what is called a Visual Studio Community Content Installer…which is a .VSI file that installs things like snippets, etc.  And actually you can still do that today.  The process is manual and involves a few XML manifest files, zipping up the contents and renaming it to .VSI (the VSI is just a ZIP format).  It isn’t hard, but isn’t painless as well – it’s a lot of manual steps.

Enter VS2010 and the Visual Studio SDK.  First, the items I am describing below require you to have the VS2010 SDK installed.  It is NOT installed by default.  Visual Studio 2010 has a file format called VSIX which is basically a Visual Studio Extension (VSX was already taken by Visio).  This extension format is intended to be a one-stop installer format for all things extensible.  Things like add-ins, etc.  But it can also be used for simple things like Item and Project template types.  Here’s what I did.

1. Starting the project

After you have VS2010 SDK installed, choose File…New VSIX Project

VSIX Project

Note that this is under a language area (C# or Visual Basic).  This is because there is some assumption that you are creating more than just a template deployer…but just note that.  In my instance it actually didn’t matter what language area I chose.

2. Removing ‘binary’ packages

By default the VSIX project thinks you are going to be creating code extensions and will package the project’s DLL and PDB files as a part of your extension.  If you are using this process as I was for template extensions, this is not necessary.  There is an easy way of avoiding this.  Open up the csproj file (or vbproj) you just created in notepad and add these lines in the XML file:

   1: <PropertyGroup>
   2:   <CopyBuildOutputToOutputDirectory>false</CopyBuildOutputToOutputDirectory>
   3:   <CopyOutputSymbolsToOutputDirectory>false</CopyOutputSymbolsToOutputDirectory>
   4: </PropertyGroup>

This tells the compiler to not package those types of files into our extension.  I put these below my last PropertyGroup statement in the file.  Save the proj file.  If you return to Visual Studio (and had the project open while making these edits in notepad) you’ll be alerted to reload the project, go ahead and reload baby.

3. Editing the manfiest information

When you create the project it will open up with a dialog that is a visual editor to the core manifest.  This is where you will put your metadata as well as begin to add your content.  Here is a snapshot of mine:

VSIX Manifest Editor

Notice the simple metadata information (name, author, version, etc.).  This is important information that I’d highly recommend to include as you’ll see why in later steps.

Notice the Content area in the bottom.  This is where you’ll add your content.  If you have a blank project you will click the Add Content button and choose the type (in my case Project Template and Item Template) and browse to the file.  Note that this copies that file to this project…not a reference.  So if you change the file outside of this project, you’ll want to update it again.  Do this for each template type you want to deploy.

4. Understanding Path information for templates

Notice my path of my templates:

template path data

This is important because it will determine how the templates are structured in Visual Studio after the user installs them.  My path above results in this:

Installed Templates view

This enables my users to find it under Silverlight as well as the custom branch that I have specified.  This is a helpful tip to your users and provides a more professional look in my opinion.

5.  Building the VSIX file

This step is easy.  F5.  It’s the same build process as any other project type.  The result is a VSIX file.  When the user double-clicks on that (and has Visual Studio installed) they’ll see your dialog:

VSIX Install Dialog

You could optionally digitally sign your VSIX file so the ‘unidentified publisher’ statement isn’t there.

6.  Making your VSIX Discoverable

This is the fun part.  Now that you have a standard Visual Studio Extension, you can make it readily available to any Visual Studio developer.  You could simply post a link to it on your blog, have the user download the VSIX and that is acceptable.  But you can also make it available in Visual Studio’s online gallery which then becomes searchable and seamlessly installable by end users.

Visit the Visual Studio Gallery page to start the process.  Notice the Upload button in the upper right area…that is where you start.  After authenticating with Windows Live ID, it is a 3 step process:

  1. Determine what type (Tool, Control, Template)
  2. Upload the VSIX
  3. Edit and annotate further criteria

The first two steps are simple, in my case I chose Template, then uploaded my VSIX which goes through some steps of validation making sure it is a valid VSIX file.  The final step enables you to specify more data that is annotating your extension to make it more searchable.  Here was my page.

Visual Studio Gallery info page

Notice the tags I added to help it be discoverable?  Now users can – from within Visual Studio 2010 – search and install extensions immediately:

Integrated extension search in Visual Studio

Any installed extensions show up in the Extension Manager (Tools menu) for easy disabling or uninstalling).

Summary

After this quick process I have a distributed package for my community as well as now have added templates to my development environment making it easy to create new extensions for Seesmic (my sample used here):

new project templates

It was fairly simple and I love that it is integrated into Visual Studio 2010 for everyone now!

Hope this helps!