Creating Advanced Snippets:
Let's create some advance snippets.
We are going to convert the following code to snippet.
| public string UserName
{
get
{
if (!String.IsNullOrEmpty(_userName))
return _userName;
else return String.Empty;
}
set { _userName = value; }
}
|
Now let's see the XML file:
| <?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/
2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>String Property</Title>
</Header>
<Snippet>
<References>
<Reference>
<Assembly>System.dll</Assembly>
</Reference>
</References>
<Imports>
<Import>
<Namespace>System.Data.SqlClient</Namespace>
</Import>
</Imports>
<Declarations>
<Literal>
<ID>UserName</ID>
<Default>UserName</Default>
</Literal>
<Literal>
<ID>PrivateField</ID>
<Default>_userName</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
public string $UserName$
{
get
{
if (!String.IsNullOrEmpty($PrivateField$))
return $PrivateField$;
else return String.Empty;
}
set { _userName = value; }
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
|
All the XML files that I have included in this article are embedded in article and not available as a separate file. Simply copy and paste the above XML into a .snippet file and that's it.
Here is another XML file that allows you to return the DataSet.
| <?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/
2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>GetDataSet</Title>
</Header>
<Snippet>
<References>
<Reference>
<Assembly>System.dll</Assembly>
</Reference>
</References>
<Imports>
<Import>
<Namespace>System.Data.SqlClient</Namespace>
</Import>
</Imports>
<Declarations>
<Literal>
<ID>METHOD</ID>
<Default>BindData()</Default>
</Literal>
<Literal>
<ID>SQLCONNECTION</ID>
<Default>myConnection</Default>
</Literal>
<Literal>
<ID>CONNECTIONSTRING</ID>
<Default>ConnectionString</Default>
</Literal>
<Literal>
<ID>ADAPTER</ID>
<Default>ad</Default>
</Literal>
<Literal>
<ID>QUERY</ID>
<Default>query</Default>
</Literal>
<Literal>
<ID>QUERYTEXT</ID>
<Default>SELECT * FROM Categories</Default>
</Literal>
<Literal>
<ID>DATASET</ID>
<Default>ds</Default>
</Literal>
<Literal>
<ID>TABLENAME</ID>
<Default>Categories</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
private DataSet $METHOD$
{
// make the query
string $QUERY$ = "$QUERYTEXT$";
SqlConnection $SQLCONNECTION$ = new SqlConnection($CONNECTIONSTRING$);
SqlDataAdapter $ADAPTER$ = new SqlDataAdapter($QUERY$,$SQLCONNECTION$);
DataSet $DATASET$ = new DataSet();
$ADAPTER$.Fill($DATASET$,"$TABLENAME$");
return $DATASET$;
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
|
Try the above XML file and see what it generates.
So, you see making code snippets can really save you time. You can use it to create any snippets which you frequently use.
I hope you liked the article, happy coding!