Free C# Snippets For All!

I think I had been developing for over 4 years, or so, in .net before truly figuring out snippets. If you haven’t used them before, now is the time. Snippets allow you to type in a quick couple letters and expand into a complete set of code that you can use. The great thing about them is they are customizable and super simple to build. While the snippets that ship with VS are great — see the “prop” snippet, there is a great deal that one can add.

Creating Your Own Snippets

First let’s try using an existing snippet. The “prop” snippet ships with VS 2008 and can be used by simply typing in “prop” on an empty line in code. Once you have typed in the snippet, hit the “tab” key twice, the snippet will expand into:

public int MyProperty { get; set; }

Notice, you get a nicely formatted little simple get and set statement. The “prop” snippet is great for building classes, as you can just tab tab away and your class will be built before you know it. What happens, however, if you are building a web page and your simple get and set methods lose their values every time you post the page back to the server?

In the case of aspx page variables, the general way of persisting data through postback is to use viewstate. For all you folks that are storing variables in hidden fields out there, this is for you. If you have an editor page for, let’s say, a user — and who hasn’t built one of these — you will most likely store a user id somewhere. The right way to go about this is not by storing it in a hiddenfield. For more reasons than I care to mention, let’s just assume that storing your data in viewstate is superior to hidden fields and get to the solution.

public long UserID {
	get {
		//get the viewstate variable and put it into an object variable
		object o = ViewState["_UserID"];
		
		//if the object is not null return the casted object
		if(o != null) {
			return (long)o;
		}
		
		//ok, we have no value, let's just return -1
		return -1;
	}
	set {
		//Set our value here.
		ViewState["_UserID"] = value;
	}	
}

So, as you can see we create a page level viewstate variable that will work across postbacks. The nice thing is the simplicity of using the variable, once it has been created. It is far more simple to type in “LoadAUserRecord(UserID);” then the multiple lines of code to check a hidden field’s value property. The problem with the viewstate property, the way I have created it, is how many lines it takes to write the property code. The snippet, then, will make our lives a bit easier.

Dissecting a Snippet

Your customized snippets are stored in “C:\Users\YourName\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets” by default. If you open up that directory, you will see a bunch of .snippet files. You can open them up directly in VS. You will notice that they are XML formatted and should appear to be pretty simple to edit.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propv</Title>
			<Shortcut>propv</Shortcut>
			<Description>Code snippet for setting up a page level ViewState Property</Description>
			<Author>Jason Janofsky</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Type</ToolTip>
					<Default>TypeName</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
				<Literal>
					<ID>DefaultReturn</ID>
					<ToolTip>Default Return</ToolTip>
					<Default>null</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp">
				<![CDATA[
			public $type$ $property$ {
				get {
					object o = ViewState["_$property$"];
					if(o != null) {
						return ($type$)o;
					}
					return $DefaultReturn$;
			}
			set {
				ViewState["_$property$"] = value;
			}	
			}
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

As you can see, you just create properties that will take values upon snippet expansion and decorate the variable names with a “$” character in front, and in back of, your property name. Simple eh? Once you have saved your snippet file into your snippet directory, it should be immediately available for use.

Some Snippets For You

So, while I have completely run amok building snippets for myself doing all sorts of DAL and CRUD code for myself, the code for that stuff is very much specialized for what I do on a daily basis.. not for what you do. I do, however, have some snippets that I use all the time that I have removed some customizing and left more open for your use.

propr – A Quick Request.Querystring Page Level Property

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propr</Title>
			<Shortcut>propr</Shortcut>
			<Description>Code snippet for setting up a page level Querystring Property</Description>
			<Author>Jason Janofsky</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Type</ToolTip>
					<Default>TypeName</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
				<Literal>
					<ID>DefaultReturn</ID>
					<ToolTip>Default Return</ToolTip>
					<Default>null</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp">
				<![CDATA[
			public $type$ rq$property$ {
				get {
					object o = Request.Querystring["$property$"];
					$type$ _$property$;
					if(o != null) {
						$type$.TryParse(o.ToString(), out _$property$);
					}
					return _$property$;
				}	
			}
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

propm – A Custom Class Variable with Lazy Loading Abilities

Tip: Lazy loading is the process of creating an object that does not fill itself up until you need it. If you have a large object with properties that contain other objects, it might be smarter not to fill up that property until you explicitly need it. Linq uses lazy loading to prevent too many database calls every time one pulls up an object.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propm</Title>
			<Shortcut>propm</Shortcut>
			<Description>Code snippet for setting up a private and public property with a lazy loader connection</Description>
			<Author>Jason Janofsky</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Type</ToolTip>
					<Default>TypeName</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
				<Literal>
					<ID>method</ID>
					<ToolTip>DB Method Name</ToolTip>
					<Default>GetByID</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp">
				<![CDATA[private $type$ _$property$;
			public $type$ $property$ {
				get {
					if(_$property$ == null) {
						Fill$property$();
					}
					return _$property$;
			}
			set {
				_$property$ = value;
			}	
			}
			public void Fill$property$() {
				_$property$ = 
			}
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

par – A Snippet For Quickly Adding Parameters and Values to DB Calls.

I usually use approximately the same name for my connections and, therefore, normally do not have the “connection” variable in there, my own snippet is hardcoded for “con” instead of “$Connection$”.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>par</Title>
			<Shortcut>par</Shortcut>
			<Description>Code snippet for an automatically setup command parameter addwithvalue</Description>
			<Author>Jason Janofsky</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>Connection</ID>
					<ToolTip>The name of your connection variable</ToolTip>
					<Default>Connection</Default>
				</Literal>
				<Literal>
					<ID>type</ID>
					<ToolTip>ParamName</ToolTip>
					<Default>string</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[$Connection$.Command.Parameters.AddWithValue("@$type$", $property$);$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

That’s It, But….

I would love to be let in on your favorite snippets, drop me a line and I will be happy to include your snippets on this article.

Advertisements

4 responses to this post.

  1. Personally I have changed the default prop snippet so that the default data type is string instead of int. I found myself having to alter it so much that I figured it made sense to have it as the default.

    Reply

  2. Posted by brennydoogles on March 3, 2010 at 1:00 am

    That is fantastic… I use prop all the time, but never realized it was a snippet. Is there a GUI way of setting them up as well?

    Reply

    • There are definitely GUI snippet editors out there, try: http://www.codeplex.com/snippy

      Reply

      • Posted by brennydoogles on March 3, 2010 at 4:06 am

        I will have to take a look at that. I wonder if there is an online repository of snippets anywhere that I could contribute to once I start making some. Also… I have a newish programming blog dealing with C# as well as a slew of other languages and I was wondering if you would mind occupying a slot in my blogroll. Your blog is very well written and informative, and I would love to send some traffic your way. If you want to check it out, my blog is at http://brennydoogles.wordpress.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: