n the first article of this two-part Visual Studio Snippets series, I introduced snippets, how to use them, and how to create your own, as well as packaging them for distribution. This time, I’ll show you some real-world examples by taking 10 existing code clips from DevX and FreeVBCode and converting them to snippets that you can use in Visual Studio 2005; for the first two, I’ll walk you through the conversion process.
As a brief review, snippet files are simply well formed and valid XML files with a .snippet extension stored in a location that must be registered with the Snippet Manager in Visual Studio (VS). To distribute snippets, you must include an XML manifest file with a .vscontent extension that describes the snippet. Finally, you zip both files into a ZIP archive with the extension changed to .vsi so that the Visual Studio Community Content Installer will process the snippets correctly.
You can create your snippets in any XML IDE. Both MSDN and GotDotNet have a beta-ready Visual Basic .NET snippet editor that you can download here. Note the download is available only as a collection of source files, so you will have to compile it yourself unless you don’t want to actually install it. I’ve also included a blank template snippet file (template_snippet.snippet) in the downloadable code that accompanies this article. You can use that template to get started.
Snippetizing Your Code
Before getting started, you need to understand that you must complete the header elements for each snippet so that the Snippets Manager applet will recognize and display your snippets properly. The header elements for each snippet include a title, author, a description, keywords for future searching features, and a “shortcut phrase” (which is one way to insert a snippet into your code). There is also a helpURL element that points to any online documentation available for a snippet.
The beginning of your snippets file should look like this, with each element’s value changed appropriately for your particular snippet.
Replace Last Occurence of a String Francesco Balena -- Snippetized by Michael Sanchez Replaces only the LAST occurrence of the SEARCH substring in the SOURCE. "replace" "string manipulation" replLastStr Help not available
Tip 1: Replacing the Last Occurrence of a Substring
As the first example tip, the following code (see the first article for more detail) replaces the last occurrence of a given string with a different string. You can place this snippet into a function that would accept three arguments; source, search and a replace string.
The original code I am putting into the snippet is,
Dim ReplaceLast As String ReplaceLast = StrReverse( _ Replace(StrReverse(Source), _ StrReverse(Search), _ StrReverse(ReplaceStr), , 1))
You can find the original tip on DevX here.
Creating Replaceable Parameters
After creating the header, you’ll need to make alterations to parameterized methods so that your snippets support variable parameters. So, to turn this into a snippet, begin by adding an opening
The first variable is “Source”?the string to search in, so create an
Your literal node should look like the following,
Source String Replace with the string to be checked. "Visit VB2TheMax.com and VB2TheMax.com"
The next variable parameter is “Search” which is the string to search for. Create a new
- An
element with a value of Search. Again, this value represents the highlighted replaceable parameter in the snippet and VS inserts it into the actual code with dollar signs. - A
element with a value of String to declare the data type for this replaceable parameter - A
element with a descriptive value. I used “Replace with the string to be searched for.” - A
element and value?I’ve used “VB2TheMax.”
This second
Search String Replace with the string to be searched for. "VB2TheMax"
Repeat the process with the final “replaceStr” variable, which is the string that should replace the Search variable. This third and final
ReplaceStr String Replace with the string that replaces the string searched for. "DevX"
With the three element. This is where you place the actual code, embedding the value of the
Within the element, add two attributes. First, the Language attribute with a value of “VB,” and then the Kind attribute with a value of “function body.” These attributes control when the snippet shows up in the Intellisense list. For example, if you were working in a C# project, and press CTL+K+X to display snippet Intellisense, this particular snippet would not appear, because the language is defined as VB.
The element contains your snippet source code, but because source code often includes characters that aren’t valid with XML, you need to wrap the code in a CDATA declaration, for example:
The CDATA tag tells the XML interpreter to not parse the code?to treat it as literal content. After creating the opening CDATA tag, paste in your code and replace the Source variable with $Source$, the Search variable with $Search$ and finally the ReplaceStr variable with $ReplaceStr$. This tells Visual Studio to replace those delimited items with the value of your
Your Code element should look like this:
After completing the element, close your
Save this file with a .snippet extension into the following folder, where
C:Documents and SettingsMy DocumentsVisual Studio 2005Code SnippetsVisual BasicMy Code Snippets.
You can actually store your snippets wherever you like, but you must register that folder with the Snippets Manager. You can do this by pressing CTL+K+B to open the manager, and then clicking the Add button to add a new folder.
Tip 2: Creating and Deleting Directories
This next snippet was chosen to show additional features supported in snippet files and it’s also an example of including multiple related snippets in a single file. This snippet contains three functions:
Imports System.IO Public Function CreateDirectory( _ ByVal FullPath As String) As Boolean Dim objDI As New DirectoryInfo(FullPath) Try objDI.Create() Return True Catch Return False End Try End Function Public Function CreateSubDirectory( _ ByVal ParentPath As String, _ ByVal NewSubDirectory As String) As Boolean Dim objDI As New DirectoryInfo(ParentPath) Try objDI.CreateSubdirectory(NewSubDirectory) Return True Catch Return False End Try End Function Public Function DeleteDirectory( _ ByVal FullPath As String) As Boolean Dim objDI As New DirectoryInfo(FullPath) Try objDI.Delete(True) Return True Catch Return False End Try End Function
You can find the original tip on FreeVBCode.
This snippet’s header elements have two keywords: “File System” and “Directories” and I’ve assigned a shortcut of “createDelDir.”
Begin by creating an opening
System.dll
The snippets also import the System.IO namespace, so below the closing tag, add an
System.IO
With references and imports taken care of, the remainder of the process is similar to the first example. Create a
The parameter FullPath is the physical path the snippet uses when creating the new directory. Create the following elements in a process that by now should begin to look familiar.
- An
element with a value of PhysPath. This value represents the highlighted replaceable parameter in the snippet and VS inserts it into the actual code with dollar signs. - A
element with a value of String, which declares the data type for this replaceable parameter. - A
element with a value of “Physical path to where you want to create a directory.” - A
element of “FullPath.” This will be inserted into your code wherever VS finds the value of the element.
Your
physPath String Physical path to where you want to create a directory FullPath
Next, create the object reference by adding an element. The element has the same child elements as the
Note that although all three functions in this snippet file reference the System.IO.DirectoryInfo object, you only have to add the element once, in the first snippet. The same rule applies to the
Now you can close the element. Add Language=”VB” and Kind=”function body” attribute/value pairs. The value of your
element will be the function code wrapped in a tag. Even though CDATA tells XML to not parse the characters within, Visual Studio parses the snippets upon insert, so it can process replaceable parameters delimited by dollar signs correctly.
Replace your variable reference with the value of your element should look like this,
With that completed, you can now close your first
I won’t bore you by repeating the process to create snippets out of the remaining tips. You can use these tips to practice the process of creating snippets from existing code, or simply download them with the rest of the sample code for this article and install them into Visual Studio, making them available for use in your projects.
Tip 3: Trimming Strings
The following line of code is a simple and compact way of trimming strings by using VB.NET’s new trimming functions. I chose this example because it can be turned into a cool little function where you can pass in the characters you want trimmed from a given string; a feature not available in VB6. You can find the original code here.
' S is the string to be trimmed. Dim cArr() As Char = { " ", Chr(9), Chr(13), Chr(10) } s = s.TrimStart(cArr)
Tip 4: Splitting Strings at Multiple Characters
This For Each loop and its declarations are a quick way to split string into substrings when the separator points may be any of a number of characters. This is good opportunity to take advantage of the declaration in your snippet file (hint: for the RegEx object). You can find the original code and explanation here.
Dim input As String = _ "This is{sep}my input string{sep}to test the " _ & "RegEx's{sep}Split method!" Dim output As String() = _ System.Text.RegularExpressions.Regex.Split( _ input, "{sep}") For Each token As String In output Debug.WriteLine(token) Next
Tip 5: Using the Clipboard Programmatically
The code displayed here shows you how to use the clipboard programmatically. I chose this one because it’s the first sample where the snippet is a complete sub procedure. You can view the original code here, along with an explanation of how to make the object you copied to it available after the program terminates.
Sub CopyFromTextBox(ByVal tb As TextBox) ' Copy the TextBox's selected text to ' the clipboard. Dim t As String = tb.SelectedText ' Copy the entire Text, if no text is selected. If t.Length = 0 Then t = tb.Text ' Proceed only if there is something to be copied. If t.Length > 0 Then Clipboard.SetDataObject(t) End If End Sub
Tip 6: Reverse For Each Loop
Here’s a For Each loop that iterates in reverse order, over any IEnumerable class. The snippet code is a complete class that’s simple to use. Be sure to check out the original code listing for an example.
Class ReverseIterator Implements IEnumerable ' a low-overhead ArrayList to store references Dim items As New ArrayList() Sub New(ByVal collection As IEnumerable) ' load all the items in the ArrayList, but in ' reverse order Dim o As Object For Each o In collection items.Insert(0, o) Next End Sub Public Function GetEnumerator() As _ System.Collections.IEnumerator Implements _ System.Collections.IEnumerable.GetEnumerator ' return the enumerator of the inner ArrayList Return items.GetEnumerator() End Function End Class
Tip 7: Check for SQL Server Database
This tip checks for the existence of a SQL Server database. While it may seem a little complex, just break it down by variables and objects and it will be as easy as the rest. It’s another good example of using the Object element in your snippet.
Function SQLDatabaseExists(ByVal objConnection As _ SqlConnection, ByVal strDatabaseName As String) _ As Boolean 'DEMO USAGE: ' Dim objConn As New SqlConnection _ ' ("data source=sqlservername;user " & _ "id=sa;password=mypassword;Initial " & _ "Catalog=master;Connection Timeout=120") ' objConn.open() ' Debug.WriteLine(SQLDatabaseExists( _ ' objConn, "MyDatabase")) ' objConn.Close() Dim objCommand As SqlCommand Dim i As Integer Try objCommand = New SqlCommand( _ "SELECT COUNT(*) FROM master..sysdatabases " & _ "WHERE [name]='" & strDatabaseName & "'", _ objConnection) i = objCommand.ExecuteScalar Return i > 0 Catch ex As Exception Throw ex End Try End Function
Tip 8. Retrieve a Named DataSet
I chose this function because it retrieves a named DataSet using C#, a language that I have not covered in these two snippet articles. Including it makes it pretty easy to see that snippets work the same way for C# as for VB.NET.
public System.Data.DataSet dsReturnedDataSetFrom( System.Data.SqlClient.SqlConnection sqlOpenConn, System.Data.SqlClient.SqlCommand TheSQLCommand, string TheQueriedTable, String TheDatasetName) { TheSQLCommand.Connection = sqlOpenConn; System.Data.SqlClient.SqlDataAdapter NewDA = new System.Data.SqlClient.SqlDataAdapter (TheSQLCommand); DataSet NewDS = new DataSet(); TheDatasetName.Trim(); NewDS.DataSetName=TheDatasetName; NewDA.Fill(NewDS, TheQueriedTable); NewDA.Dispose(); return NewDS; }
Tip 9: Export DataGrid to XML
This tip is a cool little ASP.NET function written in C# that exports the content of a DataGrid to an XML file and sends that to the client.
ArrayList al = new ArrayList(); for(int i=0;i<=10;i++) { al.Add(i+""); } DataGrid1.DataSource=al; DataGrid1.DataBind(); Response.Clear(); Response.AddHeader( "content-disposition", "fileattachment;filename=test.xml"); Response.ContentType="text/xml"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); DataGrid1.RenderControl(hw); Response.Write(sw.ToString()); Response.End();
Tip 10: Counting TreeView Nodes Recursively
In this final function the code sets up a recursive loop to count the number of checked nodes in a given TreeView.
' Return the number of checked nodes within any node ' of a TreeView Public Function CountCheckedNodes( _ ByVal rootNode As TreeNode) As Integer Dim count As Integer = 0 ' count the root node, if checked If rootNode.Checked Then count = 1 ' check the child nodes, by recursively calling ' this function Dim tvn As TreeNode For Each tvn In rootNode.Nodes count += CountCheckedNodes(tvn) Next Return count End Function
You can download and install the tips featured in this article as a preconfigured snippets file, giving you the option to separate the snippets you want into individual snippet files. If you don't want to install all the snippets in the file, here's how to remove the ones you don't want.
Each individual snippet is contained wholly within its own
After removing those, simply delete all the XML from the opening