Monday, September 8, 2008

ServiceController class, LINQ and Extension Methods

I ran across a nice article here on how to determine if a Windows Service is installed. I thought this would be better as an extension method. Previously, you would need to catch the InvalidOperationException and ignore it if you tried to use the ServiceController class to get information on a service that is not installed.

public static class ServiceControllerExtensions

{

    public static bool IsInstalled(this ServiceController controller, string serviceName)

    {

        return (from sc in ServiceController.GetServices()

                   where sc.ServiceName.EqualsIgnoreCase(serviceName)

                   select sc).Count() > 0;

    }

}

Sunday, September 7, 2008

Two birds with one stone (0xC0000005 failure for Google Chrome and SQLProfiler 2008)

In my previous blog entry on Google’s Chrome and Symantec’s EndPoint and provided a solution, which was to disable Chrome’s sandboxing. That’s really not a good idea. I noticed last week after installing SQL Server 2008 that it also was giving the same failure.

I went and re-googled for a solution and found a little further down in the article about using the —no-sandbox a link to Symantec’s site. You need to tweak a value in your Registry, reboot, and then both applications can run!

Here’s the link.

Thursday, September 4, 2008

Google's Chrome and Symantec's Endpoint Protection

I installed Google’s Chrome only to discover that our corporate anti-virus program was preventing its execution:

chrome-fail-a

And then you get the nice:

chrome-fail-b

Awww… reminds me of the old Sad Mac. I wonder if it plays the tones? Here’s a link to a temporary solution here.

chrome-fail-c


And now the love…

chrome-fail-d

Wednesday, September 3, 2008

Checking/Asserting for not null with a Generic Method

In my code I like to check parameters for entry conditions and assert where the parameters do not match with the contract for the method. I prefer to have a quick to type and one-line method to do so. My initial code to do this looked like the following:



public static void IsNotNull(object obj, string message)


{


    if (obj == null) throw new NullReferenceException(message);


}


That was great and it allowed me to check for null parameters inside of a method easily with some code that looks like this:



Assert.IsNotNull(account, "account was null");


Assert.IsNotNull(account != null, "account was null");


But notice that the signature of the method allows for the erroneous account != null to be used. To prevent this I changed the signature of method to:



public static void IsNotNull<T>(T obj, string message)


    where T : class


{


    if (obj == null) throw new NullReferenceException(message);


}


Now when you inadvertently put in a value type, it will correctly report this as an error. If you are new to Generics, then you might assume that you must identify the type. Either of the two usages below are equivalent thanks to the compiler inferring the type of the template ‘T’.


Assert.IsNotNull(account, "account was null");

Assert.IsNotNull<Account>(account, "account was null");


If you use Resharper, it will show you that you can safely remove the <Account> from the method call reporting that ‘Type argument specification is redundant.

Thursday, August 28, 2008

Generating artificial phone numbers


Having worked for a company that developed phone fraud detection software in a previous life, I was familiar with the North American Numbering Plan described in Wikipedia. Several times I’ve had a need to create artificial phone numbers.


Below is an algorithm that will handle most if not all of these numbers.



private string GetRandomPhone()


{


    // Generate a NANP compliant phone number (look in wikipedia under North American Numbering Plan)


    var rnd = new Random();


 


    // A number consists of 3 parts: NPA Nxx Station


    // NPA (Numbering Plan Area code) = [2-9][0-8][0-9]


    // Exclude common toll and toll-free numbers


    int npa = 0;


    while (npa == 0 || npa == 800 || npa == 877 || npa == 888 || npa == 900)


    {


        npa = rnd.Next(2, 9) * 100 + rnd.Next(0, 8) * 10 + rnd.Next(9);


    }


 


    // NXX (Central Office or Exchange code) = [2-9][0-9][0-9]


    // Exception the second digits may not be 11


    int nxx = 0;


    while (nxx == 0 || nxx % 100 == 11)


    {


        nxx = rnd.Next(2, 9)*100 + rnd.Next(99);


    }


 


    // Station code = [0-9][0-9][0-9][0-9]


    // When 555 is the NXX the number 100-199 are reserved or fictional numbers)


    int station = 0;


    while (station == 0 || (nxx == 555 && station > 99 && station < 200))


    {


        station = rnd.Next(9999);


    }


 


    const string format = "({0:000}) {1:000}-{2:0000}";


    return string.Format(format, npa, nxx, station);


}


 


Now playing: Hans Zimmer & James Newton Howard - Macrotus

Tuesday, August 19, 2008

Handy script to launch a solution file from the command line

Before Resharper came along and clutter my directories with files, I used tab-completion to launch my solution files from the command line using:

START MyApplication.sln

commandlineBut, with two other resharper files now preceeding the solution file I needed another way to launch the solutution file. Here’s the script that I came up with:


@ECHO OFF

FOR %%n IN (*.sln) DO START %%n

If you have more than one solution file in the same directory, this script is not for you, but that is not a likely scenario. I saved this file as sln.bat and put in the \windows\system32 directory, although any directory in your PATH will do.

Monday, August 18, 2008

Parsing Flat files and new Data 2.0 - Part I

This is the first of a two part article on parsing a fixed length line delimited set of records into a C# Object. This month’s MSDN Magazine featured two articles that caught my eye. The first, was the Toolbox written by Scott Mitchell where he makes reference of an open source project filehelpers.com by Marcos Meli. I was excited to see this as a few of our projects need this type of support for manipulating text based data and this seemed to have all of the features that I wanted. The second article I will take a look at the new Data 2.0 features that were released with Visual Studio 2008 SP1 and .NET 3.5 SP1 (see Scott Hanselman’s posting).

Here’s the brief little demo that I want to build as a console application in .NET 3.5. Read a flat file containing prescribers. This happens to be defined by SureScripts and is a format that we use with our eScript Messenger product.

sample-1

There are 42 fields in the 4.0 format of this file. I fired up the FileHelpers Wizard and proceeded to type in the details on the 42 records. The wizard takes you through a series of four dialogs that ask you details on the record structure you will read (fixed length or delimited), the name of the class and the visibility of that class as well as a few more pages on how many fields each of your records will contain. There is support for ignoring the first N or last N lines, ignoring empty lines as well as identifying a comment marker. For the more advanced usages you can even selectively filter each of the records bases on conditions that you provide.

sample-2

sample-2aAbove is a sample that I entered with a preview of the class that the wizard creates for you. Take a look at the button in the lower left. That is a really nifty button that allows you to test your definitions before you copy/save the code files out to your project! Marcos really deserves a lot of credit for a well thought out application.

Before I gush with too many more accolades for FileHelpers, I should point out a couple of issues that I ran into while putting this together. While you can see the optional field checkboxes checked in the dialog above, I discovered that you can only check the Optional Field check box on fields if all of the following fields also have it checked as well. I was presented with an error dialog, but it would have been nicer to see that in the field designer. Hey its free/donation ware.

sample-2b

After I went back and removed all of the optional fields all was well and I was presented with a nice Grid View showing all of the data that I had in my sample data file. Now that is very nice as it reminds me of the old days when I imported flat files into Microsoft Access database and such.

sample-3

To finish this off I saved the generated class as as well as the handy template for loading the sample data, fired up Visual Studio 2008 and created a new console application. Below is the source to read in all of the records:

static void Main()
{

using (var engine = new FileHelperAsyncEngine<Prescriber>())

{

engine.BeginReadFile(@"..\..\sample.txt");

while (engine.ReadNext() != null)

{

Prescriber record = engine.LastRecord;

Console.WriteLine("{0}, {1}", record.LastName, record.FirstName);

}

}

}


sample-3aThat’s really all there was to it. I changed the original template a little to use .NET 3.5 var’s which I am liking more after my initial impressions of them. Incidently, I blame Resharper for that as it likes to provide too many of those helpful hints about changing the variable to an explicit type definition.

So there you have it. I had never used FileHelpers before and had a working prototype up and running in under 20 minutes. I saved the definition file for the flat file so I can go back and make changes to it in the future if necessary.

Here’s the console running in all of its glory. What would we do without our old friends Harry Winston and Anthony Cardino!


sample-4

In Part II I will show how to use the new .NET 3.5 (or 3.6 as Hanselman sez) and stich up some simple data access using LINQ and the new SP1 features.