Chapter 3. Customizing Visual Studio

In This Chapter

  • Setting environment options

  • Changing menus and commands

  • Making and accessing snippets

  • Hacking project templates

You have seen how to install Visual Studio and make a new project. You have seen the bits that the user interface gives you. The fun's over. Now you get to make it work for you.

Then again, maybe the fun is just starting.

Visual Studio offers a dizzying array of options for customization. Used poorly, these options have the real potential to make the lives of you and your coworkers miserable. Used correctly, they have the potential to double your velocity.

I am after the doubling part.

At its most basic, customization involves setting options to better match your environment, style, and work patterns. These options include everything from your code visibility to source control. The idea is to configure Visual Studio's options to your exact specifications.

The next step is to improve the usability of the application to match your day-to-day operations. One of the best overall ways to accomplish this is to change the button tape and the menus to make what you use every day more available. Another great way to do this is to manage or create snippets that automate generation of code.

Finally, you take a short deep dive (just hold your breath, you'll be fine) into the Project and File templates of Visual Studio. Did you know that when you create a new XAML file (for example) or C# Class file that the contents of that file are controlled by a template and are editable? No? Well, do I have a surprise for you!

All these things put together amount to a rather flexible Integrated Development Environment (IDE). Although the flexibility is nice, the goal is to set a configuration that matches your style. I can't tell you what that configuration is. All I can do is tell you what the software can do and give you the tools to make the changes.

I learned a new phrase yesterday at DevLink: convention over configuration. You build software the way most people use it, rather than provide 10,000 options to change the way it works. I think Visual Studio gives you some of each, but you have to push the balance to the convention side yourself.

Setting Options

The Options dialog box can be found by choosing the Tools

Setting Options
The default Options screen.

Figure 3-1. The default Options screen.

Those details are all well and good, but my goal is to introduce the other things that the options provide. I start with adjustments to your environment and then describe the remarkable language options, and then I explore some neat stuff.

Environment

The Environment section is where you begin in the Options dialog box. Sections here include the font details of code-editing screens, key mappings, and the RSS feed settings for the Start page.

The Font and Colors settings will probably be of interest only when you need them for a presentation. Sixteen points is the size of choice for most speakers, including myself. There are a number of "code friendly" fonts out there, and this is where you select them.

Defining the Start Page

The start page is the first page you see when you start Visual Studio. It consumes an RSS feed from Microsoft with news related to the kind of development you do, as you told Visual Studio when you first installed the software. Often, people change roles and the RSS feed no longer applies to their work. This is a problem.

Note

The solution is the Start Page News Channel field. You can pick any RSS feed you are interested in using for your Start Page content. If you like Microsoft Developer content, you can choose Scott Hanselman's feed for your Start Page. If you are interested in security, you can use Exotic Liability's blog. If you like silliness, you can use the feed at www.sempf.net. Alternatively, you can set it to show nothing. You're in charge.

Keyboard commands

The most useful settings in the Options dialog box are the Keyboard settings. This is where you make Visual Studio feel like Emacs through the use of keyboard mappings.

Tip

Keyboard mappings are key combinations you set to run commands you usually run by clicking your mouse. For example, one commonly used mapping is Ctrl+C, which copies material in the same way that clicking the Edit menu and then clicking Copy does. Many developers feel that using keyboard mapped commands makes the development experience faster and easier.

The keyboard settings essentially enable you to set keyboard commands for any menu selection in Visual Studio. The Apply the Following Additional Keyboard Mapping Scheme drop-down list enables the key mappings to be different, if you happen to like the mappings of other development environments.

Language

By language, I don't mean the Internationalization setting that enables you to change the display language of Visual Studio if you have additional language packs installed (although that is neat). I am talking about the programming languages you work in with Visual Studio. The Languages option is where you can provide settings for each of these programming languages.

The Text Editor options change the way the Code Editor behaves. All the languages that Visual Studio supports out of the box appear in the tree view under the main heading and allow you to alter general options, tabbing, formatting, sometimes advanced options, and miscellaneous features of the text editor.

For instance, look at C#. To open the C# view, click where it says C# with the little triangle in the Options tree view (that's a WPF tree view — you'll get used to it). The first view in the Options panel is the General view. Here you can change the default options for statement completion, various behavior settings, and what the Code Editor should display aside from the code.

After you click the little triangle next to the C# node, you see the General panel (which is the default view) and then the other panels you can use:

  • Tabs: This section is for people who are obsessive about the tabbing of their source code. The Tabs panel determines how many spaces make up a tab, and whether Visual Studio should insert them automatically.

  • Advanced: This section should probably be called Miscellaneous. Everything that doesn't fit into other categories is here. In this section, handling comments, interface implementation, and refactoring details all have a checkbox that basically says "If you don't like it when Visual Studio does this, click here."

  • Formatting: Formatting in C# is very in-depth. Generally, C# coders are a little persnickety about the look of their code. Visual Studio does a lot of work to help make your code look the way you want it, but you have to tell it what to do. Options for formatting include:

    • Automatic formatting

    • Indentation

    • Newlines

    • Spacing

    • Wrapping

  • IntelliSense: The most interesting field is the list of characters that "commit" an IntelliSense selection. By typing one of these characters, you select the highlighted IntelliSense member. Usually, I just use space or dot (.) but there are many more options, and I had no idea!

Neat stuff

I provide a canonical list of the options that I always forget are in here, but that I have to use frequently. Right now, they probably won't make a lot of sense, but you may remember them when you need them later.

  • To implement a new source control provider, first install the package (for instance, Turtle for CodePlex's SVN implementation, or Team System) and then go to Source Control in Options to pick the one you want to use. Just one at a time!

  • Many people recommend that you store your projects in a short file path, like c:Projects. You can change where you store projects in the Projects and Solutions section in the options dialog box.

  • Specify which browser you are coding your HTML for in the Text Editor / HTML / Validation section of the Options dialog box.

  • Set up automatic Windows Forms data binding in the Designer for custom controls (that you have bought or built) in the Windows Forms Designer / Data UI Customization section of the Options dialog box.

  • If you are one of those crazy people who think table names should not be pluralized, you can turn off that behavior in the Data Designer in the Database Tools / O/R Designer section of the Options dialog box.

  • You can teach Visual Studio to open a file with a given extension in a certain file editor using the Text Editor / File Extension section of the Options panel.

Using Snippets

Snippets are little bits of pre-coded logic that are meant to help you remember how to perform some standard code functions in various languages. In VB, for instance, you might not remember how to read from a file, so there is a snippet for that. In C#, you may want implement a property getter and setter, so you use a shortcut to get the snippet in place.

Using snippets

You can use a snippet in a few different ways, most of which are somewhat slow. The fastest way is through the use of key commands. To use a snippet this way, type its shortcut code and press Tab twice. For instance, try these steps:

  1. Open Visual Studio and start a new Class Library project in C#.

  2. In the new class that is created, place the cursor inside the curly braces.

  3. Type prop.

  4. Press Tab twice. Your results should look like the ones shown in Figure 3-2.

    See the template that is put into place? Int is highlighted. You can type over it.

  5. Type string and press Tab twice. Now MyProperty is highlighted.

  6. Type FirstName and press Enter twice.

    Now you have a finished automatically implemented property. It should look like this:

    public string FirstName {get; set; }
The automatically generated property snippet.

Figure 3-2. The automatically generated property snippet.

You can get to a snippet in other ways, including this one:

  1. Right-click at the insertion point.

    You have the option to select Insert Snippet.

  2. Click Insert Snippet.

    The full list of all the installed snippets appears at the insertion point.

  3. Click an item in the list, and the contents of that folder appear.

    Continue selecting categories (the menu extends to the right) until you have selected the snippet you were looking for.

  4. Double-click the snippet to insert it.

After they're inserted, populating the variables works just like the shortcut version.

Using surround snippets

Surround snippets are very cool. Have you ever written a few lines of code, and then realized that you should probably try and catch errors? You have to add a little code at the beginning, and then add a little code at the end, and then make sure the middle is in the right place. It's a pain.

Surround snippets are designed to solve that problem. They are normal snippets with a bit of logic in them that says "This part goes above the selection, and this part goes below the selection." If you want to handle errors for a section, you highlight that section, and the snippet will put the try before the selection and the catch at the end. To use a surround snippet, follow these steps:

  1. Highlight some code in the Code Designer.

  2. Press Ctrl+K,S to open the snippets menu.

  3. Select the appropriate snippet from the menu. You can choose the snippet that is right for whatever you are coding. Try prop for a property getter and setter.

  4. Set the various variables that Visual Studio prompts you.

The snippet will appear appropriately above and below the selected text. For instance, if I had this chunk of code:

for (int loopcounter = 1; loopcounter <= 10; loopcounter++)
{
     Console.WriteLine(string.Format("The number is {0}.",
   loopcounter));
}

and I felt that I needed a try ... catch block around it, I could highlight that code and do the preceding steps. If I select try from the menu, I will get this:

try
{
    for (int loopcounter = 1; loopcounter <= 10;
   loopcounter++)
    {
        Console.WriteLine(string.Format("The number is {0}.",
   loopcounter));
    }
}
catch (Exception)
{
     throw;
}

Exception is highlighted in green; I can tab to that and add the exception type I am expecting. It's a slick system.

Making snippets

Snippets are XML files that follow a format understood by Visual Studio. They include a Header and Snippet element. The Header includes a title, which is how the snippet is referred. The Snippet element, where all the work is done, includes a Code element, which has the code to be inserted.

The best way to make a new snippet is to modify an existing one. Snippets can be found in your Visual Studio install directory, which should be C:Program Files (x86)Microsoft Visual Studio 10.0VC#Snippets1033 if you are on a 64-bit operating system (otherwise you can drop the x86).

In the folder referenced in the preceding paragraph, let's look at a simple example: cw.snippet is a Console.Writeline command. Right-click the file to open it. Here's the code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
   <CodeSnippet Format="1.0.0">
    <Header>
         <Title>cw</Title>
         <Shortcut>cw</Shortcut>
         <Description>Code snippet for Console.WriteLine</Description>
         <Author>Microsoft Corporation</Author>
         <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
         </SnippetTypes>
      </Header>
      <Snippet>
         <Declarations>
            <Literal Editable="false">
               <ID>SystemConsole</ID>
               <Function>SimpleTypeName(global::System.Console)</Function>
            </Literal>
         </Declarations>
         <Code Language="csharp">
            <![CDATA[$SystemConsole$.WriteLine($end$);]]>
         </Code>
      </Snippet>
   </CodeSnippet>
</CodeSnippets>

This list describes what's in the Header element:

  • Title: Shows up on the context menu.

  • Shortcut: The key combination you can type for IntelliSense.

  • Description and Author: Show up in the tooltip when you mouse over the snippet in Visual Studio.

  • SnippetType: Defines which menus the snippet appears on. The most common types are Expansion and SurroundsWith. Expansion means that it inserts the text. SurroundsWith means that it's placed above and below the selection.

The Snippet element is where the work is done. In the cw.snippet example there are two elements in Snippet: Declarations and Code. Declarations declares the variables, and Code is what gets inserted. Within these, these statements are true:

  • The Literal element describes a variable that will be used in the creation of the snippet.

  • In this case, Function tries to get the simplest version of the System.Console namespace given the current constraints, and ID names it SystemConsole.

  • The Code element specifies the language and then puts the actual code in place.

Tip

If you want to make your own snippet, I suggest that you start with one of the samples provided in the Visual Studio install. You can just start from scratch too — if you wish, you can create an XML file and give it a .snippet file extension — but I think these things are best done iteratively.

Deploying snippets

To deploy a snippet of your own, use the Code Snippets Manager. The manager is found on the Tools menu and looks like the one shown in Figure 3-3.

The Code Snippets Manager.

Figure 3-3. The Code Snippets Manager.

Adding a new snippet this way is fairly simple. After you create your snippets file, click the Import button, and select the .snippet file. It's placed in the selected folder, so make sure you have the snippet folder highlighted.

The Add and Remove buttons in the Manager refer to directories, not files. Use them to make new snippet folders. The Search Online feature just searches Help for IntelliSense Code Snippets.

Sharing snippets

Sharing a snippet is a more complicated act than it should be. One would think that you could just create a .snippet file, send it to someone, and that would be that. It isn't so.

I should amend that — it is so if you are just sending it to a friend — then it is just a matter of using the Manager. On the other hand, if you are making a package of snippets for a group to install, you get to the nitty-gritty.

A snippet sharing escapade has three components:

  • The .snippet file itself: This topic is discussed in the preceding section.

  • The .vscontent file that lists the snippets (even if there is only one): The .vscontent file is one with a listing of snippets in a package. It consists of multiple Content elements that describe the various files in the package. For instance, here is the .vscontent file that would be used for the previous Console.Writeline example.

    <VSContent xmlns="http://schemas.microsoft.com/
       developer/vscontent/2010">
        <Content>
            <FileName>cw.snippet</FileName>
            <DisplayName>cw</DisplayName>
            <Description>Console.Writeline</Description>
            <FileContentType>Code Snippet</FileContentType>
            <ContentVersion>3.0</ContentVersion>
            <Attributes>
                <Attribute name="lang" value="csharp"/>
            </Attributes>
        </Content>
    </VSContent>
  • This gives you two files in the package — the snippet and the content file. These need to be packaged in a .vsi file, and then distributed.

  • The .vsi file to package it all together: The .vsi file is a Zip file with a new extension. To make it, literally zip your folder of snippets with the vscontent file and change the file extension from .zip to .vsi.

  • Visual Studio users can double-click .vsi files in order to have the vstudio installer handle them. The command line can also be used for more in-depth installs. The complexity of the system on the snippet developer side makes sense when you consider that the end user ends up with a better experience.

Hacking the Project Types

Throughout the book, I recommend that you not start with a blank screen. Click New Project and select a project type in order to get some basic set of code to start with. In C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDE, you find the files that make all the magic project types work.

Hacking Project templates

The first, most obvious target for hacking are the project types because they are text based and have a lot of useful information in them. Found in the IDE folder referenced in the preceding paragraph, the ProjectTemplates folder follows the hierarchy of the New Project tree view. (See Figure 3-4.)

A bunch of project-type Zips.

Figure 3-4. A bunch of project-type Zips.

I focus on the CSharp directory tree because this book is about C#. To keep examples to a minimum, open the Windows/1033 folder, in order to view Windows project types. In a default install, that looks something like this:

  • ClassLibrary

  • ConsoleApplication

  • EmptyProject

  • WindowsApplication

  • WindowsControlLibrary

  • WindowsService

  • WPFApplication

  • WPFBrowserApplication

  • WPFControlLibrary

  • WPFCustomControl

The explorer should look like Figure 3-4. The files are Zip files and should stay that way. The setup process for the development environment reads right from the Zips.

The ConsoleApplication is about the simplest project type, and it is a great place to begin creating your own. Open the ConsoleApplication zip and take a look at the four files it includes:

  • assemblyinfo.cs: This file goes directly into the project. Take a look at the code; it is the exact code that is in the assemblyinfo file in a project, except there are project-specific variables surrounded by dollar signs.

  • consoleapplication.csproj: This is the actual project file; the name will be replaced by the new project-creation process. As with the other included files, there are variable names within the XML of the file.

  • csConsoleApplication.vstemplate: This is the magic file that tells the project-creation process how to build the new project. The important part is the TemplateContent element, which contains the name of the ProjectFile and the ProjectItems that go into the finished product. This is clearly where you would put new files if you needed them.

  • program.cs: This is the default file for the application. This is where you begin when you start coding. Take a look at the code — it should look familiar.

So where does that leave you? You can change the projects. Try these steps:

  1. Copy the ConsoleApplication.zip from C:Program FilesMicrosoft Visual Studio 10.0Common7IDEProjectTemplatesCSharpWindows1033.

  2. Paste the file back into the folder — it should make ConsoleApplication – Copy.zip.

  3. Rename that file ConsoleAndClass.zip.

  4. Drag the new class to your desktop temporarily.

  5. Right-click and select Extract All from the menu. Select the defaults.

    A new ConsoleAndClass folder is created.

  6. Delete the ConsoleAndClass.zip file from your desktop.

  7. Open C:Program FilesMicrosoft Visual Studio 10.0Common7IDEProjectTemplatesCSharpWindows1033ClassLibrary.zip.

  8. Copy the class1.cs file from that compressed folder.

  9. Paste it back into the new ConsoleAndClass folder on your desktop.

  10. Right-click csConsoleApplication.vstemplate and select Edit from the menu to open the file in Notepad.

  11. In the file, change each instance of ConsoleApplication to ConsoleClassApplication.

  12. Add the bolded line to the file, in order to reference the new file.

    <?xml version="1.0" encoding="utf-8"?>
    <VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.
        microsoft.com/developer/vstemplate/2005">
      <TemplateData>
        <Name Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2320" />
        <Description Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2321" />
        <Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4548" />
        <TemplateID>Microsoft.CSharp.ConsoleClassApplication</TemplateID>
        <ProjectType>CSharp</ProjectType>
        <RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
        <SortOrder>70</SortOrder>
        <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
        <CreateNewFolder>true</CreateNewFolder>
        <DefaultName>ConsoleClassApplication</DefaultName>
        <ProvideDefaultName>true</ProvideDefaultName>
      </TemplateData>
      <TemplateContent>
        <Project File="ConsoleClassApplication.csproj"
        ReplaceParameters="true">
          <ProjectItem ReplaceParameters="true" TargetFileName="Properties
        AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
          <ProjectItem ReplaceParameters="true" OpenInEditor="true">Program.
        cs</ProjectItem>
          <ProjectItem ReplaceParameters="true" OpenInEditor="true">Class1.
        cs</ProjectItem>
        </Project>
      </TemplateContent>
    </VSTemplate>
  13. Save and close csConsoleApplication.vstemplate.

  14. Rename consoleapplication.csproj to consoleclassapplication.csproj.

  15. Close the folder, right-click its icon on your desktop, and click Send To / Compressed folder from the resulting menu in order to make a new ConsoleAndClass.zip folder.

  16. Copy the Zip file back to the original folder.

  17. Close Visual Studio if it is open.

  18. Open the Visual Studio Command Prompt as Administrator.

    (It is in the All Programs folder in the Start Bar, under Visual Studio 2010 / Visual Studio tools.)

  19. Run devenv /setup.

Now, when you open Visual Studio and click New Project, there should be a new project type, called Console And Class. Create a new project based on this type, and it will make you a Console .cs file and a class .cs file.

Hacking item templates

Items work the same way. Check into C:Program FilesMicrosoft Visual Studio 10.0Common7IDEItemTemplatesCSharp and you'll see the same set of items types that show in the Add New Item dialog box:

  • Code

  • Data

  • General

  • Office

  • Reporting

  • Silverlight

  • Web

  • Windows Forms

  • Workflow

  • WPF

If you dig into a directory through the Code/1033 folder, you will find more or less the same kinds of things you saw in the project templates in the preceding section. The templates are in Zip files (and have to stay that way). These files include a .vstemplate file that has the details Visual Studio needs. The files that go into the project are in there, too.

Yes, some of these item templates are duplicates of the items in the project templates. I don't like that, but I can't see any way around it.

Look in the Code/1033 folder. There is a Class.zip file that maintains the Class template, if you were to right-click a project name and select Add New Class. Suppose that you want to put the default comment block in here too. Here's what to do:

  1. Extract the Class.zip onto your desktop temporarily.

  2. Open the class1.cs file in Visual Studio.

  3. Add the bold lines to the file.

    The file in the project group looks like the following listing. To edit it, you just make a new line before the class declaration and type ///.

    using System;
    using System.Collections.Generic;
    $if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
    $endif$using System.Text;
    
    
    namespace $rootnamespace$
    {
        /// <summary>
        ///
        /// </summary>
       class $safeitemrootname$
       {
       }
    }
  4. Save the file and close Visual Studio.

  5. Zip the folder on your desktop by right-clicking the folder and choosing Send To/Compressed Folder from the resulting menu.

  6. Put the file back in C:Program FilesMicrosoft Visual Studio 10.0Common7IDEItemTemplatesCSharpCode1033.

  7. Open Visual Studio and make a new Class project.

  8. Right-click the project name and select Add

    Hacking item templates

    Keep the default name.

    Visual Studio makes a new file with the comment block, as shown in Figure 3-5.

    You've changed Visual Studio behavior — again!

    Figure 3-5. You've changed Visual Studio behavior — again!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.149.180