Category: Programming

Catching unhandled exceptions

August 18th, 2010 — 07:46 am

As a rule, in every application I write, I always implement both the Application.ThreadException and AppDomain.UnhandledException events, to catch exceptions which were not caught by a try..catch block.

There are three reasons behind this:

  1. Present a custom failure message to the user (something like Twitter’s fail whale message) instead of the default ugly (and unclear) error dialog, i.e. “XXX.exe has encountered a problem and needs to close. We are sorry for the inconvenience.
  2. Log the exception so it may be resolved in future releases.
  3. Although it’s not considered as a good practice, some exception may be ignored so the application may keep on running, instead of crashing.

However, I recently came across a case in which the application crashed ungracefully although I implemented those methods. Some research led to me to realize my code is not as full-proof as I thought it was.

The code below will crash your application even if you hooked the two events mentioned above. The UnhandledException event WILL be executed, but afterwards the application will crash anyway, presenting Microsoft’s default error dialog:

private void MyThreadProc()
    throw new Exception(”Bad wolf”);

private void ClickMe()
    Thread myThread = new Thread(new ThreadStart(MyThreadProc));

Turns out I was not aware that during the transition between Framework 1.1 and 2.0 (and beyond), Microsoft changed the way the CLR deals with exception that don’t occurs in the application’s main thread, meaning that if you want the application to remain alive even after an external thread exception, you need to tell the CLR to revert to the Framework 1.1 exception handling mechanism, by adding this section to your app.config file:


legacyUnhandledExceptionPolicy enabled=”1″

Again, not a best practice, but if you can’t afford to having

Another footnote is related to using the Application.SetUnhandledExceptionModeMethod. If you try setting it from a Winform application running inside the Visual Studio, you’ll get the following error: “Application exception mode cannot be changed once any Controls are created in the application“, even if that’s the first line of code in the application. This is because the Visual Studio runs a host environment prior to running your application. The methods works just fine when you run it from outside the Visual Studio.

Comment » | Programming, Winforms

Garbage collector, gen2 and memory abuse

January 28th, 2009 — 01:43 pm

There are limits most application developers never encounter. One of them is the 2GB memory limit for applications running on a 32bit operating system.

But what happens if your application is a memory consumer (and most GIS applications are)?

You may find out your application tends to crash and burn once reaching a memory signature of a little over 1GB.

It’s a common knowledge for developers (I hope) that a useful way to measure application’s true memory consumption is using the Task manager’s “VM Size” column (as the “Mem Usage” column only indicates the size of the application’s Working Set). So why does the application crash when supposedly there is still plenty of free memory?

There are 2 possible answers:

  1. Although a certain size of memory is allocated to the application, fragmentation to the memory may cause the application to actually consume more than that. This may also be related to the GC behavior in relation to 2nd generation objects, which I’ll discuss later.
  2. The VM Size column does not represent the actual Virtual address space allocated to the application, which is limited to 2-3GB on a 32bit OS. In addition to the allocated memory the OS may have designated addition shared memory (shared with other applications, but still counts towards the 2GB limit). To view the actual size of memory allocated by the OS to the application, use the Perfmon.exe tool’s Virtual Size counter:

The .Net Garbage Collector and 2nd generation (gen2) collections

The GC algorithm divides the allocated objects to 3 generations (0-2), when generation 0 objects are retrieved most frequently and “live” for the shortest amount of time. Generation 1 objects are collected less frequently and generation 2 collections are truely a rare occasion.

But when does the GC collects generation 2 allocations (”full” collection)? What triggers such a collection?

Surprisingly I found very little information of this subject, but the information I did find, combined with experimentation led to the conclusion such collection occurs when the overall system is low on physical memory.

Now, let’s consider the implications for a 4GB computer running a 32bit OS. While the gen2 heap may inflate over time (especially considering large objects are also collected only in gen2 collections), the GC will never trigger as a single application can never consume the entire amount of memory on the computer (being limited to 2GB). However, this may lead to a memory leak and eventually crashing the application (once it’s virtual address space reaches 2GB).

The solution? Call the GC.Collect() method yourself to trigger a full collection.

1 comment » | Programming, Windows

Juval Lowy and .NET Service Bus

January 12th, 2009 — 01:21 pm

I have recently been to an Israeli user group meeting in which iDesign’s Juval Lowy gave a lecture about the new Azure .Net Service Bus for web services written in WCF.

Basically a service bus is a router, similar to the one you use in your office network. Instead of needing to update the configuration for multiple clients each time a service they are connected to is moved to a new location or changes channel, all clients/services connect to a central hub. In this case the service bus is located online, somewhere on Microsoft servers.

Here is what the meeting’s page says about the lecture:

The .NET services bus is part of the new Microsoft Cloud Computing Windows Azure initiative, and arguably, it is the most accessible, ready to use, powerful, and needed piece. The service bus allows clients to connects to services across any machine, network, firewall, NAT, routers, load balancers, virtualization, IP and DNS as if they were part of the same local network, and doing all that without compromising on the programming model or security. The service bus also supports callbacks, event publishing, authentication and authorization and doing all that in a WCF-friendly manner. This session will present the service bus programming model, how to configure and administer service bus solutions, working with the dedicated relay bindings including the available communication modes, relying on authentication in the cloud for local services and the various authentication options, and how to provide for end-to-end security through the relay service. You will also see some advanced WCF programming techniques, original helper classes, productivity-enhancing utilities and tools, as well as discussion of design best practices and pitfalls.

Although Juval clearly know a lot on the subject, and apparently is currently doing a tour lecture on the subject (at least in Israel and Belgium), I have to say the talk was not very interesting for experienced WCF developers. This is due to the fact the interface is almost identical to that of a simple WCF service, therefor I kept getting a feeling of “been there, done that“. It’s very easy to work the .NET service bus.

The .NET service bus supports both TCP/IP and HTTP based connections (highlight of the lecture: “to add WS support just add an ass“), and allows both connectivity through the cloud or P2P (after negotiation). There is a limited usage to SSL transport level security, something that alarms me a bit, as this is the best performance/security ratio option in WCF.

I do have to wonder regarding the usability of this platform. Many companies I know moved to SOA architecture, splitting central servers to many services. Such systems need a service bus residing inside the local network due to two reasons:

  1. Local network is more secure. Although Mr. Lowy waved his hands and replied “message level security is NP complete” to a question on the subject, I doubt IT managers or security officers in large firms would accept that.
  2. Local network is faster. Although a large downwards bandwidth is easily obtained, for a true 2 way communication you need a decent outgoing bandwidth (unlike ADSL lines, for example), and that’s not cheap.

There are local alternatives, both commercial (Microsoft Biztalk server) and open source (Udi Dahan’s NServiceBus).

I guess only time will tell if this new technology is successful.

6 comments » | Programming, Technology, WCF

Visual Studio 2009 is out, welcome VS2010

December 22nd, 2008 — 02:26 pm

Some time ago, frustrated with my RSS reader being overrun by VS2008 beta announcements, I wrote a short post announcing the release of VS 2009 beta 1. And although there are some calls to re-brand the most recent service pack, I doubt we’ll see this version.

Instead we got Visual Studio 2010, with new features such as support for cloud computing, parallel extensions, ASP.NET MVC, etc.

Frankly, I’m not that excited.
Most of the features to be included in the upcoming version are already available to developers as additions to existing developing tools (although most are in CTP mode at the moment).
There ARE the new features of C# 4.0, but unlike the changes between 1.1 and 2.0, the most recent set of changes is “nice to have” at most.

What is more impressive (in my opinion) are the changes and improvements in the new Visual Studio Team System package, which had a lot of room for improvement even after the latest service pack, and especially the new and improved tester version.

Considering the release of VS2008, we’ll probably be able to see a stable version (beta 2) at the second half of the year 2009.

Anders Hejlsberg, Mads Torgersen and Eric Lippert discuss the new features of C# 4.0

5 comments » | Programming, Visual Studio

The dangers of static members

December 14th, 2008 — 04:30 pm

(If you use Visual Studio 2003 or you tend to ignore compiler warnings, this post is for you)

Static classes and members have their uses. However, I recently encountered a dangerous pitfall regarding their usage.

Consider the following code:

public static class MyClass
    public static int myVal = MyClass.myVal;
    public static MyOtherClass myClass = MyClass.myClass;
    public static Color myColor = MyClass.myColor;

Can you spot what is wrong here?

You got it right - this class assign it’s members back to themselves, effectively avoiding assigning them.

If you try using this code using VS2003 it will compile without any notification. In more recent version you’ll only get a compiler warning.

What’s worse yet: you can make the member private and the code would still compile.

But it can get even worse:
Since these members are not assigned, with value types you’ll get the default value, while with most classes you’ll have a null reference.
But the Color struct is something different. It retains an Empty value, and if your winform application uses the default theme and colors, assigning an empty color to a control basically does nothing.
Now try understanding why your panel refuses to change color….

2 comments » | Programming, Visual Studio, Winforms

There are some things a good developer is NOT required to know

July 31st, 2008 — 01:11 am

Jeff Atwood and Peter Norvig seem to think you must have a deep understanding of how computer hardware works to be a good software developer:

Know how long it takes your computer to execute an instruction, fetch a word from memory (with and without a cache miss), read consecutive words from disk, and seek to a new location on disk

I did learn these things, but after reading Jeff’s post I have been trying to remember a project I worked on during the past 10 years which required this type of knowledge - and I got nothing.

Let’s put aside for a moment specialized area in software development in which this knowledge is important:

  • Real time applications
  • Embedded applications

Assuming you are developing using a modern, high level programming language like Java or C#. During development of applications in areas not mentioned above, did you ever encounter an actual need to know these things? why?

1 comment » | Programming

Good team developers are cameleons

July 17th, 2008 — 08:18 am

Jeff Atwood thinks regions are evil:

No, I will not use #regions. And no, I DO NOT NEGOTIATE WITH TERRORISTS. Shut up.

I tend to disagree. I like being able to navigate through code blocks by scanning them and not using incremental search.
Besides, you can always expand all regions in code using a keyboard shortcut, and if it really bugs you, simply do a replace of “#” with “//#” and your problem is solved (until the next guy does the opposite).

However, I do agree with Jeff about working with a team, and that’s why I think feeling that strongly about any coding habit is wrong.
Whenever I go into a new project I try to adapt my coding style to the existing style, even if initially I don’t really like it.

That’s why I don’t think you should feel that strongly about anything and fighting about coding habits is useless - a good developer can adapt to any working environment.

Comment » | Programming

« Previous Entries