Friday 13 January 2012

Adding snippets in Visual Studio

In this example I will create a snippet, that surrounds code block and makes it run with elevated privileges.

1. Go to

2. Create new text file, rename with .snippet extension
3. Open for edit in Notepad
4. Insert this code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>SPSecurity.RunWithElevatedPrivileges</Title>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    <Shortcut>spsec</Shortcut>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[SPSecurity.RunWithElevatedPrivileges(delegate
            {
                $selected$ $end$
            });]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

5. What you need to customize:
  • Title
  • Shortcut - this is how you use snippet
  • Language (XML, csharp, VB)
  • Code - insert it always between <![CDATA[ and ]]>
  • Put $selected$ where your surrounded code block should be
6. Save file
7. Test it:






This snippet is available here. And here is another link with snippet that adds two using blocks for SPSite and SPWeb.

More documentation on snippets: http://msdn.microsoft.com/en-us/library/ms171418.aspx

No comments:

Post a Comment