Continue or Break using Parallel.ForEach

You might be converting your normal foreach loop over to use the Parallel.ForEach syntax to improve performance in a thread safe loop.

You also probably have some break and continue statements.

Well, it took me a few to figure out how to deal with these. Turns out, it is simple.

When you converted your loop into a compatible definition for the Parallel.Foreach logic, you ended up making the statement body a lambda, right. Well, that is an action that gets called by the Parallel function.

So, pretend it is a method. When you are done, you just return. So, replace your continues and breaks with return statements.

Easy, right? Requires the mental shift from built in operators, to library function calls.

Happy Coding!

The remote certificate is invalid according to the validation procedure for FTP

I was testing a C# FTP application of mine and got this lovely gem of an error when connecting using SSL. I had a self signed certificate in the trusted store, but the FTP library kept screaming that the certificate was invalid.

Well, I found a great workaround for the time being. It should only be used by configuration or conditional compiling though.

Disable Certificate Chain Checking

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

Using the code above, your certificate checks will always be considered good. The channel will still be SSL protected, you just won’t be looking for man in the middle attacks nor identity mismatches. Something you don’t care about in development, just production.

Happy Coding!

.NET 4.5 in-place upgrade might confuse you and your users

I learned something new today, something I strive to do everyday. I learned that the new .NET 4.5 Framework doesn’t just install side by side with 4.0 but it actually “upgrades” it for you. This doesn’t sound terrible, until you realize that if you are developing an application for 4.0 (many of need to as we support XP clients, which 4.5 won’t run on).

Why the issue, well one is that you run you application and you may not get the quirks you would on a machine with just 4.0. You get the bug fixes that were done for 4.5. Why is this bad? Well, you can’t reproduce the issues your customers face, and worse you won’t see them in development. Hence, you first learn about the issue after it hits your customers. No bueno!.

The issue I am facing is more insidious. I use reflections to reach inside the bowels of the framework to do things that they won’t expose to me publicly. Sealed classes, private initializers, etc. Well, they can rename these things since they aren’t public. You see where I am going. In 4.5, my method isn’t there anymore.

So, user installs 4.5, boom goes the app. Yeah, could have happened with any bug fix, sp, or update. I just didn’t expect a new framework edition to crumble the empire.

Well, just watch out and test your apps on both 4.0 and 4.5 systems. Even if, especially if, you are writing targeted 4.0 applications.

Happy Coding!

More details I read about at Hanselman’s blog.

Detect Windows/Operating System Version in C# .NET

Are you looking for a way to detect which OS you are running on in your .NET application? I know I had to so that I could implement workarounds that were OS specific.

Here is a simple function to get the name. You can use this as an idea of how to pick the exact version you are on.

Please don’t be one of those morons that uses this function then does a string comparison on the return. Use common sense and extract the logic from this to get what you need.

I better not see any code out there like

if(GetOSVersionName() == "Windows 98"){Do stupid stuff here}

Yes, it would technically work, so I have no doubt it will be implemented that way by some of you. Religious debate? Probably.

 public string GetOSVersionName()
            string strVersion = "Unknown";
            switch (Environment.OSVersion.Platform)
                case PlatformID.Win32S:
                    return "Windows 3.1";
                case PlatformID.Win32Windows:
                    switch (Environment.OSVersion.Version.Minor)
                        case 0:
                            return "Windows 95";
                        case 10:
                            if (Environment.OSVersion.Version.Revision.ToString() == "2222A")
                                return "Windows 98 Second Edition";
                                return "Windows 98";
                        case 90:
                            return "Windows ME";
                case PlatformID.Win32NT:
                    switch (Environment.OSVersion.Version.Major)
                        case 3:
                            return "Windows NT 3.51";
                        case 4:
                            return "Windows NT 4.0";
                        case 5:
                            switch (Environment.OSVersion.Version.Minor)
                                case 0:
                                    return "Windows 2000";
                                case 1:
                                    return "Windows XP";
                                case 2:
                                    return "Windows 2003";
                        case 6:
                            switch (Environment.OSVersion.Version.Minor)
                                case 0:
                                    return "Windows Vista";
                                case 1:
                                    return "Windows 2008";
                                case 2:
                                    return "Windows 7";
                case PlatformID.WinCE:
                    return "Windows CE";
                case PlatformID.Unix:
                    return "Unix";
            return strVersion;

Happy Coding!

HRESULT: 0x80131515 when running installutil to install a .NET Service

So you write your nice and fancy service and are all excited to distribute it to your client. You don’t feel like creating an installer for it, that seems like overkill. You just send a zip file with a batch file that calls installutil to register the service. Easy right?

Well, your client calls and complains that get the following error when running installutil aka your batch file:

Exception occurred while initializing the installation:

System.IO.FileLoadException: Could not load file or assembly ‘file:///D:servicesmyservicehost.exe’ or one of its dependencies. Operation is not support. (Exception from HRESULT: 0x80131515).

I am sure you will start scratching your head and immediately blame them missing a dll or maybe the client ran it wrong. Maybe they have it in the wrong directory? Seems feasible, right? Wrong.

It turns out that Windows was protecting them. Windows doesn’t like files from other computers very much, especially not executables. They get a special stay away from me flag.

So, how do I fix this? Easy. Just open the properties dialog on the exe/service you extracted and hit the UNBLOCK button. Now installutil will work great!

Happy Coding!

Unit Test to verify Entity Framework Model (EDMX) is accurate

I work extensively with the Entity Framework in most of my projects. One thing that gets frustrating though is when you work with a large team and the data model gets out of synch with your local database.

You normally don’t figure it out until you are running some operation in your application and get the dreaded Entity Framework error. (inner exception = Column Missing), or non-nullable type, or other enjoyable light reading.

I put together a simple unit test that will work with any model and verify it using a very simplistic technique. It’s a quick smoke test.


You will need to modify this code to fit your mechanics for creating the entity context, and the connection strings, etc. Other than that, it is shake and bake.

        public void VerifyModelAccuracy()
            //FYI – When switching to multiple engagements, will need to pass in engagement id for db connection (get from routing db)
            using (var context = EngagementContextFactory.CreateEngagementContext())
                //lazy and dont want to research why this isnt loading
                //use reflection to iterate over each collection in the context and just watch for errors.

                Type t = context.GetType();
                var props = t.GetProperties();
                foreach (var p in props)
                    var isEnumerable = (from i in p.PropertyType.GetInterfaces()
                                        where i == typeof(IEnumerable)
                                        select i
                                            ).Count() > 0;
                    if (isEnumerable)
                            IEnumerable dataToPull = (IEnumerable)p.GetValue(context,null);
                            if (dataToPull != null)
                                var result = (from object d in dataToPull select d).FirstOrDefault();
                        catch (Exception ex)
                            string error = ex.Message;
                            if (ex.InnerException != null)
                                error += ex.InnerException.Message;
Happy Coding!!

Validate ACH Routing Numbers for EFT and Electronic Checks

I was looking for a way to validate the routing numbers for an eCommerce system I am working on and found a nice VB sample here.

I converted the logic to C# and optimized it for better performance and use.

Hopefully some others out there will find use:

    /// Validates the routing number.
    private bool ValidateRoutingNumber(int routingNumber)
        //The check equation for a number a1a2a3a4a5a6a7a8a9 is 3a1 + 7a2 + a3 + 3a4 + 7a5 + a6 + 3a7 + 7 a8 + a9 mod 10 = 0

        //rewrote for higher efficiency

        //must be 9 digits
        if(routingNumber < 100000000)
           return false;
       if(routingNumber > 999999999)
            return false;
        //build array for quick comparison
        //left to right using fun with math.

        int[] routingNumberAsArray =
           routingNumber / 100000000,
            (routingNumber % 100000000) / 10000000,
            (routingNumber % 10000000) / 1000000,
            (routingNumber % 1000000) / 100000,
            (routingNumber % 100000) / 10000,
            (routingNumber % 10000) / 1000,
            (routingNumber % 1000) / 100,
            (routingNumber % 100) / 10,
            (routingNumber % 10) / 1

        //calculate the route sum using the formula above. 3 7 1.
        int routeSum =
            3 * routingNumberAsArray[0] +
            7 * routingNumberAsArray[1] +
            routingNumberAsArray[2] +
            3 * routingNumberAsArray[3] +
            7 *+routingNumberAsArray[4] +
            routingNumberAsArray[5] +
            3* routingNumberAsArray [6] +
            7 * routingNumberAsArray [7] +
            routingNumberAsArray [8] ;
        return routeSum % 10 ==0;

FedEx Integration Address Service: Unable to generate a temporary class…ParsedElement[]

Are you using the new WCF service reference against the FedEx Address service WSDL? I’ll bet your scratching your head on why you get this craptastic error.

 InnerException: {"Unable to generate a temporary class (result=1).rnerror CS0030: Cannot convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement[]' to 'YOURNAMESPACE.FedExAddressService.ParsedElement'rnerror CS0029: Cannot implicitly convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement' to 'YOURNAMESPACE.FedExAddressService.ParsedElement[]'rn"}
    Message: "There was an error in serializing body of message addressValidationRequest1: 'Unable to generate a temporary class (result=1).rnerror CS0030: Cannot convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement[]' to 'YOURNAMESPACE.FedExAddressService.ParsedElement'rnerror CS0029: Cannot implicitly convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement' to 'YOURNAMESPACE.FedExAddressService.ParsedElement[]'rn'.  Please see InnerException for more details."
    Source: "mscorlib"

The answer is annoying. You would think running on the .NET 4.0 Framework they would have figured out their bugs with consuming WSDL’s.

So, open your references.cs file for the service. (It’s hidden, you either go to disk or hit the little icon that says show all files, hit the arrow on the service reference, then you see the magic file)

Hit Ctrl+H and type in [][] for the find and replace with [].

Basically, it made this nice two dimensional array that the server is less than pleased to receive.

If you refresh from the WSDL, guess what? You get to do this all over again, so quit hitting the refresh button.

Happy coding!

Dotfuscator and KernelBase crashes, .NET crash with your application or service after obfuscation

Quick Tip: Don’t let Dotfuscator auto-sign your assemblies without specifying the key file explicitly.

I spent the last hour beating my head into the wall, again, trying to figure out why Dotfuscator was creating a crap exe. I turned off every option, no help.I figured it must be because I am writing a windows service, so I tried it on a normal exe of mine.

Everything worked fine there. The pain , oh the pain. Well, it finally dawns on me to try turning off my digital signature on my service. Voila! Dotfuscator no longer create the crap exe that threw awesome KernelBase.dll exceptions.

So, it turns out the Dotfuscator’s auto re-sign sucks. The trick is that if you do the re-sign, make sure you explicitly specify the signing key path.

InstallUtil and BadImageFormat with a normal C# service

So, you get the old BadImageFormat error when installing your service. If you aren’t writing C++ extensions, then this is probably because you forgot to use the right version of InstallUtil for your target platform.

i.e. x86 build using x64 InstallUtil or vice versa.

Easiest fix? Just build for Any CPU. Then you really don’t have to think about it too hard.

Happy coding!