October 2009 Archive

C# Replace New Lines

October 29th, 2009

If you know you’re working on the Windows platform and all data will come from Windows then to replace newlines using C#.NET we just use.

myString=myString.Replace(Environment.NewLine,"");

In all other cases it’s much safer to string together the Replace function to cover all possibilities.

myString=myString.Replace("\r", "").Replace("\n", "");

C# IsNumeric

October 28th, 2009

If you do a search for ‘C# IsNumeric’ you’ll find a lot of hits talking about why this function is available in VB.NET but not in C#.NET. It’s used to test if a given string can be converted to a number.

I agree it’s a very useful function and there’s lots of possible solutions, the main ones being

  1. Loop through the string and check each Char is a number
  2. Use Double.TryParse is a very popular one since it doesn’t throw an exception on failure
  3. Use Convert.ToInt32 inside a try/catch block
  4. Using a Regex expression

I really wanted to use Double.TryParse but unfortunately this will return true for numbers that are decimals. Therefore if you want to test a string for whole numbers you also have to check the string for periods or commas (using string.contains) depending on your locale.

For this reason I tend to use the Regex solution, mainly because it’s very short and simple to implement.

public static bool IsNumeric(string str)
       {
            return Regex.IsMatch(str, "^[0-9]+$");
       }

It also requires the using directive System.Text.RegularExpressions

Linux Out of Box Experience

October 15th, 2009

I recently had a problem with a 2 page document scanned to pdf that was far too light to read, the black text had become light grey and the contrast was too low.

I searched how to fix this but everything suggested using Photoshop to edit each page, then save to pdf and finally using some extra program to stitch the 2 pdf files together.

At this point it was obviously going to be easier using Linux so I opened Virtualbox and started Fedora 11.

I imported the pdf pages into GIMP, edited them and saved as pdf, then I used Ghostscript to join the files using the following command:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf file1.pdf file2.pdf

I could have done all of this on Windows but not without searching and installing extra programs, in Fedora it was all just there

This is one of the reasons I love Linux, for me the out of box experience leaves Windows in the dust.