BradVin's .Net Blog

Code, snippets, controls, utils, etc. Basically all things .net

October 2007 - Posts

ÜberUtils Series posts so far :

So every developer has (or should have) a utilities class for strings. It seems the built-in string class never has enough (well for me in any case). So I hereby introduce my string utils class. It actually comprises of 3 files which are :

  1. Strings.cs (the actual string utils)
  2. SafeConvert.cs (a class for doing common conversions)
  3. Extensions/Strings.cs (extension methods using the string utils)

Here is the class diagram of the Strings class :

 

As you can see it has a nested class Regex which is also static. More on this later. Lets cover the string utility methods first (in 'logical' order):

  • IsEmpty - returns true if the object passed in is either null or has a length of zero (exactly like string.isNullOrEmpty but can take an object as input)
  • IsNumeric - returns true if we are dealing with a numeric value. Uses the regular expression : @"^\-?\(?([0-9]{0,3}(\,?[0-9]{3})*(\.?[0-9]*))\)?$". This matches a positive or negative value with any precision and scale (whole number or decimal). It also allows for left-padded zeros, commas as group separators or parenthesis to indicate negative number
  • IsEmail - returns true if an email. Uses the regular expression : @"([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)"
  • Trim - exactly like "abc".Trim() but adds checking for nulls
  • CutWhitespace - cuts all whitespace from a string aswell as trims it
    • eg. Strings.CutWhitespace(" 12  34   5 6  7   ") == "12 34 5 6 7"
  • CutEnd - chops the end n chars off the end of a string
    • eg. Strings.CutEnd("1234567890", 3) == "1234567"
  • CutStart - chops the first n chars off the beginning of a string
    • eg. Strings.CutStart("1234567890", 3) == "4567890"
  • Start - returns the first n chars of a string
    • eg. Strings.Start("1234567890", 3) == "123"
  • End - returns the last n chars of a string
    • eg. Strings.End("1234567890", 3) == "890"
  • GetOccurences - returns an array of strings that are found within another string based on a regular expression
    • eg. Strings.GetOccurences("say day bay toy", "[sdbt]ay") == new string[] {"say" , "day" , "bay"}
    • eg. Strings.GetOccurences("123asdasd 1sk 555 sdkfjsdfkl999", "\\d+") == new string [] {"123" , "1" , "555" , "999"}
  • OccurenceCount - returns the count of strings found within another string based on a regular expression
    • eg. Strings.OccurenceCount("the cat sat on the mat", "at") == 3
    • eg. Strings.OccurenceCount("abcabc", "a") == 2
  • Combine - combines a string array by a delimeter (or not) (DEPRICATED - read update and comments)
    • eg. Strings.Combine(Strings.GetOccurences("123asdasd 1sk 555 sdkfjsdfkl999", "\\d+"), ",") == "123,1,555,999"
    • eg. Strings.Combine(new string[] { "a", "b", "c", "d" }, ";") == "a;b;c;d"
  • ToPaddedNumber - returns a zero padded number (DEPRICATED - read update and comments)
    • eg. Strings.ToPaddedNumber("123", 5) == "00123"
  • XOR - performs a binary XOR operation on each char in the input string based on a key. Very simple form of encryption where XOR(XOR(input)) == input
    • eg. Strings.XOR(Strings.XOR("test", "key"), "key") == "test"
  • ToTitleCase - returns the title case of a string
    • eg. Strings.ToTitleCase("this is a title") == "This Is A Title"
  • ToFriendlyName - returns what I call a "friendly" version of a string. I use this mainly for converting a database field name into a user friendly name
    • eg. Strings.ToFriendlyName("IAmNotFriendly") == "I Am Not Friendly"
    • eg. Strings.ToFriendlyName("SomePrimaryKeyId") == "Some Primary Key"

Now onto the Regex class. The static Regex class just wraps regular expression functionality and contains a few commonly used expressions as constants. Here is the run down :

  •  IsExactMatch - returns true if a string is an exact match for a pattern
    • eg. Strings.Regex.IsExactMatch("test@google.com", Strings.Regex.REGEX_EMAIL) == true
  • Contains - returns true if a string contains a pattern
    • eg. Strings.Regex.Contains("here is my email : test@google.com", Strings.Regex.REGEX_EMAIL) == true
  • Replace - returns a string with a pattern replaced by another string
    • eg. Strings.Regex.Replace("1 23 a 456", @"\d+", "!") == "! ! a !"
  • GetMatch - returns the first match of pattern within a string
    • eg. Strings.Regex.GetMatch("Subject: Test Subject\r\n", @"Subject\s*\:\s*(?<SubjectReturn>.*)\r\n", "SubjectReturn") == "Text Subject"

Now onto the SafeConvert class. It contains the following methods :

  • ToBoolean - returns a boolean value from an object
  • ToInt - returns an integer value from an object
  • ToDecimal - returns a decimal value from an object
  • ToDouble - returns a double value from an object
  • ToHexString - returns a hexidecimal string representation of a byte array. This is used from Extensions\ByteArray.cs
  • ToStream - returns a System.IO.MemoryStream from a string

So thats version 1 of the strings utilities. I say version 1 because I will no doubt add to this over the next couple of posts.

Oh yes, and again we have a whole bunch of new extension methods :

  • Start
  • End
  • CutStart
  • CutEnd
  • OccurenceCount
  • GetOccurences
  • ReplaceAll - similar to Replace, but uses a regular expression to do the replacement
  • Split - similar to Split(char c) but takes a string pattern to split using regular expressions
  • Combine (DEPRICATED - read update and comments)
  • Join - an extension method for string arrays wrapping the string.Join method

Now I know some people might argue that this is extension method abuse, but look at how much more power my strings have :

 

... and anything that helps me code quicker and smarter is not abuse in my book - its smart coding!

Download the source code and unit tests here

UPDATE - thanks to Dan's comments we found a bug in the email regular expression whereby it would not allow the domain ".museum" so I changed the regex to
@"([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,8}|[0-9]{1,8})(\]?)" (changes in bold)
Please note that email validation seems to be a touchy point for many developers as can be seen over at haaked.com . I would suggest not to use ANY email validation like this for restricting comments or purchases online, as you would be limiting your site's reach. Source code and unit tests have been updated.

UPDATE - thanks to Scott Hanselman for pointing out that ToPaddedNumber is redundant as the string class has a PadLeft (as well a PadRight) method - DOH! Source code and unit tests have been updated.

UPDATE - thanks to Don and John for pointing out the fact that my Combine method is redundant as the string.Join method does the exact same thing. - oops ;)
I then renamed my extension method Combine to Join and changed it to wrap the string.Join functionality. Again Source and tests have been updated.

NOTE - I renamed the static extension classes so that you could include both the Utils and Utils.Extensions namespaces without getting the build error : 'Strings' is an ambiguous reference between 'Utils.Strings' and 'Utils.Extensions.Strings'. Please get the latest source.


Thanks for all comments and feedback and please keep it coming. Collaboration and a LOT of testing is the only way to produce robust,useful code!

Posted by bradvin | 22 comment(s)
Filed under: , , ,

I think today is the start for great things to come. And why? Because I had my first article published today, thats why! You can find it over at Dotnetslackers : http://dotnetslackers.com/articles/silverlight/HelloSilverlightStartYourSilverlightJourneyToday.aspx. It basically is the walk through I was looking for when I was curious about Silverlight, but could never find.

It discusses what you need to start developing in Silverlight, what makes up your average Silverlight project, and walks you through a simple example.

If you found my article useful, I also found another good Silverlight article today at the codeproject :  http://www.codeproject.com/silverlight/BeginningSilverlightPart1.asp

happy coding 

Update : 
Ever wondered how you can render HTML in your silverlight controls? Delay has written an HTMLTextBlock control that does just that. Obviously it does not have a fully fledged HTML rendering engine behind the scenes, but it supports the more common tags. Check it out.
 

Posted by bradvin | 1 comment(s)
Filed under: ,

ÜberUtils Series posts so far :

I am now going to finish off the cryptography part of my ÜberUtils project. If you don't know about it, check it out. In the first article I released the hashing class. This post I am going to run through the Encryption class. The Encryption class is pretty straight forward and basically wraps the System.Security.Cryptography symmetric encryption classes. Here are the types of encryption available (this is exposed as an enum):

public enum EncryptionTypes
{
DES,
RC2,
Rijndael,
TripleDES
}

A simple example demostrates the ease of use :

Encryption target = new Encryption();
string inputText = "Thi$ is @ str!&n to tEst encrypti0n!";
string output = target.Encrypt(inputText);

You can also call a static method to make it even easier :

string strCiperText = Encryption.EncryptText("hello world!");

You can also as easily change the encryption algorithm, the password key or the salt. I am not going to write an article explaining how encryption works and what the different components are. If you are interested, check out this nice article I found on the subject.

You guessed it, it is as simple to decrypt too :

string strOriginal = Encryption.DecryptText(strEncryptedText);

Here is the class diagram :

 

Like the hashing class, the encryption class also uses some extension methods. Please note : extension methods should only be used when extending functionality of an existing class in a reusable fashion. Don't create an extension method just because you can, create one when you see yourself using the method over and over again in many places. This is my reasoning behind creating these extension methods. I feel they will be reused again in the future and it makes my life as a developer easier. Here they are :

        public static string ToBase64String(this byte[] data)
{
return Convert.ToBase64String(data);
}

public static string ToUTF8String(this byte[] data)
{
return new UTF8Encoding().GetString(data);
}

public static byte[] ToByteArrayUTF8(this string str)
{
return new UTF8Encoding().GetBytes(str);
}

public static byte[] ToByteArrayBase64(this string str)
{
return Convert.FromBase64String(str);
}

 So thats the encryption class. Included in the source, we again add unit tests for encryption. Download the source here. Enjoy.

Posted by bradvin | 2 comment(s)
Filed under: , , ,

Well if you havent heard the good news already, then go read about it here at ScuttGu's Blog : Releasing the Source Code for the .NET Framework Libraries . As the name of the article implies, Microsoft is planning to release a standalone install that contains the .NET Framework source libraries. It will also include integrated debugging support within VS2008.

WOW!!!!

If you develop using .NET there must have been a time when you needed to delve into the framework code. Thank goodness for the Reflector tool written by Lutz Roeder. It has been the only way to see what the framework is actually doing, by decompiling the framework code:

Or, if you're like me and you want to view the code within VS, then you can download Denis Bauer's Reflector add-in Reflector.FileDisassembler . This allows you to dump a whole framework DLL or single class to a file so you can play :

 

OK, back to the topic - .NET FRAMEWORK SOURCE CODE! Go check out ScottGu's post which shows him stepping through the code within VS2008.

Another amazing feature he talks about is the ability to step into the source even if you haven't downloaded the source. Just step into a framework method and VS2008 will automatically download the appropriate source file from Microsoft. All built in! Pretty awesome.

Posted by bradvin | with no comments
Filed under: ,

ÜberUtils Series posts so far :

If you read my previous post, you would know that it is my time to give back to the community. So where should you start when creating the ULTIMATE REUSABLE UTILS CLASS LIBRARY? (from now on called ÜberUtils)? Good question, and thats the reason why its taken me a while to start this series, cause I had to start it at exactly the right point. I thought back to the first utils class I wrote back in 2003 in .NET 1.1. It was a cryptography class that wrapped existing functionality that exists in the system.security.cryptography namespace.
So I figure thats a good place to start again. But first I wanna note a few things :

  • This code will be written for .NET 3.5 framework (this is to take advantage of the newer features)
  • I will be using VS2008 beta 2 which, which at this point in time (Oct 2007), you can download for free. (I want to utilise some of the new features available e.g. Unit Testing)
  • The namespaces I use will be as simple and generic as possible, meaning that it will be simple to incorporate into any number of companies / projects / systems / architectures etc. I hate having weird long namespaces when I use other developers libraries. I would prefer a namespace like "Utils" rather than "BradVin.Core.Utils". Wouldnt you agree? (I was also thinking about using "System.Utils")
  • The project files and code can be downloaded from codeplex at the ÜberUtils project page.
  • Code license : public domain. This means that all the code in this series is absolutely free, and by definition : the code may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. So rip it to pieces, pull out what you like - I DONT CARE! My only stipulation is this : IF YOU ADD SOMETHING USEFUL PLEASE SHARE IT WITH US!!!!! (you can do this by commenting on this blog or on discussing it at code plex)


I'm gonna start with a Hashing class which is extremely simple to use. This class makes it easy to hash a byte array or a string e.g.

string strHash = Hashing.Hash("test");

You can also use different hashing algorithms e.g.

string strHash = Hashing.Hash("test", Hashing.HashingTypes.SHA512);

Internally, the different hashing algorithm classes used are : SHA1CryptoServiceProvider, SHA256Managed, SHA384Managed, SHA512Managed and the default MD5CryptoServiceProvider.

Very simple isn't it?. Here is the class diagram :

If you have a look at the code, you would have noticed some strange new methods on both string and byte array. This is using a new .NET 3.5 feature called extension methods. If you've not heard of it yet, the best explanation is by ScottGu here. Infinities Loop also talks about it here and ScottGu again here . So let's see how I implement my extension methods. Check this code out :

private string ComputeHash(string inputText)
{
//convert output byte array to a string
return ComputeHash(inputText.ToByteArray()).ToHexString().ToUpper();
}
You'll see a string has a new method called ToByteArray. Also note that the ComputeHash method returns a byte array, and this means that a byte array now has a new method too : ToHexString. Here is the code for these 2 extension methods :
namespace Utils.Extensions
{
public static class ByteArrays
{
public static string ToHexString(this byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 2);
foreach (byte b in data)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
public static byte[] ToByteArray(this string str)
{
return ASCIIEncoding.ASCII.GetBytes(str);
}
}
}

Now all I had to do to use these methods was add a using at the top of my class :

using Utils.Extensions;

But I didn't want to just stop here. I've had a scenario in the past when I needed to compute a MD5 hash of a string. I also found this blog post on the subject and decided I can now use extension methods to add this functionality to every string. So heres the code :

namespace Utils.Extensions
{
public static class Cryptography
{
public static string GetMD5HashCode(this string str)
{
return Utils.Cryptography.Hashing.Hash(str);
}
}
}

So now I can use it on any string e.g.

string actual = "test".GetMD5HashCode();
So thats the Hashing class. This post ended up a lot longer than I expected, so in my next post Im going to add an encryption class. Please check out the code (Download here or get it from my CodePlex project page). Included in the source are unit tests that check the hashing is doing its job correctly. (I used the  System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile method to make sure the tests are valid and double checked the results against other non-C# hashing algorithms e.g. http://pajhome.org.uk/crypt/md5/ )

 

Posted by bradvin | 6 comment(s)
Filed under: , , ,
More Posts