Thursday, July 10, 2008

C# version of VB6/VBA's Val function

Here is some code to emulate VB6/VBA's Val function in C#. I found the original http://www.dreamincode.net/code/snippet1821.htm but it needed some changes to work correctly.


using System.Text.RegularExpressions;

using System;



namespace ValinCS

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine(Val("AAA234"));

Console.WriteLine(Val("1234asdv"));

Console.WriteLine(Val(" 345"));

Console.WriteLine(Val("1.2345f"));

Console.WriteLine(Val(" 1 2"));

Console.WriteLine(Val(""));

Console.WriteLine(Val("12"));

}



private static int Val(string value)

{

string returnVal = string.Empty;

int tryInt = 0;

//^ specifies that the match has to start at the start of the string

//Trim() trims both ends of the string before matching

MatchCollection collection = Regex.Matches(value.Trim(), "^\\d+");

foreach (Match match in collection)

{

returnVal += match.ToString();

}



//attempt conversion to int

int.TryParse(returnVal,out tryInt);

return tryInt;

}

}

}



Wednesday, July 02, 2008

Cloning using Serialization

I found some great C# code the other day which allows deep copying of objects, rather than shallow copies which object.Clone() does. Saved heaps of time mucking around with the ICloneable interface, and basically rewriting heaps of code.

You need to decorate the class(es) that you want to clone with the [Serializable] attribute. If you are trying to clone a object of a type which has members of some other class, those classes need to be serializable too.

public static object Clone(object obj)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(ms);
}

Labels: , ,

Ebay International Search Gadget rewritten

For any of you that use the Ebay international search gadget on the right hand side of the blog, I have just rewritten it as it was not working anymore.

I am have also added an Amazon international search gadget.

Use them directly from this site or add them to your iGoogle page. Note that the international functionadoes not work if you use the gadgets directly from this site. It only links to the respective US sites. You need to add it to a your iGoogle page to get the full functionality.