Sunday, December 26, 2010

Visual Studio 2010 Code Snippets

Code snippets are a great way to speed up development time. In this post I'll go through a simple way to create your own code snippets. I'll be creating a snippet to log to the 14\LOGS files.

Open a Visual Studio project and add a new xml file. Make sure to save it with a .snippet extension.

Right click in the new xml file,  select Insert Snippet and double click on snippet. The xml below will be inserted for you.



Fill in the values you would like for these tag. The most important is the shortcut - its what will start intellisence for you.
    <Title>SharePoint Logging</Title>
    <Author>Me</Author>
    <Shortcut>SPLog</Shortcut>
    <Description></Description>

Choose what type of snippet you want either SurroundsWith or Expansion, I'm using expansion here.
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>

Now enter what you would like to replace in instances of the snippet. Here the component name to be logged changes. If there are more replacements needed, add more Literal tags.
    <Declarations>
      <Literal>
        <ID>Component</ID>
        <Default>CustomComponent</Default>
      </Literal>
    </Declarations>

Change the code language to CSharp.
    <Code Language="CSharp">

Enter the code to be inserted in CDATA[ YOUR CODE GOES HERE  ]
  <![CDATA[
  SPDiagnosticsService.Local.WriteTrace(0,
                    new SPDiagnosticsCategory("$Component$", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
  ]]>


Save the snippet to the default location "C:\Users\Administrator\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets" and your ready to try your new snippet.

Completed snippet file
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>SharePoint Logging</Title>
    <Author>Me</Author>
    <Shortcut>SPLog</Shortcut>
    <Description></Description>
    <SnippetTypes>

      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>Component</ID>
        <Default>CustomComponent</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[
  SPDiagnosticsService.Local.WriteTrace(0,
      new SPDiagnosticsCategory("$Component$", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
  ]]>
    </Code>
  </Snippet>
</CodeSnippet>

No comments:

Post a Comment