Friday, August 29, 2008

[.NET] Difference between casting and 'as' operator in C#

This is an easy one - but it can be useful to someone so here it comes:

The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.

So you can have something like:

MyClass myObj = new MyClass();
MyOtherClass myOtherObj = myObj as MyOtherClass;
if (obj != null)
//cast was successful
//a little bit of a fuck-up

The correspondent in VB is the TryCast (usage is the same as DirectCast but it doesn't throw any exception).

Saturday, August 23, 2008

[.NET] How to Simulate HttpContext Cookies

This might be useful if you're developing an ASP.NET application and you need to Unit Test (for example with NUnit or some other unit testing framework) some .NET component but you cannot do it because your classes use cookies.

using System.Web;
using System.IO;
using System.Web.Hosting;
//Initialize this stuff with some crap
string appVirtualDir = "/";
string appPhysicalDir = @"C:\Documents and Settings\";
string page = @"localhost";
string query = string.Empty;
TextWriter output = null;
//Create a SimpleWorkerRequest object passing down the crap
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
//Create your fake HttpContext instance
HttpContext.Current = new HttpContext(workerRequest);
//Create your fake cookie
HttpCookie myCookie = new HttpCookie("myTestCookie", "value");
//... somewhere else in your code
//create a cookie object
HttpCookie anotherCookie;
//Get your cookie from the HttpContext
anotherCookie = HttpContext.Current.Request.Cookies.Get(0);
string cookieName = anotherCookie.Name;//cookieName should be now "myTestCookie"
string cookieValue = anotherCookie.Value;//cookieValue should be now "value"

You can use the same strategy to stuff the HttpContext with whatever you may need - maybe your problem are not cookies but some other HttpContext property your classes use.

Anyway I didn't figure this out all by myself - most of the inspiration came from this post on Haacked: Simulating HttpContext (btw - he says he has a better version of the post in the first line but for what I needed it I do not agree).

kick it on