Saturday 22 March 2014

How to Create Code Snippet Using VS2012?

            Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code during presentations. Instead of typing everything live, I find it far easier to simply add the code block by block using code snippets.

Follow the steps to create a code snippet using Visual Studio 2012.
Name should be *.snippet



Next you can create your Snippet code.



Here I've write Sql Code.




below sql sample code

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>SqlInsert</Title>
    <Author>Ram</Author>
    <Shortcut>SqlIns</Shortcut>
    <Description>Sql Connection</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>message</ID>
        <Default>my function</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[
           using( SqlConnection con = new SqlConnection())
           {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "";
                cmd.Parameters.AddWithValue("", "");
                cmd.Parameters.AddWithValue("", "");
                cmd.ExecuteNonQuery();
            }]]>
    </Code>
  </Snippet>
</CodeSnippet>

Click Tools--> Code snippets manager Or Click ctrl +K,B




Select My code Snippets then Click Import Button.


Select your snippet file.



Click Finish button.



Click ok button. check your Snippet code.


Type sqlIns and two times click TAB key.


Result of Snippet.




Some other way to also we can do Snippet



try it..