Results 1 to 9 of 9

Thread: How to use Code Snippets

  1. #1

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    How to use Code Snippets

    Hello,

    The intention of this submission is to illustrate how you can use the built in code snippets capabilities within Visual Studio 2005.

    What are code snippets?

    To give an example, type:

    prop

    and then hit the Tab Key twice. This will generate the following result:



    As you can see, this has generated both the private member and the public property. It is then possible to Tab through the areas highlighted in green to make the required modifications to make this definition into what you want. Any changes you make to the type of the private member will be reflected in the public property. I have found this particular code snippet very useful!!

    There are a number of different code snippets available within Visual Studio, but it is also possible to create your own ones.

    Do you ever find yourself writing the same code over and over again? I know I did when I was creating my website, especially when creating connections to a database, so I decided to create my own code snippet for this purpose.

    Typically, the built-in code snippets are located at:

    C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#

    But you can check this using Tools | Code Snippets Manager. Using this window, you can also find the location to store your custom snippets by clicking on "My Code Snippets", shown here:



    A code snippet file, is an xml file that adheres to a standard schema, and the easiest way to create your own, is to look at an existing example. Here is the snippet used in the prop snippet I described earlier, and you can find it in the folder mentioned above:

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    	<CodeSnippet Format="1.0.0">
    		<Header>
    			<Title>prop</Title>
    			<Shortcut>prop</Shortcut>
    			<Description>Code snippet for property and backing field</Description>
    			<Author>Microsoft Corporation</Author>
    			<SnippetTypes>
    				<SnippetType>Expansion</SnippetType>
    			</SnippetTypes>
    		</Header>
    		<Snippet>
    			<Declarations>
    				<Literal>
    					<ID>type</ID>
    					<ToolTip>Property type</ToolTip>
    					<Default>int</Default>
    				</Literal>
    				<Literal>
    					<ID>property</ID>
    					<ToolTip>Property name</ToolTip>
    					<Default>MyProperty</Default>
    				</Literal>
    				<Literal>
    					<ID>field</ID>
    					<ToolTip>The variable backing this property</ToolTip>
    					<Default>myVar</Default>
    				</Literal>
    			</Declarations>
    			<Code Language="csharp"><![CDATA[private $type$ $field$;
    
    	public $type$ $property$
    	{
    		get { return $field$;}
    		set { $field$ = value;}
    	}
    	$end$]]>
    			</Code>
    		</Snippet>
    	</CodeSnippet>
    </CodeSnippets>
    What I would like to achieve is a code snippet that will generate the following code:

    Code:
                using (SqlConnection cn = new SqlConnection(this.ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("ARTICLES_InsertCategory", cn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                    }
                }
    The easiest way to achieve this is to take the code that you want and place it into the "Code" node in the above prop sample xml file and then start to modify it.

    The things that I want to be able to change include the type of connection that is used, the connection string, the type of command used, the actual command text, and the CommandType definition. The reason that I want to have this flexibility is because I use both SQL and MySQL. However, it is possible to set up default values, so these can be set up to be the one that you use most often.

    You need to have a literal node for each part of the code that you want to change using the snippet, it is possible to use the same literal in multiple places, however, only the first instance of it will be tabbable, all the others will be updated depending on what you type into the first one.

    The only other thing that you need to change in the xml file is the Title of the snippet, the shortcut for it, and the Author, and you are good to go.

    Save the new xml file in the location of "My Code Snippets", described earlier, and straight away you will be able to use the snippet.

    Here is the finalized version of my connection snippet:

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    	<CodeSnippet Format="1.0.0">
    		<Header>
    			<Title>conn</Title>
    			<Shortcut>conn</Shortcut>
    			<Description>Code snippet for creating connection and command</Description>
    			<Author>Gary Ewan Park</Author>
    			<SnippetTypes>
    				<SnippetType>Expansion</SnippetType>
    			</SnippetTypes>
    		</Header>
    		<Snippet>
    			<Declarations>
    				<Literal>
    					<ID>connectiontype</ID>
    					<ToolTip>What type of connection</ToolTip>
    					<Default>SqlConnection</Default>
    				</Literal>
    				<Literal>
    					<ID>commandtype</ID>
    					<ToolTip>What type of command</ToolTip>
    					<Default>SqlCommand</Default>
    				</Literal>
    				<Literal>
    					<ID>connectionstring</ID>
    					<ToolTip>The connection string to use for Connection Object</ToolTip>
    					<Default>this.ConnectionString</Default>
    				</Literal>
    				<Literal>
    					<ID>commandText</ID>
    					<ToolTip>The Text to be executed by the Command Object</ToolTip>
    					<Default>Command</Default>
    				</Literal>
    				<Literal>
    					<ID>commandobjecttype</ID>
    					<ToolTip>The Type of command object, i.e. StoredProcedure</ToolTip>
    					<Default>StoredProcedure</Default>
    				</Literal>
    			</Declarations>
    			<Code Language="csharp"><![CDATA[            using ($connectiontype$ cn = new $connectiontype$($connectionstring$))
                {
                    using ($commandtype$ cmd = new $commandtype$("$commandText$", cn))
                    {
                    cmd.CommandType = CommandType.$commandobjecttype$;
                    $end$
                    }
                }
    	]]>
    			</Code>
    		</Snippet>
    	</CodeSnippet>
    </CodeSnippets>
    You will notice that I have moved the $end$ tag of the above snippet to go after the CommandType declaration. The reason I did this, is that normally after using this snippet, straight away I want to start adding parameters, or open the connection.

    And this generates the following when I type conn into the IDE and hit Tab twice:



    I hope this makes sense, if not, please feel free to ask questions.

    Gary

  2. #2
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,123

    Re: How to use Code Snippets

    Pretty straightforward, upon reading your tutorial I have come up with this for adding singleton to my form objects.

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>Singleton</Title>
          <Shortcut>single</Shortcut>
          <Description>Code snippet for Singleton</Description>
          <Author>Rodelio M. Rodriguez</Author>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
        </Header>
        <Snippet>
          <Declarations>
            <Literal>
              <ID>form</ID>
              <ToolTip>The form</ToolTip>
              <Default>Form1</Default>
            </Literal>        
          </Declarations>
          <Code Language="csharp">
            <![CDATA[ private static $form$ instance = null;
                  public static $form$ Instance()
                  {
                      if (instance == null)
                      {
                          instance = new $form$();
                      }
                      return instance;
                  }
    	]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>
    The thing is, is there a way that would automatically fill-up the Literal form using the form name where the snippet is generated? I don't mind filling up the Literal but it would be better if it can take the name of the form where it is generated.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  3. #3

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: How to use Code Snippets

    Hey there,

    I am glad that it was helpful to you.

    I see what you are trying to do, but I am not aware of being able to do it. I have just done a quick google, but nothing immediately jumped out.

    I will keep looking though, and if I find anything I will post back.

    Gary

  4. #4

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: How to use Code Snippets

    Hey,

    I have done some digging aroung, and I think what you are asking for is possible using Code Snippet Functions.

    Have a look at the below, is that what you are after?

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>Singleton</Title>
          <Shortcut>single</Shortcut>
          <Description>Code snippet for Singleton</Description>
          <Author>Rodelio M. Rodriguez</Author>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
        </Header>
        <Snippet>
          <Declarations>
            <Literal>
              <ID>classname</ID>
              <ToolTip>The form</ToolTip>
              <Function>ClassName()</Function> 
              <Default>ClassNamePlaceholder</Default>
            </Literal>        
          </Declarations>
          <Code Language="csharp">
            <![CDATA[ private static $classname$ instance = null;
                  public static $classname$ Instance()
                  {
                      if (instance == null)
                      {
                          instance = new $classname$();
                      }
                      return instance;
                  }
    	]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>
    Hope that helps!!!

    Gary

  5. #5
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,123

    Re: How to use Code Snippets

    Wow, that's it! Thank you so much for taking time to look for it, it really is handy! Can't thank you enough but couldn't give you another rep.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  6. #6

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: How to use Code Snippets

    Ha ha, don't worry about it, I was happy to help, and it was something that I didn't know was possible either, so it was good to find it.

    Gary

  7. #7

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: How to use Code Snippets

    Hello,

    For additional useful Code Snippets, you might want to take a look at the following:

    http://blogs.msdn.com/b/dohollan/arc...1-release.aspx

    Very interesting to see that all of these Code Snippets are StyleCop compliant.

    Gary

  8. #8
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: How to use Code Snippets

    I'd like to add that there is an excellent code snippet editor available as an extension to VS2010. It's very easy to create your own snippets right within Visual Studio itself, no need to edit the XML manually I can't remember the exact name, but searching for 'code snippet editor' in the Extension Manager should be enough, I could only find one when I was looking for it.

  9. #9

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: How to use Code Snippets

    Hello Nick,

    Yes, this is very true. The one that I use is this one:

    http://visualstudiogallery.msdn.micr...B-FAEE50F68392

    This article was written a few years ago now, before Snippet Editors had made much of an impact, and it was necessary to do some things manually. It is still good to know about "how" things are done, but the available editors makes it much easier and quicker to get up and running with snippets.

    Gary

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width