Monday, April 24, 2017

My favourite Visual Studio Snippets

It happens a fair bit: there’s a small identical piece of code that you have to need to include in each project you work on. Sometimes you can copy and paste from an old project or you simply write it from scratch. You do this over and over so much that you get used to writing it.

Fortunately, Visual Studio “snippets” can tame this monster. Simply type a keyword and hit tab twice and – bam! – code magically appears. But if you’re like me, the thought of deviating from your project to write a snippet can seem tedious. Lucky for you, you don’t have to write them, you can just borrow my favourite snippets.

vmbase

My vmbase snippet includes some common boilerplate code for INotifyPropertyChanged. It includes the SetField<T> method you may see in a few of my posts. After adding this snippet, be sure to decorate your class with INotifyPropertyChanged.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Base ViewModel implementation</Title>
            <Shortcut>vmbase</Shortcut>
            <Description>Inserts SetField and NotifyPropertyChanged</Description>
            <Author>BCook</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Imports>
                <Import>
                    <Namespace>System.Collections.Generic</Namespace>
                </Import>
                <Import>
                    <Namespace>System.ComponentModel</Namespace>
                </Import>
                <Import>
                    <Namespace>System.Runtime.CompilerServices</Namespace>
                </Import>

            </Imports>
            <Declarations>
            </Declarations>
            <Code Language="csharp"><![CDATA[
            protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
            {
                if (!EqualityComparer<T>.Default.Equals(field, value))
                {
                    field = value;
                    NotifyPropertyChanged(propertyName);
                    return true;
                }
                
                return false;
            }
            
            protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
            {
                var handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

propvm

The propvm snippet is similar to other “prop” snippets. It creates a property with a backing field and uses the SetField<T> method for raising property change notifications.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Define a Property with SetField</Title>
            <Shortcut>propvm</Shortcut>
            <Description>Code snippet for a ViewModel property</Description>
            <Author>Bryan Cook</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property Type</ToolTip>
                    <Default>string</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property Name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>Field Name</ToolTip>
                    <Default>myProperty</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[
private $type$ _$field$;

public $type$ $property$
{
    get { return _$field$; }
    set { SetField(ref _$field$, value); }
}
$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

propbp

Similar to the propdp snippet which creates WPF dependency properties, propbp creates a Xamarin.Form BindableProperty.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Define a Xamarin.Forms Bindable Property</Title>
            <Shortcut>propbp</Shortcut>
            <Description>Code snippet for Xamarin.Forms Bindable Property</Description>
            <Author>Bryan Cook</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Imports>
                <Import>
                    <Namespace>Xamarin.Forms</Namespace>
                </Import>
            </Imports>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property Type</ToolTip>
                    <Default>string</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property Name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>owner</ID>
                    <ToolTip>Owner Type for the BindableProperty</ToolTip>
                    <Default>object</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[
#region $property$
public static BindableProperty $property$Property =
    BindableProperty.Create(
        "$property$",
        typeof($type$),
        typeof($owner$),
        default($type$),
        defaultBindingMode: BindingMode.OneWay,
        propertyChanged: On$property$Changed);
        
private static void On$property$Changed(BindableObject sender, object oldValue, object newValue)
{
}
#endregion

public $type$ $property$
{
    get { return ($type$)GetValue($property$Property); }
    set { SetValue($property$Property, value); }
}

$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

testma

Visual Studio ships with a super helpful testm snippet which generates a MSTest test method for you. My simple testma snippet creates an asynchronous test method.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Async Test Method</Title>
            <Shortcut>testma</Shortcut>
            <Description>Inserts Test Method with async keyword</Description>
            <Author>BCook</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Imports>
                <Import>
                    <Namespace>Microsoft.VisualStudio.TestTools.UnitTesting</Namespace>
                </Import>
                <Import>
                    <Namespace>System.Threading.Tasks</Namespace>
                </Import>
            </Imports>
            <References>
                <Reference>
                    <Assembly>Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll</Assembly>
                </Reference>
            </References>        
            <Declarations>
                <Literal>
                    <ID>method</ID>
                    <ToolTip>MethodName</ToolTip>
                    <Default>TestMethodName</Default>
                </Literal>
                <Literal Editable="false">
                    <ID>TestMethod</ID>
                    <Function>SimpleTypeName(global::Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod)</Function>
                </Literal>                
            </Declarations>
            <Code Language="csharp"><![CDATA[
            [$TestMethod$]
            public async Task $method$()
            {
                // await ...
                Assert.Fail();
            }
            
$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Installing Snippets

To install the snippets:

  1. Copy/paste each snippet into a dedicated file on your hard-drive, eg propbp.snippet
  2. In Visual Studio, select Tools –> Code Snippets Manager
  3. Click the Import button
  4. Navigate to the location where you put the snippets
  5. Select one or more snippet files.
  6. Click Open and Ok.

To use them, simply type the keyword for the snippet (as defined in the ShortCut element in the snippet) and press the tab key twice.

Note: If you have resharper installed, the default tab/tab keyboard shortcut might not be enabled.

Any feedback is greatly welcomed.

Enjoy.

No comments:

Post a Comment