ARTICLE

How to Create Code Snippet Using C#

Posted by Ravindra T C Articles | Visual Studio 2010 February 24, 2012
In this article I will discuss how to create a code snippet.
Reader Level:

In this article I will discuss how to create a code snippet. 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.

Fallow the steps to create a code snippet using Visual Studio 2010.

CodeSnpt1.gif

Default Blank XML:

CodeSnpt2.gif

Default snippet generated XML tags:

CodeSnpt3.gif

Modified XML tags.

Add the SQL Connection Code to ![CDATA[]]

<?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>Ravindra</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[
           SqlConnection con = new SqlConnection();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "";
                cmd.Parameters.AddWithValue("", "");
                cmd.Parameters.AddWithValue("", "");
                cmd.Parameters.AddWithValue("", "");
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
 
                throw;
            }
            finally
            {
                con.Close();
            }
]]>
    </
Code>
  </
Snippet>
</
CodeSnippet>

Snippet IntelliSense

CodeSnpt4.gif

Snippet generated C# code

CodeSnpt5.gif
 

Login to add your contents and source code to this article
comments
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter