Showing posts from March, 2012

Properly disposing COM objects in your .NET code

Here at work, we are using a third party component where they provide a COM interface. We're using .NET code so we are using COM interop to use the COM object. Remember back in the VB6 days when you would set your objects to null when you're done with it? Well, so did someone else here, because that's what I saw. I'm going to show you an example using the Microsoft Excel Type Library. Here's some sample code that I wrote that will open up an Excel file and get the text value from a cell in the first worksheet.      using  System;      using  Microsoft.Office.Interop.Excel;      internal   class   Program     {         #region  Methods          private   static   void  Main( string [] args)         {              var  app =  new   Application ();              var  books = app.Workbooks;              var  book = books.Open( @"C:\Temp\doc.xlsx" );              var  sheets = book.Sheets;              var  sheet = sheets.Item[1]  as   Workshee

Debugging .NET Windows Service apps more easily

Here at work, I keep seeing a couple of my fellow developers struggle to debug their Windows Service apps that they're writing.  What they have to do is remove the service, install the new version of the service, start the service, then attach the debugger. If there's an error when the service first starts up, the workaround is to introduce a Thread.Sleep before it actually does anything, giving you enough time to attach the debugger. By default, you can't directly run the service from within Visual Studio. If you try, you get the following message: If you look at the code that actually starts the service, you'll see that it's not that different from a console app. By default, it looks something like this:      internal   static   class   Program     {          ///   <summary>          ///  The main entry point for the application.          ///   </summary>          private   static   void  Main()         {              ServiceBase [] Ser