Thursday, April 16th, 2009
at 11:54am
Trusted By

Welcome Back! I hope you enjoy the content on this site. If you have not done so already, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!
I initially published 5 Visual Studio c# Snippets yesterday and it got a lot of attention and had some positive feedback, so this is a follow up that I hope would be as helpful as the first one.
Reading an embedded resource as a stream
Specially when sending patches to customers, sometimes I need to embed an XML file that would contain some data that needs to be imported to the database in a compiled exe or dll to simplify the process for them. So I ended up creating a snippet on how to read an embedded resource
Shortcut: rembed
Sample Result:
Stream rulesReader = typeof(MyObject).Assembly.GetManifestResourceStream(
typeof(MyObject), "Resources.AttestationContratWorkflow.rules");
Customization:
- The type of the object to get the assembly from
- The name of the embedded resource
ViewState property
Even though I avoid using the viewstate as much as I can to keep the size of the page small but sometimes you really need to.
Shortcut: vstate
Sample Result:
public string Title
{
get
{
if (ViewState["Title"] == null)
return "My Title";
return (string)ViewState["Title"];
}
set
{
ViewState["Title"] = value;
}
}
Customization:
- The type of the property
- The name of the property
- The default return value
Null argument validation
I would say this is one of the basic best practices to have and to stick to. My Eiffel professor would be so proud of me
Shortcut: nparam
Sample Result:
if (context == null)
{
throw new ArgumentNullException("context ");
}
Customization:
- The name of the parameter
Info Message Box
This snippets shows an Information Message box.
Shortcut: ibox
Sample Result:
MessageBox.Show(this, "My Information Message", "Information...", MessageBoxButtons.OK,
MessageBoxIcon.Information);
Customization:
Error Message Box
Same as the previous snippet but shows an error message instead
Shortcut: ebox
Sample Result:
MessageBox.Show(this, "My Error Message", "Error...", MessageBoxButtons.OK,
MessageBoxIcon.Error);
Customization:
Download the snippets
Hope this helps!
Hatim
Digg This
Wednesday, April 15th, 2009
at 6:27pm
When working on a given project I always create Visual Studio snippets for repetitive tasks to save time and avoid mistakes. Of course each project has some specific requirements and therefore it’s not always the same code that is repeated.
The best snippets are the ones you would create yourself. But here are a few that I find are pretty generic and saved me sometime and hope you will find useful as well.
EventHandler
This snippet will create a generic event handler method. It’s pretty useful when working with ASP.Net controls and you don’t like to switch to the design view to then double click or go into properties of an element to generate the event handler by fear that the designer would mess something up.

Shortcut: evh
Sample Result:
void btnSubmit_Click(object sender, EventArgs e)
{
}
Customization:
- The name of the method
- The EventArgs type
OnEvent
This one is a no brainer, so I use it to save time and avoid forgetting to check if the event is null before raising it.
Shortcut: onevt
Sample Result:
protected void OnEvent(EventArgs args)
{
if (myEvent != null)
{
myEvent(this, args);
}
}
Customization:
- The name of the method
- The EventArgs type
- The Event to raise
Singleton Class
We all need a singleton class at one point or another in most of our projects. I think it’s the most used software pattern and so it deservers it’s own snippet. Oh, it’s thread safe
The implementation used is available here:
http://msdn.microsoft.com/en-us/library/ms998558.aspx
Shortcut: snglt
Sample Result:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
Customization:
SqlDataReader with Stored Procedure
We generate most of our Data Access code but for custom business requirements we end up creating specific stored procedures. So instead of copy/paste from another file I have created this snippet.
Shortcut: sqlproc
Sample Result:
using (SqlConnection sqlConnection = new SqlConnection(myConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand("myStoredProcedure",sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
#region params
//add your parameters here
#endregion
SqlDataReader dr = null;
try
{
sqlCommand.Connection.Open();
dr = sqlCommand.ExecuteReader();
while (dr.Read())
{
//do your mapping here
}
}
catch (SqlException)
{
//handle exception
}
finally
{
if (dr != null && !dr.IsClosed)
dr.Close();
if (sqlCommand.Connection.State != ConnectionState.Closed)
sqlCommand.Connection.Close();
}
}
}
Customization:
- Connection string
- Stored Procedure name
Serialize/Deserialize an object from an XML string
I can never remember the correct syntax for doing this and I am always looking at an other project to copy/paste this code so I ended up creating a snippet for it too.
Shortcut: serial
Sample Result:
public static List<MenuGroup> Deserialize(string strXml)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<MenuGroup>));
StringReader reader = new StringReader(strXml);
return (List<MenuGroup>)serializer.Deserialize(reader);
}
public static string Serialize(List<MenuGroup> items)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<MenuGroup>));
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
serializer.Serialize(writer, items);
return sb.ToString();
}
Customization:
Download the snippets.
To add this snippets to Visual Studio then Tools –> Code Snippets Manager … select Import… and browse to where you extracted the downloaded file.
Happy coding!
Hatim