ASP.NET Hosting

Fabrice's weblog

Tools and Source

  • How to handle unhandled exceptions in Windows Forms

    If you've already handled unhandled exceptions in your Windows Forms applications, your probably know the Application.ThreadException event. Thanks to this event, all you have to do is to:

    1. Register a handler for the event
    2. Handle the exception in this event handler
    Here is an example:
    [STAThread]
    static
    void Main()
    {
      Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
      Application.Run(new FrmMain());
    }

    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
      MessageBox.Show("Unhandled exception: "+e.Exception.ToString());
    }

    If you want to reuse the default dialog box, you can use the following code:
    if (SystemInformation.UserInteractive)
    {
      using (ThreadExceptionDialog dialog = new ThreadExceptionDialog(exception))
      {
        if (dialog.ShowDialog() == DialogResult.Cancel)
          return;
      }
      Application.Exit();
      Environment.Exit(0);
    }

    This is all fine and easy, but what if you have several threads? What if an exception is thrown in a thread other than the main one?
    Well, the answer is simple: you won't be notified by the Application.ThreadException event.
    Of course there is a solution: you can use the AppDomain.UnhandledException event instead. There is one thing to be aware of though: your event handler will be executed by the thread that threw the exception. This can be a problem if you want to display something or interact with graphical components, because all this kind of actions should be performed in the same thread (the main thread).

    Here is a code sample that shows a complete solution that takes care of this:
    private delegate void ExceptionDelegate(Exception x);

    static private FrmMain _MainForm;

    ///
    <summary>
    ///
    The main entry point for the application.
    /// </summary>
    [STAThread]
    static
    void Main()
    {
      _MainForm = new FrmMain();
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
      Application.Run(_MainForm);
    }

    private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
      Exception exception;

      exception = e.ExceptionObject as Exception;
      if (exception == null)
    {
    // this is an unmanaged exception, you may want to handle it differently
       return;
    }
      PublishOnMainThread(exception);
    }

    private static void PublishOnMainThread(Exception exception)
    {
      if (_MainForm.InvokeRequired)
      {
        // Invoke executes a delegate on the thread that owns _MainForms's underlying window handle.
        _MainForm.Invoke(new ExceptionDelegate(HandleException), new object[] {exception});
      }
      else
      {
        HandleException(exception);
      }
    }

    private static void HandleException(Exception exception)
    {
      if (SystemInformation.UserInteractive)
      {
        using (ThreadExceptionDialog dialog = new ThreadExceptionDialog(exception))
        {
          if (dialog.ShowDialog() == DialogResult.Cancel)
            return;
        }
        Application.Exit();
        Environment.Exit(0);
      }
    }

    private void ThreadMethod()
    {
      throw new Exception("From new thread");
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
      Thread thread;
      thread = new Thread(new ThreadStart(ThreadMethod));
      thread.Start();
    }

    Nota Bene: You'll have to register a handler for the UnhandledException event for each AppDomain.
    Nota Bene 2: The UnhandledExceptionEventArgs parameter contains a IsTerminating property that indicates whether the common language runtime is terminating. Something to test in order to know what to do with the exception.

    Thanks to Pierrick for the help.

  • How to handle unhandled exceptions in Windows Forms

    If you've already handled unhandled exceptions in your Windows Forms applications, your probably know the Application.ThreadException event.
    This event is simple to use, but cannot be used to handle exceptions thrown in threads other than the main thread.
    If you are working with multiple threads, you can take a look at this short article that shows how to handle unhandled exceptions for multithreaded Windows Forms applications.

  • SharpToolbox feeds in Javascript for your sites

    This has been up on this weblog for quite a while, but I never talked about it. If you want to display SharpToolbox' latests additions and updates on your site without having to deal with the RSS feeds, you can use this simple HTML block:

    <script src="http://z.sharptoolbox.com/js/latest.js"></script>

  • Simulated multiple inheritance pattern for C#

    David Esparza-Guerrero has a trick to simulate multiple inheritance in C#. This is not a perfect solution, but it's interesting to look at.
    Too bad we can't use the same approach (using the implicit operator) to have classes implement interfaces by delegation just like Delphi does with the implements keyword. Compiler error CS0552 states that "You cannot create a user-defined conversion to or from an interface" :-(

  • The Business of Software for microISVs

    I've been following the discussions about microISVs for a little while now, and there are some good sites on the subject.
    microISVs are usually one-developer Independent Software Vendor companies.

    A good place for discussions is The Business of Software, hosted by Joel on Software and Eric Sink.
    For news and other resources, you can visit microISV.com.
    For articles on the subject, you can should read Eric Sink's great articles:

  • Celestia: free space travels

    If you like to travel, this is for you...
    This is great software with endless possiblities. You can follow satellites, view planets in real-time, watch eclipses back in time, etc.

    Celestia is a free space simulation software that lets you explore our universe in three dimensions. Celestia runs on Windows, Linux, and Mac OS X.

    Unlike most planetarium software, Celestia doesn't confine you to the surface of the Earth. You can travel throughout the solar system, to any of over 100,000 stars, or even beyond the galaxy.
    All movement in Celestia is seamless; the exponential zoom feature lets you explore space across a huge range of scales, from galaxy clusters down to spacecraft only a few meters across. A 'point-and-goto' interface makes it simple to navigate through the universe to the object you want to visit.
    Celestia is expandable. Celestia comes with a large catalog of stars, planets, moons, asteroids, comets, and spacecraft. If that's not enough, you can download dozens of easy to install add-ons with more objects.

  • New date for Visual Studio 2005 Beta 2

    There is a new date for the release of Visual Studio 2005 Beta 2, and this time it is no April Fool's stupid joke ;-)
    According to http://www.microsoft.com/emea/msdn/betaexperience/, we should have something in our hands the 25th of April.
    This is for EMEA (Europe, Middle-East, Africa), so there may be releases sooner for other regions.

    What can you expect from the Beta Experience?
    • Visual Studio 2005 Team System Beta 2
    • Team Foundation Server Beta 2
    • WeFly247 training DVD
    • SQL Server 2005 Standard Edition Community Technology Preview
    • The Beta Experience newsletter (6-weekly, terminated with the launch of the final version of Visual Studio 2005)