Creating Code Snippets

Sunday, 26 March 2006 15:03 by admin
My previous blog entry discusses the essentials on using Code Snippets to speed up your development. But as you would have noticed, not all snippets that are available would cater to your needs. In this scenario, you must create your own Code Snippets Library so that you can have snippets which are greatly customized for your development. Here I will discuss creating custom snippets. How does a snippet work? Well, this is the first question that we need to answer to fully understand the background processing that’s happening on code snippets. Code snippets are just xml’s. There is a proper format for you to follow. Here’s a sample code snippet: <?xml version="1.0" encoding="utf-8" ?> <CodeSnippet Format="1.0.0">   <Header>     <Title>class</Title>     <Shortcut>class</Shortcut>     <Description>Expansion snippet for class</Description>     <SnippetTypes>       <SnippetType>Expansion</SnippetType>       <SnippetType>SurroundsWith</SnippetType>     </SnippetTypes>   </Header>   <Snippet>     <Declarations>       <Literal default="true">         <ID>name</ID>         <ToolTip>Class name</ToolTip>         <Default>MyClass</Default>       </Literal>     </Declarations>    <Code Language="csharp" Format="CData">     <![CDATA[class $name$     {       $selected$$end$     }]]>    </Code>   </Snippet> </CodeSnippet> Let’s digest this sample bit by bit. The root element of a code snippet is the <CodeSnippet> tag. All declarations on your snippet must reside between the <CodeSnippet> tag. The <CodeSnippet> tag has two-key sub-elements. These are the <Header> and the <Snippet> tag. The <Header> tag contains the information of the snippet that is needed by the IDE. In our example it contains four tags:
  • <Title> – the title of the code snippet.
  • <Shortcut> - defines the shortcut of the class.
    • I kinda forgot to mention that you can directly type a shortcut for the code snippet and press tab to automatically insert it in your code.
  • <Description> - A proper description of your code snippet. It will be displayed when you browse your snippet in the intellisense.
  • <SnippetTypes> - specifies which category your snippet would appear. It could have up to three values. Expansion, SurroundsWith or Refractoring. A snippet could be in all of the three categories.
The <Snippet> tag is a little bit more complicated. This is where you’ll define your parameters and the code snippet itself. The <Snippet> tag has two sub-elements. These are:
  • <Declarations> - contains the editable or user-specified variables in the snippet. In the example:
    <Declarations>       <Literal default="true">         <ID>name</ID>         <ToolTip>Class name</ToolTip>         <Default>MyClass</Default>       </Literal>     </Declarations>   The snippet contains one parameter which is the “Class name”. You can specify as many parameters as you want.
  • <Code> - this tag contains the specific code to insert. Let’s see the example:
   <Code Language="csharp" Format="CData">     <![CDATA[class $name$     {       $selected$$end$     }]]>    </Code> By looking at the code, you’ll notice three different-looking directives. The $name$, $selected$ and $end$. The $name$ directive is the ID of the parameter that you declared in the <Declarations> tag. This will tell the IDE that this is the place where the user must specify a value. The $selected$ directive represents the code that was selected prior to the insertion of the code snippet. This is pretty useful if your snippet will supports “SurroundsWith”. Lastly the $end$ directive is where your cursor would be located after the insertion of the code snippet.
By now, you can already create your own code snippet file. But how would you load it in Visual Studio? You can register your snippets by directly copying your file to the default location of all code snippets (C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#). But, if you want to create you own library then you’ll have to use the Code Snippet Manager (Tools->Code Snippet Manager). You can specify which folder the IDE would look for code snippets. Now that you have learned how to create code snippets, I would greatly advise to make use of this feature. It will definitely boost up your programming speed.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Using Code Snippets

Saturday, 25 March 2006 12:03 by admin

Visual Studio 2005 offers a great IDE for improving your coding speeds. One if the feature that would definitely boost your speed up is the Code Snippet.

Code Snippets are pieces of code that you can automatically insert in your source code to avoid redundant coding.

To insert code snippets on your code, simply right-click on the editor and choose insert snippet.

You will then be prompted to choose from the library of snippets that you have. If you’re asking on how you could create your own directory of snippets, I’ll be discussing it on a seperate article.

After choosing the snippet library you will then get the list of available snippets for that library. Lets try selecting the “for” snippet.

By selecting a snippet, a code then is automatically generated. Plus the generated code would highlight the thing that needs editing.

Another cool feature of code snippets is its ability to wrap your code with a snippet. For example you have this code:

DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col1");
DataRow dr = dt.NewRow();
...

And then you realize that you must place this in a reverse for-loop. You can do it easily by using “Surround With”. To do this, just highlight the code, then right click and select “Surround With”

Just like using code-snippets, you’ll also be prompted to select the code-snippet to wrap this code.

Let’s try selecting a reverse for-loop.

Voila! Your code now is wrapped with a reverse for-loop statement.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Indexers

Thursday, 23 March 2006 10:03 by admin

I had just a run-in-review with this feature when my friend asked me how to enable your class to contain “angle bars []” to return a value from his class, much like an array. Well, the proper way of doing this is to use Indexers in your class.

Indexers works internally like a property. You need to specify its get and set routines to retrieve and give values to your indexed class. Here’s a sample to give you a clearer image on what I’m saying:

class IndexerClass{
    private int[] arr = new int[100];
    public int this[int index]   // Indexer declaration {
        get {
            // Check the index limits.
            if (index < 0 || index >= 100) {
                return 0;
            } else {
                return arr[index];
            }
        } set {
            if (!(index < 0 || index >= 100)) {
                arr[index] = value;
            }
        }
    }
}

class MainClass {
    static void Main() {
        IndexerClass test = new IndexerClass();
        // Call the indexer to initialize the elements #3 and #5.
        test[3] = 256;
        test[5] = 1024;
        for (int i = 0; i <= 10; i++) {
            System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
        }
    }
}

Note: sample taken from the MSDN documentation.

The highlighted text in the sample shows you how you declare an Index in your class. It’s pretty quite self-explanatory. For reasons of to be able to make this blog longer, I’ll explain some bits on the code.

The first you’ll notice is the use of the this keyword. The this keyword indicates the current class that you are in, you must use the this keyword to specify a property-like index in your class. The second is the angle brackets, here you’ll specify the index itself. In the example, it uses an integer as an index. Well, virtually you can specify any type that you want inside your index. It can be a string or a double. The third part that you’ll notice is the get and set routine. As I explained earlier it works just like a property. The get routine specifies whenever the user gets the value of your index. The set routine enables you to trap whenever the user gives a value to your index. In your set routine, you would notice another keyword, the value keyword. This variable contains the value that the user is giving to your indexed class.

indexerClass[0] = “test” // the value variable would contain “test”

Well I guess that’s all the essential part of indexed class.

You might be wondering on what practical use indexed class would be. Well, for starters, it would be very useful if you would have dynamic properties. Instead of exposing a getValue() function, its more readable and easier if you’ll provide an index to your class. A perfect example of this is the DataReader and DataRow class of ADO .Net. It uses indexes to access values in your fields in a row in the database.

SqlDataReader reader = command.ExecuteReader();
int empId = (int) reader[“Id”];

Happy Indexing!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed