Category: Winforms


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));
    myThread.Start();
}

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:

<configuration
  <
runtime

    <
legacyUnhandledExceptionPolicy enabled=”1″
/> 
  <runtime
>
<configuration>

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

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

Performance improvement from switching to Framework 2.0

June 10th, 2008 — 02:55 am

The application I’m working on is a C4I, GIS based application, originally written in framework 1.1.

Recently we did several tests to prove the improvements derived from upgrading to framework 2.0 (or 3.0) without doing major changes in the base code. The performance improvement focus was on switching to Generics for collections containing value types.

Possible pitfalls - mostly the usage of Hashtable and other 1.1 collections, which tend to return NULL when the key is not found. Unlike them, the Dictionary class and similar generic collections tend to throw exceptions if the key is not found. This requires adding calls to the ContainsKey method to prevent these exceptions. Nothing complicated, but a lot of manual labour.

Performance improvements (also with some minor refactoring):

  • CPU usage in heavy-load-scenarios was reduced by 10-20%
  • Time in GC (as measured by perfmon) was reduced to half of the previous value

Comment » | Performance, Winforms

New Technologies Trends

February 25th, 2008 — 12:49 pm

I have written before a short comparison between “old” and newer technologies, but at the beginning of that post I state that part of the choice of a new technology is the market trend towards that technology.
After reading Justin’s post showing that moving to ASP.NET is beneficiary because it’s becoming a prominent technology I decided to implement his research methods (using Google) on different technologies.

I began by searching for file types

However, this reflects only on files shared on the web, and since JAVA is a web technology (unlike Delphi) the results don’t say much.

But Google trends provides a clearer picture - while C# remains stable, other programming languages are on the decline:

Focusing on the .Net world, you can clearly see new technologies are dominant in Google searches:

WPF vs. Winforms

WCF vs. Remoting

The rise of .Net Framework 3.0 technologies

With Silverlight being the “Hot New Thing” (maybe because it’s a web-based technology)

So maybe choosing a new technology is a logical move even if it doesn’t offer a significant technological advantage - since keeping older technologies means you are working against the market trend.

So consider switching from Winforms to WPF, from various communication technologies to WCF and from VS 2003 or 2005 to VS 2008 - in the long run the market will force you to do it anyway, either through the job market or through customers demands.

Comment » | Technology, Visual Studio, WCF, WPF, Winforms

Five steps for creating a transparent user control

November 29th, 2007 — 04:30 am

Guest post from Eyal Ron:

After much testing this is the correct formula for a truly transparent user control:

  1. Derive from Panel rather then UserControl.

  2. Override the OnPaintBackground function:
    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
    //do nothing
    }
  3. Override the OnMove function:
    protected override void OnMove(EventArgs e)
    {
    RecreateHandle();
    }
  4. Override the CreateParams property:
    protected override CreateParams CreateParams
    {
    get
    {
    CreateParams cp = base.CreateParams;
    cp.ExStyle = 0×00000020; //WS_EX_TRANSPARENT
    return cp;
    }
    }
  5. Override the OnPaint function:
    protected override void OnPaint(PaintEventArgs e)
    {
    Graphics g = e.Graphics;

    //Do your drawing here
    .
    .
    .

    g.Dispose();
    }

4 comments » | Winforms

Special consideration for the ThreadAbort exception

November 21st, 2007 — 11:07 pm

As a rule, I never want to see an unhandled exception crashing my application with the .Net error dialog and without logging the error.
Therefor I always hook both the AppDomain.UnhandledException and the Application.ThreadException events to catch those exceptions, log them, and close the application gracefully.

Turns out I overlooked one small detail - the ThreadAbort exception, raised by a call to the Thread.Abort method. It’s not a best practice to use it (you should let the thread shut down itself), but it may be used by a 3rd party code, so it can’t be ignored.

However, since it’s not an actual exception there is no logic in shutting down the application due to this exception.

Comment » | Winforms

Validation of a NumericUpDown control

November 18th, 2007 — 06:59 am

The NumericUpDown control has a built-in validation:

  • Values smaller than the minimum are replaced by the minimum
  • Values larger than the maximum are replaced by the maximum

This may lead to a situation in which the user entered an invalid value and pressed the form’s “OK” button, leading to saving of a value completely different than the one entered with no notification.
To prevent this, enter your own validation code into the validating event (using the “Text” property instead of “Value”), and if the validation fails set the e.Cancel argument to “true”.

2 comments » | Winforms

« Previous Entries