Download The Code.msi Sample File.
Understanding The Role of Code Snippets
Visual Studio 2005 and Visual C # Express Edition Both Support A Technology Dubbed Code Snippets, Which Are The Foundation for Two Related Code-Generation Techniques:
Expansion Templates: The ability of the IDE to generate type definitions, member definitions, and common coding constructs Surround With IntelliSense:. The ability of the IDE to surround a group of selected code statements within a relevant coding construct.
All in all, code snippets technology exists for a single reason-developer productivity Expansion templates and Surround With IntelliSense enable developers to rapidly generate blocks of code using any of the following approaches.:
The Edit | IntelliSense Menu of The Ide Ide-Dependent Keyboard Shortcuts Context-Sensitive Mouse Right-Click Typing A Snippet's Registered Shortcut (as defined by a snippet's xml file)
An Expansion Template EXAMPLE
To illustrate the role of Expansion templates, assume you have created a C # class type (named SportsCar) and wish to quickly add a property with a related backing field. Rather than manually declaring the member variable and authoring the property syntax by hand, you can Activate The Property Expansion (Using Any of The Previously Mentioned Techniques) That Automates The entire process.
For example, place the mouse cursor within the scope of the type definition and select the Edit | IntelliSense | Insert Expansion menu item From the resulting list of choices, select property as shown in Figure 1 below..
Figure 1. Activating a code Expansion
Once this code snippet Has Been ActiVated, you will find the following property / field declaration within the sportscar type:
Private int myvar; public int myProperty
{
Get {return myvar;}
Set {myvar = value;}
}
As you can see, the expansion is intentionally generic. However, if you look a bit closer at the expansion in Figure 2, you will notice that the property and field each have their name and type highlighted in yellow rectangles.
Figure 2. Yellow highlighting is your cue to edit the skeleton expansion.
..................... ..
Edits cascade throughout the expansion as required. Thus, if you Tab to the field's type (int by default) and change it to a string, the property's type declaration is updated automatically when you Tab off the item. Likewise, if you Tab to the Field name (MyVar by default) and update it to _carcolor, The Get and set scopes of the associated property is updated Automatical AS Shown in Figure 3.
Figure 3. Sorting out the details of the 'Property' Code Expansion
A surround with intelliSense Example
Surround With IntelliSense is another example of code snippet technology. Like Expansion templates, Surround With IntelliSense technology also results in code generation. The distinction, however, is that Surround With IntelliSense based code snippets allows you to select a block of code statements before applying the Expansion.
To illustrate, assume you now wish to place the SportsCar type into a region using the C # #region / #endregion directives First, select the code statements to be wrapped within the region and activate the Edit |. IntelliSense | Surround With ... menu Selection (Fighe 4).
Figure 4. Selecting Statements for Surround With IntelliSenseFrom The Resulting List, Select #Region and Edit The Region's Name As you see FIT USING TAB COMPLETION.
Note Surround With IntelliSense Can Be Used Without Selecting A Set of Statements. If this is the code, the code snippet is simply generated verbatim.
A catalog of code snippets
Visual Studio 2005 and Visual C # 2005 Express Edition Define The Same Intrinsic Code Snippets. The Following Table Documents Some (But Not All) Common Surround with code snippets.
Surround With SnippetDefinition # if #regionThese options allow you to wrap code with various C # preprocessor directives do while foreach for -. Iteration by index Reverse for -. Iteration by index These options wrap code within various C # looping constructs if statement else Wraps a code block within if / else logic.lock Wraps a code block within a lock scope.namespace Wraps a collection of types (or namespaces) into a new namespace. Try Catch Try Finally Wraps a block of code within structured exception logic.UsingWraps a statement inside a C # 'Using Scope' to Ensure Object Disposal.
The next Table Documents Some (But not all) of the expansion templates provided by The Visual Studio 2005 And Visual C # 2005 Express Edition IDES.
Expansion Template SnippetDefinitionclass interface enum structThese options generate an empty type definition. Named Iterator / Indexer pairIterators are constructs that allow you to build custom collections that expose their sub-objects using an array like index syntax. Basic attribute implementation Creates a new custom .NET attribute definition (according to best practices) .Destructor Stubs out a C # destructor (which is an overridden System.Object.Finalize in disguise) .Exception typeCreates a definition for a custom exception (according to best practices). Override System.Object.EqualsOverrides the virtual Equals () method inherited from System.Object. Property PropertygDefines a read / write property (property) or read-only property definition (propertyg) .Now, despite what you may be thinking, the remainder of this article will not illustrate the use Of Each Code Snippet. I am Quite Sure You Are Able To Investigate Each Option At Your Leisure.
What I will do is examine how a code snippet is composed under the hood. Once this is understood, you will learn how to create and register your own custom code snippets for use by Visual Studio 2005 and Visual C # 2005 Express Edition.
Locating Predefined Code Snippet Files
If you have been working with the .NET platform for any length of time, it should come as no surprise that code snippets are represented using XML (these days, what is not expressed as XML). Each code snippet is stored in a unique * .xml file, located by Default Under:
Note This path is based on beta versions of Visual Studio 2005 / Visual C # 2005 Express Edition. If you are unable to locate the Expansions folder as listed above, simply search your machine for a file namedclass.xml. Assuming the name of this file has NOT CHANGED, You Should Be in Good Shape.
Code Snippets under the hood
. Now that you have (hopefully) located the * .xml files that represent the default code snippets, let's have a look at the details Open the class.xml file, which is responsible for inserting a new class definition:
XML Version = "1.0" encoding = "UTF-8"?>
Snippettypes>
Header>
Literal>
Declarations>
{
$ SELECTED $$ End $
}]]>
Code>
Snippet>
CODESNIPPET>
The root element for any code snippet is appropriately named
The
The
Just to make sure you understand how these sub-elements are used within Visual Studio, activate the #region code snippet. Now, try to identify where the
Figure 5. The
Note Code Snippet Technology Is The Foundation for Refactoring Support Withnin A Microsoft IDE. To Learn More About Refactoring Technology, Consult The Following
Article.
The
The
The
Literal>
Declarations>
.
Again, Just to Be Sure You CAN Map There Elements to the IDE, Ponder Figure 6, Which Shows The Result of The Class Snippet Expansion.
Figure 6. The
The Element
Finally, we need to address the role of the sub-element defined within
Element for the class.xml code snippet:
{
$ SELECTED $$ End $
}]]>
Code>
Notice the various names sandwiched by $ tokens (such as $ name $). This syntax is used to reference the variables defined within a
Also note that the $ name $ token is referring to the name
Building Custom Code Snippets
If you are an XML superstar, the previous section should be about all you need to define your custom code snippets (of course, I have not yet described how to register custom code snippets with Visual Studio, so keep reading). However, for those Of you wish to see Some Concrete Examples, Allow Me To Present a Few Custom Snippets Example Your Workday Productivity To Some Extent:
The New Type Instant Expansion The New Web Method Expansion The Disposable Type Expansion
If you wish to quickly leverage these code snippets, simply copy and paste the following XML documents into an appropriately named * .xml file. The final section of this article will explain how to register custom code snippets with the Visual Studio 2005 and Visual C # 2005 Express Edition IDs.building The New Type Instant Expansion
The First Code Snippet We Will Create, Newobj, Is Responsible for Generating The Following C # Statement (Shown In Pseudo-Code):
[TypeName] = new [typename] ();
The [typeName] placeholder will be controlled by a
Figure 7. The Newobj Code Snippet in Action
Create a new xml docuument (newobj.xml) and enter the folowing:
XML Version = "1.0" encoding = "UTF-8"?>
Description>
Snippettypes>
Header>
Literal>
Literal>
Declarations>
Code>
Snippet>
CODESNIPPET>
. The current version of newobj.xml generates code that triggers the type's default (no argument) constructor One enhancement you could make is to add a third
Literal>
We could the update Our CData Section As SO:
Code>
The End Result Is That We Have PROVIDED A TAB-REACHABLE PLACEHOLDER WHERE CONSTRUCTOR ARGUMENTS Can Be Manually Entered Like The One Shown in Figure 8.
Figure 8. The Improved Newobj Code Snippet
Building the New WebMMETHOD EXPANSION
When you are building XML Web Services using the .NET platform, the almighty [WebMethod] attribute does a vast majority of the hard work. As you know, each public method adorned with [WebMethod] can be reached using HTTP requests and return its value Like XML Data REPRESENTATION. In The SimpleSt Format, [WebMethod] Takes No Arguments:
[WebMethod]
Public Sportscar getNewcar ()
{
Return new sportscar ();
}
However, The [WebMethod] Attribute Can take A Number of Optional Named Parameters, One of Which IS Description:
[WebMethod (Description = "this method returns a new sportscar"]
Public Sportscar getNewcar ()
{
Return new sportscar ();
}
Given this, our next code snippet, newWM, will account for the Description named parameter, as well as
If You Followed The Logic Behind The Previous Code Snippet, The Contents of NewWebMethod.xml Should Be straightforward:
XML Version = "1.0" encoding = "UTF-8"?>
Description>
Snippettypes>
Header>
Literal>
Literal>
Literal>
Declarations>
[WebMethod (Description = "$ desc $")]]
Public $ RETVAL $ MethodName $ ()
{
$ END $
}
]]]]
Code>
Snippet>
CODESNIPPET>
Note to Compile the Source Code generated by the
NewWM Expansion, Your Project Will Need To Reference The System.Web.Services.dll Assembly. The C # Source Code File Will Also Need To Specify It Isusing To
System.Web.Services namespace.
Building the disposable type expansion
Code snippets can expand to as much code as you feel is necessary. For example, the Exception Type expansion generates an entire class deriving from System.ApplicationException that conforms to .NET best practices. The Basic attribute implementation code snippet expands to a new System. Attribute Derived Type (Also Constructed Acording to .Net Best Practices).
In a similar vein, we will wrap up our examination of building an Expansion template that is responsible for building a disposable type As you may know, when you are creating a type that interacts with unmanaged resources, best practice dictates that you.:
. Implement the IDisposable interface The object user should (ideally) call the defined Dispose () method to release any unmanaged resources Override System.Object.Finalize:. If the object user forgets to call the Dispose () method, the CLR garbage collector will Call The Type's Destructor.
The DispClass Code Snippet Will Build Such A Type, Shown ActiVated In Figure 10.
Figure 10. The Dispclass Code Snippet in Action
Here is The XML, Which I Would Guess Requires No Comment At this point.
XML Version = "1.0" encoding = "UTF-8"?>
Description>
Snippettypes> header>
Literal>
Declarations>
{
~ $ ClassName $ ()
{
Cleanup (false);
}
Public void dispose ()
{
Cleanup (TRUE);
Gc.suppressFinalize (this);
}
Protected void cleanup (bool disposing)
{
IF (Disposing)
{
// free Other State (Managed Objects).
}
// free your owN state (unmanaged objects).
// set large fields to null.
}
}]]>
Code>
Snippet>
CODESNIPPET>
About $ SELECTED $
Each of the expansions we have create, beelong to the expansion snippet category:
Snippettypes>
If the
For the sake of illustration, here is a simple example of using the $ selected $ token to wrap selected code statements in a defining scope (note that this snippet belongs to the Expansion and SurroundsWith categories):
XML Version = "1.0" encoding = "UTF-8"?>
Description>
Snippettypes>
Header>
{
$ SELECTED $ END $
}]]>
Code>
Snippet>
CODESNIPPET>
Again, this example is purely illustrative given that we do not gain much by grouping code within a dummy scope. Nevertheless, when you are building custom code snippets, remember that the $ selected $ token allows you to capture the current selection within the IDE .
Registering Custom Code Snippets
Now That WE Have A Set of Custom Code Snippets, We need to advertise. Luckily for us, Visual Studio 2005 and Visual C # 2005 Express Edition Share Common Approaches to do so.
First Of All, You Could To Simply Copy Your * .xml Files To The Directory Containing The Out of the Box Code Expansion Files As Shown In Figure 11.
Figure 11. Registering Custom Code Snippets in The Default Expansions Folder
IF You Follow this Approach, You Will See Your Custom CODE SNIPPPEAR ALPHABETICLY WITHIN THE Related Context Menu, Shown in Figure 12.
Figure 12. Accessing Our code Snippets through intelliSense
The other approach is to create a specific folder for your code snippets (for example, C: / MySnips) and register this location using the Tools | Code Snippet Manager menu selection Once activated, you are presented with a dialog box like Figure 13 that. Allows You to Specify Alternative Folders (Using The Add Button) That Contain Your XML Documents.
Figure 13. Registering a CUSTOM SNIPPet location
Note As suggested by Figure 13, the
Figure 14. SELECTING THE CUSTOM LOCATION
Once You Do, You Will See your snippets Appear as expected.
Figure 15. SELECTING THE CUSTOM SNIPPET (in The Custom location)
Now that you have learned the basic lay of the land, you should be in a good position to build any code expansion you may require. As a logical next step, read over the snippets that ship with your Microsoft IDE to further your understanding. Happy Coding!
Summary
Visual Studio 2005 and Visual C # 2005 Express Edition each ship with a set of predefined code snippets. Snippets are authored using a small set of XML elements and are used to quickly generate code for common tasks. In addition to leveraging the supplied code snippets, developers .