Return To Sender


Straight up, the sender object that gets passed in as an argument in all .Net events kicks ass. If you already aren’t using it for copious amounts of cool stuff, you should be. Sender has so many uses it is truly silly. This article will demonstrate a couple of the common ones for your use.


Before the Code a Note


One of the few functionality items that vb.net has over c# is the handles language feature. On the .aspx page you create your linkbutton, etc. and on the code behind you simply select that object from your little drop down at the top of the page, select the event you want and away you go, you get a nicely formatted event handler for the click, or other event, of your control.


C#, on the other hand, requires us to write the handler events ourselves and reference them in our aspx code as well as code behind. Of course, one could throw up design view and, in the properties dialog, click the events button and double click an event to create a nicely formatted event, but who uses design view? I find design view insulting most days and only mildly annoying on other days; the last place I want to go to create my events is design view. Due to this little bugaboo, I write all my handlers myself. The problem with this is that sometimes I don’t know what the correct eventargs object is. My quick tip on this is that, if you don’t know what your eventargs object is, you can just throw in a junk reference, run your code locally and get a nice YSOD stating that your current eventargs object cannot be casted to the correct type of object. So, if anyone was ever wondering when a good time to purposely put an error in code…

//So, if you didn't remember that the eventargs object type for the
//rowdatabound event of a gridview was rowdataboundeventargs, throw down this:
protected void GridView1_RowDatabound(object sender, string e) {

}

//the error received will let you know the correct eventargs to use.


Less Read, More Code


A common issue one reads about is getting access to a gridviewrow from a linkbutton click inside that row. With sender, SIMPLE!

//Condensed
protected void linkbuttonInRow_Click(object sender, Eventargs e) {
GridViewRow gvr = (GridViewRow)(((linkbutton)sender).parent.parent);
}

//Simpler
protected void linkbuttonInRow_Click(object sender, Eventargs e) {
linkbutton lb = sender as linkbutton;

//in GridViewRows, going up two levels from controls in a cell will 
//give you a gridviewrow. In a repeater it's one level.
GridViewRow = (GridViewRow)lb.parent.parent;
}


How about if you have multiple linkbuttons on a page and they all do the same thing but you want to recognize which button the click came from:

protected void linkbuttonInRow_Click(object sender, Eventargs e) {
//I love using "as" in c#, makes me feel like I'm writing VB
Linkbutton lb = sender as linkbutton;

switch(lb.ID) {
case "button1":
response.write("Look I picked button 1 and didn't put a semicolon on this line because I am still digging on the vb")
break;
case "button2:
response.write("I picked button 2 and am now feeling the c# again.");
break;
}
}


If you can think of other super creative ways of using sender, let me know.

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.

Multi Presentation (tenancy) Websites for c#

So you want to build a single web application that can be used multiple times and deployed once? Have you ever built a site, only to have another customer request to have it replicated with some minor changes? One possibility is to copy the files into another directory, make changes as needed and deploy. Of course a month later your customer requests a bug fix or functionality changes to approximately the same file that now exists in two sites. Wouldn’t it be nice to have one set of files that you could change and have the change reflected on all your applications? Creating a multi presentation project might be for you.

In a Nutshell (the short version)

To make a fairly long story short, we will be creating an httpmodule that, upon being called checks to see if an application level variable for the application version has been set. If it finds that the application setting variable is null, the system will attempt to look up a record for itself inside the web.config file using the Request.URL.Host string. If the string exists as an app setting, we can grab the value (in this example I will store a numeric ID to pull up a database record for settings. Once you have your settings the only question is how to get all those sites pointed at the same set of files. To get this accomplished I use IIS to create multiple sites pointed at the same set of files with host header records to store what the incoming host name is for the site.

Let’s Break This Down…

Since this type of site takes some doing, lets go over the steps first:

  1. Create your project
  2. Create an CustomAppSettings class to store some basic information about the different versions of your site.
  3. Create a method to fill that CustomAppSettings class per site.
  4. Modify your site based on the version of the site your users have requested.
  5. Setup IIS to handle the different sites.

Create your project

There isn’t really anything tricky going on in the early stages here. Since we will be using the settings in our web.config file, go ahead and add a System.Configuration reference to your project. The System.Configuration reference will allow us to make calls to ConfigurationManager.AppSettings.
Adding the System.Configuration reference

Create an AppSettings class to store some basic information about the different versions of your site.

So now we want to create a class that will store some basic information like an application id, the site’s address, and any other settings that one might need for the application version to run independently of the other applications you will be hosting.

	public class CustomAppSettings
	{
		public int ID { get; set; }
		
		//This property will be to store the short name of our application version
		//for a template directory, if we choose to use one.
		public string ApplicationReference { get; set; }
		
		//This is the hostname our application is coming in on.
		public string HostName { get; set; }
	}	

This app settings class can be expanded significantly to include all sorts of specific settings like you would normally put in a single presentation project like SMTP servers, etc.

Create a method to fill that CustomAppSettings class per site.

We now need a method to store our CustomAppSettings into our Application object for easy access later. In a recent post (Storing User Information in Session for c#) I wrote up a class called GlobalVars that makes accessing untyped storage objects like Application and Session easier. For this project, let’s use the GlobalVars class to create a placeholder for our CustomAppSettings Object.

	public static class GlobalVars
	{
		public static CustomAppSettings CurrentAppSettings
		{
			get
			{
				object o = HttpContext.Current.Application["_CurrentAppSettings"];
				if (o != null)
				{
					//one could potentially do thier setting of the currentapp variable here
					//using the HTTPContext.Current object.
					return (CustomAppSettings)o;
				} 
				return null;
			}
		}
	}

With this code we can just type in GlobalVars.CurrentAppSettings.HostName to easily access our CurrentAppSettings whenever we need it.

The next part of this step is to get the CurrentAppSettings application level variable stored so it doesn’t return null all the time. To do this, we are going to create an httpmodule.

public class ConfigureApp : IHttpModule
{
	public void Dispose()
	{

	}

	public void Init(System.Web.HttpApplication context)
	{
		context.BeginRequest += context_BeginRequest;
	}

	public void context_BeginRequest(object sender, EventArgs e)
	{
		HttpApplication application = (HttpApplication)sender;
		Uri url = application.Context.Request.Url;

		//plug on the application setting the first time someone pulls up the app.
		if (CurrentAppSettings == null)
		{
			//check to see if our value exists in the web.config file.
			string config = ConfigurationManager.AppSettings[url.Host.ToString().ToLower()];
			
			//Setup a long variable for our try parse.
			long holderid = 1;
			if (!string.IsNullOrEmpty(config))
			{
				Int64.TryParse(config, out holderid);
				if (holderid <= 0)
				{
					holderid = 1;
				}
			}
			
			//this is where we would load our id from the db and set
			//the different settings.
			CurrentAppSettings = LoadMyApp(holderid);
		}
	}
}

While building the httpmodule you might have noticed that there is a call in there to the web.config. We actually need to make a couple different changes to the web.config file, first the reference to run the new httpmodule in our web app and, second, the application url references. Let’s take a look at those now.

Registering the http module

	<system.web>
		<httpModules>
		  <add name="ConfigureApp" type="ConfigureApp" />
		</httpModules>
	  </system.web>
	<system.webServer>
		<modules>
		  <add name="ConfigureApp" type="ConfigureApp" />
		</modules>
	</system.webServer>

Note that there are two different registrations here. The first is for iis6, the second for iis7. You will also note that the name and type both reference the name of our class from the http module.

Creating Our Application References

<configuration>
	<appSettings>
		<add key="MySite1.MyDomain.com" value="1"/>
		<add key="www.MySite1.MyDomain.com" value="1"/>
		<add key="MySite2.MyDomain.com" value="2"/>
		<add key="localhost" value="1"/>
	</appSettings>
</configuration>

We have added a few different settings into our appSettings section here to let the httpmodule know which app should point at which application. An important note here is that any individual host header record one makes into IIS needs to be entered here as, without it, the record won’t pull up from the web.config. You will also note that I have included a reference for “localhost”. If you are doing work on the different versions of the site in Visual Studio, the local web server will show up “localhost”. You can alter which version of the site you want to work on by changing the value of the localhost app setting.

Create the Site in IIS

We are on the home stretch now. Open up IIS and add a web site.
Adding a new web site
Note we are using a host header record here. Point your new web site to your file set and hit Ok. Your new web site will be up on that new host header record. To put up more sites on the same set of files, rinse and repeat!

AJAJ

I would just like to point out that I do not know anyone that writes Asynchronous Javascript And XML. What we should really be calling it is Asynchronous Javascript And Json or AJAJ.

Is anyone out there, that recently started a project still doing any async postbacks with XML?

Image Resizing and Cropping in C#

So the other day I put up a c# wrapper for ffmpeg. The wrapper I built is a part of my own asset storage system which I guess I will probably be putting up in chunks over the next few weeks. Today I have decided to put up my image resizing tools for your use.

Resize Now or Resize Later?

There are a couple theories to image resizing, should the image be resized at the point it gets uploaded, or at the point it gets sent out to the client?

Each method has advantages and disadvantages. Resizing at upload is good because it speeds up time to delivery as the processor has already done the resizing, additionally, the image is only resized once, vs. if the image is resized every time it is downloaded, it could be resized countless times. The problem with resizing at upload, however, is that it is now resized — you can’t un-resize it. Resizing at download then, is more processor intensive as it is resized every time someone requests a different size (one could probably get around some of this with caching, but the no matter how you slice it, it is still more processor intensive). The nice thing is that based on querystring or, however you pass the resizer data, you get a customized image size.

I have my own theory on this. If one has a ton of storage space (which most of us do have available to us now adays) it makes sense to resize in some basic sizes at upload while keeping the original as well for future resizing, if needed. Most good graphic designers break all their pages up into grids of magic 3rds anyways and would, generally, have ideas about their perfect image sizes for thumbnails, swatches, large previews, etc..

In another post I will detail how I get all of these different sizes and what not stored for use, but — for now — I will just give you the tools with which to do resizing and cropping in one spot.


//Overload for crop that default starts top left of the image.
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width)
{
	return CropImage(Image, Height, Width, 0,0);
}

//The crop image sub
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width, int StartAtX, int StartAtY)
{
	Image outimage;
	MemoryStream mm = null;
	try
	{
		//check the image height against our desired image height
		if (Image.Height < Height) {
			Height = Image.Height;
		}
		
		if (Image.Width < Width) {
			Width = Image.Width;
		}
		
		//create a bitmap window for cropping
		Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
		bmPhoto.SetResolution(72, 72);
		
		//create a new graphics object from our image and set properties
		Graphics grPhoto = Graphics.FromImage(bmPhoto);
		grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
		grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
		grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
		
		//now do the crop
		grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel);
		
		// Save out to memory and get an image from it to send back out the method.
		mm = new MemoryStream();
		bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
		Image.Dispose();
		bmPhoto.Dispose();
		grPhoto.Dispose();
		outimage = Image.FromStream(mm);

		return outimage;
	}
	catch (Exception ex)
	{
		throw new Exception("Error cropping image, the error was: " + ex.Message);
	}
}

//Hard resize attempts to resize as close as it can to the desired size and then crops the excess
public static System.Drawing.Image HardResizeImage(int Width, int Height, System.Drawing.Image Image)
{
	int width = Image.Width;
	int height = Image.Height;
	Image resized = null;
	if (Width > Height)
	{
		resized = ResizeImage(Width, Width, Image);
	}
	else
	{
		resized = ResizeImage(Height, Height, Image);
	}
	Image output = CropImage(resized, Height, Width);
	//return the original resized image
	return output;
}

//Image resizing
public static System.Drawing.Image ResizeImage(int maxWidth, int maxHeight, System.Drawing.Image Image)
{
	int width = Image.Width;
	int height = Image.Height;
	if (width > maxWidth || height > maxHeight)
	{
		//The flips are in here to prevent any embedded image thumbnails -- usually from cameras
		//from displaying as the thumbnail image later, in other words, we want a clean
		//resize, not a grainy one.
		Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
		Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);

		float ratio = 0;
		if (width > height)
		{
			ratio = (float)width / (float)height;
			width = maxWidth;
			height = Convert.ToInt32(Math.Round((float)width / ratio));
		}
		else
		{
			ratio = (float)height / (float)width;
			height = maxHeight;
			width = Convert.ToInt32(Math.Round((float)height / ratio));
		}

		//return the resized image
		return Image.GetThumbnailImage(width, height, null, IntPtr.Zero);
	}
	//return the original resized image
	return Image;
}

Extenders

Yesterday I posted on extenders after seeing this great post http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc. It strikes me that so much of what we do can be thrown into extenders. The code above, for example could really simply be used as extenders for you existing System.Drawing.Imaging objects.

public static string Crop(this System.Drawing.Imaging ThisImage, int maxHeight, int maxWidth)
{
    return CropImage(ThisImage, maxHeight, maxWidth);
}

public static string Resize(this System.Drawing.Imaging ThisImage, int Height, int Width)
{
    return ResizeImage(Width, Height, ThisImage);
}

public static string HardResize(this System.Drawing.Imaging ThisImage, int Height, int Width)
{
    return HardResizeImage(Width, Height, ThisImage);
}

More C# Extenders

Cool article today over at http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc about extenders. If you didn’t already know, extenders are static methods that work off the end of objects like special little hangars on. They are like little upgrades you get in a video game — like double jump in Shadow Complex.

Since I loved the article so much I figured I would add some of my collection to the list. I cannot take credit for all of these, as I have collected them over a long time — I might have written half of them.

DateTime

//The w3c string format is used for RSS feeds.
public static string ToW3CString(this DateTime ThisDate)
{
    //Return the datetime in the W3C standard format
    return String.Format("{0:yyyy-MM-ddTHH:mm:ss.fffzzz}", ThisDate);
}

public static DateTime FirstDayOfWeek(this DateTime dt) {
	int diff = dt.DayOfWeek - DayOfWeek.Sunday; 
	if (diff < 0) 
	{ 
			diff += 7; 
	} 
	return dt.AddDays(-1 * diff).Date;
}

public static DateTime LastDayOfWeek(this DateTime dt) {
	return dt.FirstDayOfWeek().AddDays(6);
}

Simple first and last day of week for a specific date. Like, for February 11, 2010 the first day of the week was the 7th.

DataTable

		
public static bool HasColumn(this IDataRecord dr, string columnName)
{	
	for (int i=0; i < dr.FieldCount; i++)
	{
		if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
			return true;        
	}
	return false;
}

Boy, this one has been sitting around for a while. A simple check to see if an untype dataset or table has a specific column.

Strings

//One could probably do more to strip MS Word stuff, etc..
public static string StripHTML(this string str)
{
	if (!string.IsNullOrEmpty(str)) {
		string pattern = "<.*?>";
        string str = Regex.Replace(htmlString, pattern, string.Empty);
        pattern = "&nbsp;";
        str = Regex.Replace(str, pattern, string.Empty);
        return str;
	}
	return string.Empty;
}

public static string CapitalizeWords(this string str)
{
    //Capitalize the words
    if (str == null)
        return str;
    if (str.Length == 0)
        return str;

    StringBuilder Result = new StringBuilder(str);
    Result[0] = char.ToUpper(Result[0]);
    for (int i = 1; i < Result.Length; ++i)
    {
        if (char.IsWhiteSpace(Result[i - 1]))
            Result[i] = char.ToUpper(Result[i]);
        else
            Result[i] = char.ToLower(Result[i]);
    }
    return Result.ToString();
}

//Cleans up text to make a nice little url string
public static string ToURLItem(this string str)
{
    //Make the item a URL item
    if (!string.IsNullOrEmpty(str))
    {
        return str.Replace("™", "")
                     .Replace("&trade;", "")
                     .Replace("©", "")
                     .Replace("&copy;", "")
                     .Replace(".", "")
                     .Replace(":", "")
                     .Replace("?", "")
                     .Replace("!", "")
                     .Replace("'", "")
                     .Replace("\"", "")
                     .Replace("/", "")
                     .Replace("&", "")
                     .Replace("  ", " ")
                     .Replace(" ", "-");
    }
    else
    {
        return string.Empty;
    }
}

Storing User Information in Session for C#

A topic that I deal with a lot, when building custom sites, is the session object. It seems to me that many folks are constantly using that old standby Session[“MyVariableHere”] method of grabbing a session variable. While this method works, we soon realize that *Surprise* the session variable can be null, or, in fact, a typo has been made. The code then becomes something like:

	bool UserLoggedIn = false;
	if (session["UserLoggedIn" != null)
		UserLoggedIn = (bool)["UserLoggedIn"];

Now imagine we want to store the user name, maybe the user’s email address etc. Pretty soon we have about ten differently named session level variables floating around that one might have trouble remembering the name of.

The method I have most often used to deal with this issue is a simple LoggedInUser object that is stored in session upon the users login event and then accessed through a global static class.

The LoggedInUser Class

    
    //Lets mark the class as serializable so that when we go to throw it in
    //session we don't get a nasty error
    [Serializable()]
    public class LoggedInUser
    {
		//Some private variables to store our data
        private long _ID;
        private string _name;
        private string _UserName;
        private string _email;
        
        //and some public ones to expose them (note, one could make these read only)
        public long ID
        {
            get { return _ID; }
            set { _ID = value; }
        }

        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }

		//hey what the heck, now that I have my login ID, etc, why
		//not make it easy to load the full record if needed.
        public Login LoadMyLogin()
        {
           //Load from your DB here and Return the full Login Object
        }

		//Ok let's add a couple more properties for giggles
		public long OrgID { get; set; }
		public bool IsSiteAdmin { get; set; }
		public bool IsOrgActive { get; set; }
		public bool AgreedEULA { get; set; }
    }

So, as you can see we have a simple, serializable class setup for consumption later.

Hydration

Well, now that we have this nice little login class, we need to actually fill it with data. In the code I am yanking this out of I have a larger (more monolithic login object) that contains links to other objects, etc.. I don’t really want to serialize it and, further, it is a Linq object — in this case, so it isn’t easily serializable. To accomplish this task of hydration, I throw a quickie ToLoggedInUser method to my login class.

public LoggedInUser ToLoggedInUser()
{
    LoggedInUser aduser = new LoggedInUser();
    aduser.ID = this.LoginID;
    aduser.Name = this.Person.DisplayName;
    aduser.UserName = this.UserName;
    aduser.Email = this.Person.Email;
    aduser.IsAdmin = this.isAdmin;
    aduser.IsSiteAdmin = this.isSiteAdmin;
	aduser.OrgID = this.Person.OrgID;
	
    return aduser;
}

Once we have the object creation method available we can throw it into session upon user login.

Voila, I now have a hydrated LoggedInUser object. The only remaining piece then is to setup a property in session for easy access later. To accomplish this, I am going to create a GlobalVars static class inside my app_code folder (or in my dll — assuming I have imported system web so I can use httpcontext.current). With the GlobalVars class I can, from inside my pages, use the code:

lblUserName.Text = GlobalVars.LoggedInUser.Name;

or

btnDeleteEntireSite.Visible = GlobalVars.LoggedInUser.isSiteAdmin;

The “GlobalVars” Class — or heck call it “Settings” or “StuffINeed”

The final piece here is to create our static class. Code Below:

public static class GlobalVars
{
	public static LoggedInUser LoggedInUser
	{
		get
		{
			object o = HttpContext.Current.Session["_LoggedInUser"];
			if (o != null)
			{
				return (LoggedInUser)o;
			}
			return null;
		}
	}

Not too much to this piece really, we check to see if the session object is null and cast it to our object, if it exists, otherwise we send out null.

And one more thing…

I use my little GlobalVars class for all sorts of stuff like web.config settings and other random goodness, here is a more built out GlobalVars class to demonstrate some of these uses.

public static class GlobalVars
{
	public static LoggedInUser LoggedInUser
	{
		get
		{
			object o = HttpContext.Current.Session["_LoggedInUser"];
			if (o != null)
			{
				return (LoggedInUser)o;
			}
			return null;
		}
	}
	
	public static string SMTPServer
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:Server"];
			if (o != null) {
				return o.ToString();	
			}
			return string.Empty;
		}
	}

	public static int SMTPServerPort
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:ServerPort"];
			if (o != null)
			{
				if (!string.IsNullOrEmpty(o.ToString())) {
					return Convert.ToInt32(o);
				}
			}
			return 25;
		}
	}
	
	public static string SMTPFromAddress
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:FromAddress"];
			if (o != null)
			{
				return o.ToString();
			}
			return "info@MySite.com";
		}
	}

	public static string SMTPBCC
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:BCC"];
			if (o != null)
			{
				return o.ToString();
			}
			return "info@MySite.com";
		}
	}
}