Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


SSWUG

Reader rating:
Click here to read 2 comments about this article.
Article source: CoDe (2006 - Jan/Feb)


Article Pages:  1  2 3 - Next >


Having Fun with Code Snippets

Using code snippets can make it quick to add common code pieces to your application. Creating your own snippets allows you to create a library of custom code pieces and share them with other developers.

There are some pieces of code that you write over and over again. Some of these pieces make sense as standard components or standard methods, like logging or validation. Other pieces are more unique and cannot easily be made into standard methods, like Property procedures, For loops, or file input/output. For these types of code pieces, snippets are a perfect answer.

"
Inserting snippets into your code is quick and easy AND saves you from all of that typing!
"

This article demonstrates how you can insert existing code snippets into your application, how to build your own snippets, and how to use the open-source Snippet Editor.

Inserting Code Snippets

A code snippet is a pre-built commonly used intelligent piece of code, sometimes referred to as an expansion template, which you can easily insert into a code window within the Visual Studio Integrated Development Environment (IDE).

Most code snippets are either common programming constructs, such as For loops, or common programming tasks, such as calling the ExecuteReader method of a SQLCommand.

To insert a snippet into a code window, place the cursor where the snippet is to be inserted, right-click to display the context menu, and select Insert Snippet or type CTRL + K, then X. The Code Snippet Picker is then displayed for you to pick the desired snippet. To cancel the Code Snippet Picker, press the Esc key.

Snippets also have short cuts to minimize the steps required to access a snippet. To insert a snippet using the short cut, type in the short cut and press the Tab key. The short cut associated with a snippet is displayed in the tool tip of the Code Snippet Picker entry.

The snippets you have available depend on the language associated with the code window that has focus. If you are using Visual Basic, the Code Snippet Picker will appear as in Figure 1. Figure 2 shows the C# Code Snippet Picker. If you are in an XML code window, the Code Snippet Picker is as shown in Figure 3.

Click for a larger version of this image.

Figure 1: Visual Basic provides a comprehensive set of task-based code snippets for your use.

Click for a larger version of this image.

Figure 2: C# focuses on code snippets for common language constructs.

Click for a larger version of this image.

Figure 3: XML code snippets provide easy access to XML syntax.

Let’s look at some specific examples. Say you want to add a property to a class. You could type all of the code to create your private member variable (or backing variable) and then your property getter and setter. But a more efficient way would be to use the property code snippet.

To accomplish this task in C#, display the Code Snippet Picker and then select the Visual C# > prop context menu item. Or, instead of using the Code Snippet Picker, use the short cut by typing “prop” in the code window and then press the Tab key. (You may need to press the Tab key twice if the auto list members drop down is open.) The following code is automatically inserted into the code window.

private int myVar;

public int MyProperty
{
            get return myVar}
            set { myVar = value; }
}

The highlighted portions of the snippet are called replacements. Focus is moved to the first highlighted replacement, shown in a highlighted rectangle. All like-named replacements are shown with a dotted rectangle. Edits cascade through the expansion, so when you change the replacement, all like-named replacements are changed to match. Tab between the replacements to change each one as needed.

In this example, the focus is initially moved to the data type of the private member. If you change the int to string, the data type of the property is also changed to string.

Press the Tab key to move to the private member variable name replacement and change it. The other references to that replacement within the snippet are then changed. Press Tab again to move to the property name replacement and change it as well.

When you have finished, the code appears like this.

private string _LastName;

public string LastName
{
            get return _LastName}
            set { _LastName = value; }
}

Notice that the replacements remain highlighted, allowing you to tab through again and make further changes. As soon as you change anything else in the code window, the replacement highlights are removed and the code must be edited the old fashioned way.

To accomplish the same task in Visual Basic, display the Code Snippet Picker and then select Common Code Patterns, choose Properties and Procedures and then choose the Define a Property context menu item. Or, instead of using the Code Snippet Picker, access the short cut by typing “property” in the code window and then the pressing the Tab key.

The question mark (?) character is also available in Visual Basic to assist with inserting snippets. Type ? and press the Tab key to display the Code Snippet Picker. Or, type the first letter(s) of the snippet short cut, ? and then press the Tab key to display the list of short cuts. The tool tip for each short cut displays the name of the snippet.

When the property snippet is inserted into the code window, the following code is generated.

   Private newPropertyValue As Integer
   Public Property NewProperty() As Integer
      Get
         Return newPropertyValue
      End Get
      Set(ByVal value As Integer)
         newPropertyValue = value
      End Set
   End Property

In the Visual Basic case, all occurrences of the replacements are highlighted and the one with focus is shown with a rectangle. Press the Tab key to move between the replacements. As in the C# case, edits cascade through the expansion. So if you change the data type replacement for the private member variable to a string, the property data types will automatically be changed to a string as well.

Unlike C#, all occurrences of the replacement are highlighted in Visual Basic, not just the first one. And the replacement highlights will remain on for further editing until the code window is closed.

C# and XML snippets have one additional feature called Surround With snippets. These snippets allow you to surround existing code with a snippet.

For example, say that you write the following code:

// Build the array
string[] arr = new string[4] {"This","is", 
"a","test"};

string DisplayString=string.Empty;

DisplayString += arr[0];

MessageBox.Show(DisplayString);

But you really want a loop around the code that builds the display string. To insert the loop using a snippet, select the code that is to be within the loop, select Insert Snippet from the context menu and then select Visual C# > for from the Code Snippet Picker. Alternatively, you can select Surround With from the code window context menu and then select for from the list.

The resulting code is as follows:

for (int i = 0; i < length; i++)
{
DisplayString += arr[0]; 
}

Tab through the replacements to update them as needed and replace the arr[0] with arr[i] to complete the code.

If the snippet you insert requires a reference or import that you don’t currently have set, the snippet will automatically add the reference and import.

Inserting snippets into your code is quick and easy AND saves you from all of that typing!

&

By: Deborah Kurata

Deborah Kurata is cofounder of InStep Technologies Inc., a professional consulting firm that focuses on turning your business vision into reality using Microsoft .NET technologies. She has over 15 years of experience in architecting, designing and developing successful applications.

Deborah is the author of several books, including Best Kept Secrets in .NET (Apress), Doing Objects in Visual Basic 6.0 (SAMS) and Doing Web Development: Client-Side Techniques (Apress). She is on the INETA Speaker’s Bureau, is a well-known speaker at technical conferences, and is a Microsoft Most Valuable Professional (MVP). After a hard day of coding and taking care of her family, Deborah enjoys blowing stuff up (on her XBox of course).

Some of the information in this article was obtained from her upcoming book, Doing Objects in VB 2005.

deborahk@insteptech.com

Fast Facts

Download the open source Snippet Editor from msdn.microsoft.com/vbasic.



Article Pages:  1  2 3 - Next Page: 'Managing Code Snippets' >>

Page 1: Having Fun with Code Snippets
Page 2: Managing Code Snippets
Page 3: Building Your Own Snippet

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.5 out of 5

15 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      Sharepoint TechCon

 

SSWUG