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
}
else
{
//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");
HttpContext.Current.Request.Cookies.Add(myCookie);
//...
//... 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 DotNetKicks.com

Sunday, July 20, 2008

[.NET] How to Reformat strings with Regular Expressions

.NET has great RegEx support, bad thing is in order to use this features you have to know about regular expressions (or you can just google validation patterns like crazy as I do).

In a recent post we covered how to validate input against a regex pattern How to Validate Strings with RegEx , now we'll see how to reformat strings using Regular Expressions.

Instead of using the System.Text.RegularExpressions.Regex.IsMatch (jeez) method that just checks for a match giving you back a boolean you can use the System.Text.RegularExpressions.Regex.Match (jeez) method which gives you back a match object stuffed with useful crap.

Let'see an example:

//include this statement
using System.Text.RegularExpressions;

//...

string funkyString = "Scuffia likes moby dick";
string reformattedString = "";

//we use round brackets in the reg ex to create groups
Match funkyMatch = Regex.Match(funkyString, @"^(Scuffia) (likes) (moby) (dick)$");

if (funkyMatch.Success)//success property tells us if we have any match
{
reformattedString = String.Format("{0} {1} {2}", funkyMatch.Groups[1], funkyMatch.Groups[2], funkyMatch.Groups[4]);
Console.WriteLine(reformattedString);
}


The output of this example app should read something (exactly) like "Scuffia likes dick".

As discussed above the Match object is being filled with useful stuff. You can access the Success property in order to check if we have any match, if so you can reformat the input string accessing "Groups" - assigned using the round brackets in the regular expression. Notice the group array is zero based but in the first element (index=0) we have the whole matched expression - we can access the actual sub-strings starting from the second element of the Groups array (index = 1).

I must admit, I really suck at regular expressions (I hate them) so my example is really lame, I'll give you that.

Anyway - a couple of days ago Scuffia turned 26 - happy birthday Scuffia!

Wednesday, July 16, 2008

[VC++] How to Convert from CString to const char * and back

Dealing with VC++, this is only one of the painful conversions you could have to perform if you're working with CString and you need to pass down to some function (or whatever) a const char *.

Code-snippet follows (UNICODE on):

CString myString = "bollocks";

char stoneageBuffer[100];
//initialize your stoneage buffer
memset(stoneageBuffer,0,sizeof(stoneageBuffer));
sprintf(stoneageBuffer,"%S",myString);

//...

//back to CString
myString = stoneageBuffer;


Note that %S (and not %s) formatting type switches to the opposite type of character set (UNICODE if MBCS build and MBCS if UNICODE build).

Sunday, July 13, 2008

[.NET] How to Validate strings with Regular Expressions

Hi fellas,

a tiny code-snippet to show how to use regular expressions to validate strings in .NET:


//include this
using System.Text.RegularExpressions;
//...
string myRegEx = @"^ScuffiaIsOneBigFatFaggot$";
string myStringToValidate;
//...
//fill string to validate from input or whatever
//...
if (Regex.IsMatch(myRegEx, myStringToValidate))
Console.WriteLine("String is valid!");
else
Console.WriteLine("String is rubbish");
//...


It's worth to underline that Regular expressions are case-sensitive, even in VB. I hate writing Regular Expressions, but Scuffia is pretty good at it so when I can't find stuff on google I always bug him when I need to validate some data. For example a couple of weeks ago I needed to validate an email and I asked him for help.
He sent this regular expression straightaway:


^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))
([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$


Writing regular expressions is a mess but reading one if someone else wrote it is definitely something you don't wanna even think about: gotta have blind faith sometimes in this job - just remember to throw some bones to them SQA people (they're paid to break what us developers put together after all).

Thanx Scuffia, the email validation reg ex is working pretty well.