Some notes on software development... RSS 2.0
# Sunday, 22 May 2011

To stop HTTP parsing exceptions being thrown you can set useUnsafeHeaderParsing=true


From MSDN:

HttpWebRequestElement.UseUnsafeHeaderParsing Property

Sunday, 22 May 2011 16:01:05 (GMT Standard Time, UTC+00:00)  #    -
# Friday, 11 September 2009

Here is an extension method that will swap two list items for any class that implements IList

public static void SwapElements<T>(this IList<T> obj, int index1, int index2)
    if (index1 > (obj.Count() - 1) ||
        index2 > (obj.Count() - 1) ||
        index1 < 0 || index2 < 0)
        throw (new IndexOutOfRangeException());

    T tempHolder = obj[index1];
    obj[index1] = obj[index2];
    obj[index2] = tempHolder;

And a quick test:

static void Main(string[] args)
    List<string> testList = new List<string>();

    testList.AddRange(new string[] { "Test1", "Test2", "Test3", "Test4", "Test5" });

    Console.WriteLine("Original List Contents");
    testList.ForEach(s => Console.WriteLine("{0}", s));

    testList.SwapElements(1, 3);

    Console.WriteLine("Swapped Item 1 with 3 List Contents");
    testList.ForEach(s => Console.WriteLine("{0}", s));


The result:


Don’t forget that lists are zero-based ;-)

Friday, 11 September 2009 10:39:22 (GMT Standard Time, UTC+00:00)  #    -
# Thursday, 05 March 2009

This is old news but something I had to use recently....
Add a .cs file to your project, any filename is fine but I called mine ExtensionAttribute.cs.
Add the following code...


Wherever you declare your extension methods you need to include 'using System.Runtime.CompilerServices' to the top.

Note:- You must be using Visual Studio 2008 for this to work.

The Moth - Using Extension Methods in Fx 2.0 Projects
CodeThinked - Using Extension Methods in .net 2.0

Thursday, 05 March 2009 10:12:41 (GMT Standard Time, UTC+00:00)  #    -
# Friday, 05 September 2008

If an exception occurs in the BackgroundWorker control's DoWork method it will get wrapped in to the RunWorkerCompletedEventArgs object in the RunWorkerCompleted method.
Checking the Error property of the RunWorkerCompletedEventArgs tells us if an exception occurred on the BackgroundWorker's thread. By re-throwing the exception in the RunWorkerCompleted method it will then be on the calling (GUI) thread where it can be then be dealt with accordingly:

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) throw e.Error; }
The error check should always be the first statement in the RunWorkerCompleted method.
Friday, 05 September 2008 13:10:33 (GMT Standard Time, UTC+00:00)  #    -

Steve Tibbett has a nice blog post describing string formatting in C#.

Here are the useful bits....




Friday, 05 September 2008 10:56:52 (GMT Standard Time, UTC+00:00)  #    -
# Wednesday, 20 August 2008

The following function returns the number of SQL Server statements from a SQL text file using GO as the batch separator:

private int GetBatchCount(string scriptFile)
    string allSql = string.Empty;

    using (StreamReader sr = new StreamReader(scriptFile)) 
        allSql = sr.ReadToEnd();
    Regex regex = new Regex(@"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    return regex.Split(allSql).Length - 1;    
Wednesday, 20 August 2008 12:32:22 (GMT Standard Time, UTC+00:00)  #    -
# Friday, 15 August 2008

When trying to use anonymous methods called by Control.Invoke, like so:

this.Invoke(delegate { txtTest.Text = "Hello World"; });

you get the follow compiler error:


This is because the Delegate class, expected by the Control.Invoke method, is not a delegate type which the anonymous method is.
To work round this you can cast the anonymous method to a MethodInvoker delegate.
Our previous code now becomes:

this.Invoke((MethodInvoker)delegate { txtTest.Text = "Hello World"; });

Guy Mahieu has a nice blog about it here.

Friday, 15 August 2008 16:13:17 (GMT Standard Time, UTC+00:00)  #    -
# Thursday, 12 June 2008

Handy reference for the C# data types...


Taken from (article)

Thursday, 12 June 2008 15:13:22 (GMT Standard Time, UTC+00:00)  #    -
# Tuesday, 27 May 2008

If you save a HTML page to a text file, or as a string in memory, you are likely to get the relative path contained in any IMG or HREF tags

Example snippet:

<H1>Hello from Test Page</H1>
<IMG src="images/TestImage1.jpg">

When you then load you saved HTML page you will not see the image because the HTML is looking for TestImage1.jpg in the images folder which doesn't exist. All that exists is your saved HTML text file.
So we need to parse the HTML and prefix the missing server path to the src tag in the HTML.

The most efficient way to achieve this is to use the power of Regular Expressions, but I'm no expert with RegEx's so after trawling the Internet looking for a suitable RegEx example, rather than read a book ;), I finally found the correct expression at

The pattern: "<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>"
The Match Evaluator: "<$1$2=\"" + absoluteUrl + "$3\"$4>"

The example method:

public static String ConvertRelativePathsToAbsolute(String text, String absoluteUrl)
    String value = Regex.Replace(text, "<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>", "<$1$2=\"" + absoluteUrl + "$3\"$4>",
                                 RegexOptions.IgnoreCase | RegexOptions.Multiline);

    // Now just make sure that there isn't a // because if
    // the original relative path started with a / then the
    // replacement above would create a //.

    return value.Replace(absoluteUrl + "/", absoluteUrl);

Using the method:

ConvertRelativePathsToAbsolute(myHTML, "http://localhost/")

Will return:

<H1>Hello from test Page</H1>
<IMG src="http://localhost/images/TestImage1.jpg">

Works great for me so thanks!

Links - Convert Relative Paths to Absolute Using Regular Expressions

Tuesday, 27 May 2008 18:27:08 (GMT Standard Time, UTC+00:00)  #    -
C# | Regular Expressions
# Monday, 28 April 2008

Scott Gu has a nice article describing the null coalescing operator when used with LINQ queries.

A quick example:

The Qty & Size properties for the anonymous type will be defined as integer types NOT nullable integers. If any of the spec.Attribute("x") values are null or don't exist for any reason, the value returned will be a simple integer zero.
This is because using the null coalescing operator (??) is enforcing that null can never ever happen.

Scott Gu blog article

Monday, 28 April 2008 17:01:12 (GMT Standard Time, UTC+00:00)  #    -
# Wednesday, 02 April 2008

If you have a char array that contains the string you want but is padded out with null terminators e.g. '\0' you can use the String.TrimEnd method to get the exact string you need.

A 12 element char array contains the following chars: M y S t r i n g \0 \0 \0 \0

To convert to a string you can use the String constructor to pass in a Char[] type. Unfortunately a .NET string can happily contain null characters so your resulting string would be MyString\0\0\0\0
Using the TrimEnd('\0') will return the correctly terminated string.


Note: Outputting a string containing null characters to other classes like form controls may automatically terminate the strings correctly at the first null character but behind the scenes the string still contains the null characters.

MSDN String.TrimEnd Method
Strings In .NET and C# (Jon Skeet)

Wednesday, 02 April 2008 09:46:35 (GMT Standard Time, UTC+00:00)  #    -
# Monday, 10 March 2008

Using P/Invoke you can play a beep through the PC speaker.

The P/Invoke prototype:

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool Beep(uint dwFreq, uint dwDuration);
specifies the frequency, in hertz, of the sound. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).
dwDuration specifies the duration, in milliseconds, of the sound.
Example code to call the function:
Beep(500, 1000);
Warning!!! Beep is NOT asynchronous so it does not return to the caller until the beep has finished
Links: Beep (Kernel32) reference

Monday, 10 March 2008 17:25:20 (GMT Standard Time, UTC+00:00)  #    -
# Friday, 07 March 2008

An excellent article by Jon Skeet explaining how to make a Singleton thread-safe:

Implementing the singleton pattern

Friday, 07 March 2008 11:56:09 (GMT Standard Time, UTC+00:00)  #    -
# Monday, 18 February 2008

To get the Windows folder you can use the static GetEnvironment method from the Environment class.
You need to pass in the name of the Environment variable, in this case WinDir, and it will return the correct Windows path regardless of which Windows OS the app is running on.


Other Environment variables available are:

  • FrameworkVersion
  • OS
  • SystemDrive
  • TEMP
There are many others but they vary depending on the OS and applications installed. View all the Environment variables by running SET from a command line.

Monday, 18 February 2008 11:26:57 (GMT Standard Time, UTC+00:00)  #    -
# Thursday, 07 February 2008
Thursday, 07 February 2008 10:35:36 (GMT Standard Time, UTC+00:00)  #    -

This is a handy operator that can be used to replaces 'if-else' syntax therefore producing less code.
The operator is used in the form:

condition ? first_expression : second_expression;

If the condition is true then the first_expression is returned. If the condition is false the second_expression is returned.

For example:

if (string.IsNullOrEmpty(_name))
  txtName.Text = "";
  txtName.Text = _name;

can be re-written using the ternary operator like so:

txtName.Text = string.IsNullOrEmpty(_name) ? "" : _name;


MSDN ?: Operator (C# Reference)

Thursday, 07 February 2008 09:34:49 (GMT Standard Time, UTC+00:00)  #    -

Sign In
Total Posts: 116
This Year: 0
This Month: 0
This Week: 0
Comments: 36
About the author/Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Hadrian Phillips

All Content © 2017, Hadrian Phillips
DasBlog theme 'Business' created by Christoph De Baene (delarou)