Archives / 2003 / October
  • Managing Windows Services

    It may happen that you wish to connect to and control the behavior of a Windows Service - programatically. There's a .NET class called ServiceController just to do that. It represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it. You will most likely use the ServiceController component in an administrative capacity. For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snapin does not support custom commands.

    Here's an example to check the status of the Telnet Windows Service and start/stop it as needed:

    Dim sc As New ServiceController("Telnet")


    If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then




    End If



    The ServiceController class can also be used to manage services on another machine (by specifying the MachineName property). The ServiceController class requires the System.ServiceProcess namespace which you may need to add a reference to.


  • Articles at MSDNAA

    The following two articles at MSDNAA are pretty interesting:

    Use Design Patterns to Simplify the Relationship Between Menus and Form Elements in .NET - In Windows Forms applications, similar commands, such as those in a menu and their counterparts on a toolbar, are not automatically related. They don't fire the same event or run the same handler routine. Yet code that allows the same or similar user commands to fire the same code simplifies development. This article describes the principles of command management and why it's important to have functional commands that are not exclusive to any one UI element.

    Performance Comparison: Exposing Existing Code as a Web Service - This article provides a performance comparison between three Web Service implementations that expose existing COM components and Transact SQL code and an equivalent Web Service implementation using ASP.NET.

    More technical articles at MSDNAA ...


  • Avalon Screen Saver Contest and Longhorn Installation Tips

    XAML != XUL ?!?!

    Avalon Screen Saver Contest Info: Develop a screen saver using the new Avalon technologies in Microsoft Longhorn and you could win a Media Center edition or an XBox -- we'll choose the best three entries designed during Microsoft's Professional Developer Conference. Visit the PDC hands-on-labs to learn how to build your screen saver using Microsoft Longhorn and Avalon. Unfortunately, for PDC attendee's only.

    Clemens Vasters has got the “PDC build” of Longhorn running on Virtual PC. If you plan to install a copy as well, which hopefully even the PDC absentee's will be able to when the alpha/beta version is released, don't forget to review his notes and tips on Longhorn installation. Andrej Budja writes about the Top 10 things to remember before installing Longhorn.

    BTW, WinSuperSite has some Longhorn “Aero” screenshots on display.


  • Longhorn Development Center and XAML

    The Longhorn Developer Center @ MSDN is live as expected. And so is the Longhorn SDK.

    Scott Hanselman moblogs (cool term, for mobile/handheld blogging) from PDC - “They've brought out the folks from Adobe. They've got an image editing program (Adobe After Effects) that can export images/vectors/UI as XAML (eXtensible Application Markup Language) declarative UI directly! They imported the XAML file directly into VS.NET and get a form. Its a VERY dynamic, sexy UI with animations, charts, gradients ...”. Thanks Scott - for your amazing real time updates from PDC.


  • Thread Isolator

    While reading an article at CodeProject, I came across AmThreader - a code generator for “converting any singlethreaded .NET class to a multithreaded one”. However, what it actually does is create a class wrapper for any .NET class (not necessarily C#) and any call of wrapper class method will be translated to original class call but in a separate thread. For independent developers AmThreader is free.


  • Inno Setup

    Inno Setup 4.0.9 has been released. I use and recommend it for packaging & deployment of Windows desktop and client applications. Its scripting based compiler system provides a lot of flexibility. And, it is open source (Borland Delphi).

    A few colleagues at work are also writing a similar installer program in VB.NET. They tell me that its also going to have a scripting based compiler system (like Inno Setup). I'll post a demo of their product as soon as I get to review it myself.


  • Free ASP.NET Training

    Free ASP.NET training sessions are scheduled in the month of October and November 2003 in New York, Florida and Virginia. A great offer indeed!

    I just wish such events were also held (atleast occasionally) in Europe and Asia - where there's a growing community of .NET developers, most of whom generally won't be able to afford the $599 price tag on such traning sessions conducted by Microsoft Certified Training Education Centers.


  • Joel on Developers and Exceptions

    In his latest article, Joel Spolsky refers to the Empower Program for ISVs: “If you're a software company willing to commit to developing software for any variant of Windows, you can join the Empower Program for ISVs, which entitles you a huge pile of software at the ridiculously low price of $750.” Not to mention, the video of Microsoft CEO Steve Ballmer in the advanced stages of ecstatic frenzy chanting the “Developers” mantra ...

    It seems like Joel and Ned Batchelder are in bit of a tussle over a hot topic these days: Exceptions. There has been a growing debate between the two over exceptions and error handling in/through code. In my opinion, particularly in context of .NET, exceptions provide a structured and object oriented model for error handling which is of extreme relevance, directly or indirectly, right from the development & testing phase to product marketing & acceptance by customers. Having said that, comments and discussions by two industry experts is enlightening.

    BTW, there's a nice article on Ten tips for .NET exceptions at CNET. The article is a bit outdated but a good read.


  • Windows Form in Full Screen "Kiosk Mode"

    [Quick Tip] The following lines of code (VB.NET) will produce a full screen Windows form - like the kiosk mode in Internet Explorer (press F11 to toggle). This screen mode is quite useful in situations where full screen user interactivity is required or the GUI demands full screen usability, like in multimedia demos, POS systems, embedded kiosk applications, touchscreen-driven apps, software installer programs etc.

    With Me

    .MaximizeBox = False

    .MinimizeBox = False

    .TopMost = True

    .FormBorderStyle = System.Windows.Forms.FormBorderStyle.None

    .WindowState = System.Windows.Forms.FormWindowState.Maximized

    End With


  • Run .NET Code from SQL Stored Procedures

    The CLR Proc Container is free software that enhances the capabilities of SQL Server stored procedures by opening a door to the .NET world. Code written in any .NET language can be invoked from stored procedures, providing stored procedures all the functionality of the full .NET runtime. Named procedures can be defined in .NET, dynamic procedures can be created and run, and binary objects passed between stored procedure code and the .NET object.


  • FileSystemWatcher Tips

    The .NET FileSystemWatcher class makes it possible to quickly and easily launch business processes when certain files or directories are created, modified, or deleted. The FileSystemWatcher class, for example, can be quite useful in application integration, by way of monitoring incoming data files and processing it once an event is raised. It listens to the file system change notifications and raises events when a directory, or file(s) in a directory, changes. The component can watch files on a local computer, a network drive, or a remote computer.

    I've come to realize that it does need some understanding of this class to make it work efficiently. For example, a denial-of-service attack is possible if a malicious program gains access to a directory the FileSystemWatcher component is monitoring, and which thereby generates so many changes that the component cannot manage them and can cause a buffer overflow or other drastic effects. Following are some tips and notes on how to use the FileSystemWatcher class to build a more robust solution:

    1. Events being raised twice - An event will be raised twice if an event handler (AddHander FSW.Created, AddressOf FSW_Created) is explicitly specified. This is because, by default, the public events automatically call the respective protected methods (OnChanged, OnCreated, OnDeleted, OnRenamed). To correct this problem, simply remove the explicit event handler (AddHandler ...).

    2. Events being raised multiple times - In some cases a single event can generate multiple events that are handled by the component. Because FileSystemWatcher monitors the operating system activities, all events that applications fire will be picked up. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Such multiple events can be correctly handled and processed by using a simple boolean flag check (for a first-come-first-serve approach) or by setting the FileSystemWatcher.NotifyFilter property to one of the NotifyFilters values.

    3. Thread Safety - Any public static (Shared in VB) members of this class type are thread safe. Any instance members are not guaranteed to be thread safe.

    4. File System Type - The FileSystemWatcher does not raise events for CDs and DVDs, because time stamps and properties cannot change for such media types.

    5. Filter - The Filter property can be used to watch for changes in a certain type(s) of file(s) (eg: "*.txt"). To watch for changes in all files, set the Filter property to an empty string (""). Hidden files are also monitored by the FileSystemWatcher.

    6. Internal Buffer - The FileSytemWatcher component uses an internal buffer to keep track of file system actions. You should set the buffer to an appropriate size for the approximate number of events you expect to receive. By default, the buffer is set to a size of 4 KB. A 4 KB buffer can track changes on approximately 80 files in a directory. Each event takes up 16 bytes in the buffer, plus enough bytes to store the name of the file, in Unicode (2 bytes per character), that the event occurred on. You can use this information to approximate the buffer size you will need. You (re)set the buffer size by setting the InternalBufferSize property. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. Setting the Filter does not decrease what goes into the buffer. If you are using Microsoft Windows 2000, you should increase the buffer size in increments of 4 KB, because this corresponds to the operating system's default page size. With any other operating system, you should increase the buffer size in increments that correspond to the operating system's default page size. If you are unsure of the default page size for the operating system you are using, the safest way to proceed is to just double the original size of the buffer. This will maintain the original interval needed for your operating system.

    7. Directories - Changing a file within a directory you are monitoring with a FileSystemWatcher component generates not only a Changed event on the file but also a similar event for the directory itself. This is because the directory maintains several types of information for each file it contains - the names and sizes of files, their modification dates, attributes, and so on. Use the IncludeSubdirectories property to indicate whether or not you want to include the subdirectories of the directory you are watching. If you turn this off when you do not need it, you will receive fewer events than when it is turned on.

    8. Stop Watching - When file system monitoring is not needed anymore, you should set the EnableRaisingEvents property to False to disable the component, otherwise the component will continue listening.

    The FileSystemWatcher class provides a useful feature but it should be implemented along with a thorough examination.


  • Scheduled Execution in ASP.NET

    On a .NET-based project, I had the need to run scheduled maintenance tasks on the web server. My first preference was building a Windows Service or a Console Application (and scheduling it using the Windows Scheduler to run at regular intervals). However, this option was not feasible considering that the client for whom I am developing the application plans to host it in a shared hosting environment where they don't have the privilege to deploy & run a Windows Service or Console Applications. So I had to come-up with an alternate approach, something that's robust, efficient and flexible - if not as suitable for the concerned task as a Windows Service or a Console Application.

    I read many similar concerns about scheduled execution using ASP.NET by fellow programmers on the community discussion forums. I finally came across an article on how to Force ASP.NET Apps to Keep-Alive by Paul Wilson. At first sight, it had the precise solution to what I was looking for - a simple Timer and Thread based workaround to pre-compilation plus background event invocation. Paul's approach basically involves making the Global.asax file to inherit from his custom GlobalBase class (instead of System.Web.HttpApplication). It also exhibits an Application_Elapsed event which is pretty much what I needed.

    Paul's solution worked just fine in terms of its primary objective - force ASP.NET apps to keep-alive. However, I encountered a strange problem with the Application_Elapsed event. For some reason, the event was being triggered twice on each timer invocation. I spent sometime trying to figure out the cause of this behavior and even talked to Paul on what could be the problem. Paul was pretty busy with some other stuff so I decided to take another walkthrough of the GlobalBase class. While everything seemed fine in Paul's code, an unexpected name change did the trick. First a quick glance at the snippet (modified to show only relevant code) from the class:

    Namespace Wilson.WebCompile

          Public Class GlobalBase

                Inherits System.Web.HttpApplication


                Private Shared _timer As System.Timers.Timer = Nothing


                Public Event Elapsed As EventHandler



                Public Overrides Sub Init()



                        _timer = New System.Timers.Timer(60000 * Me.KeepAliveMinutes)

                        AddHandler _timer.Elapsed, AddressOf KeepAlive




                End Sub


                Private Sub KeepAlive(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)



                End Sub



          End Class

    End Namespace

    I simply changed the name of the Event/EventHandler from Elapsed (to myElapsed) and it worked. The Application_Elapsed event (in the Global.asax file) was now being triggered only once per timer call as intended. However, I still haven't been able to understand what's the reason behind this behavior. My guess is that the Elapsed EventHandler of the class was somehow colliding with the Timer's Elapsed event. Maybe someone has an explanation to it.

    As Paul has also mentioned in his article that this approach of forcing apps to keep-alive is just a “hack”. It doesn't guarantee timed execution on the server. But I'm pretty sure its robust & time-tested as Paul has been using it on his site for quite a long time now.


  • .NET India User Groups

    MSDN .NET India User Groups exist to help facilitate education and knowledge exchange among developers, architects and managers (residing/working in India) with an interest in Microsoft's .NET technologies. They provide a great place for local developers to come together to learn about .NET technologies, to network with their peers and to foster a sense of community among developers learning and using the same technologies.

    Locale - Currently active in/for 11 Indian cities - INETA member.

    BTW, lately I have been unable to access any of the official Indian .NET User Groups web sites (localized MSN Groups) from India - I wonder why? Hmmm ...


  • Longhorn Bits

    On October 27 2003, the day after the PDC starts, Microsoft will launch the "Longhorn" Developer Center on MSDN. The actual product is expected sometime in 2005 but all the buzz reminds me of the hype that was before Windows 95 was launched. Ofcourse, this time, its a more mature product and hopefully less buggy.

    Among many other things that Longhorn will bring to your desktop or server, its core components will (hopefully) be:

    • Aero - the 3D-rendering user interface
    • Avalon - the core set of application programming interfaces (APIs) for handling graphics/presentation chores
    • Indigo - the next release of Microsoft's Web-services infrastructure that will underlie the OS; think .NET Remoting + MSMQ + ASMX + .NET Enterprise Services (a k a COM+)
    • WinFS - the Windows File System data-store that Longhorn will borrow from Microsoft's SQL Server "Yukon" database; will be able to store XML and metadata in a single place
    • Palladium - the next-generation secure computing base

    Robert McLaws brought to attention some Longhorn snapshots at


  • Free .NET Web Hosting

    Some guys at work and others online, have been asking me for some suggestions on a free .NET web host. Free hosting may be a good way to play around and learn .NET (ASP.NET in particular) but by no means is it suitable and reliable for live production-level applications. Although I strongly recommend a (paid) basic shared hosting plan for any meaningful development but I just did a bit of lookup and came-up with the following list of free .NET web hosts:

    1. Web Matrix Hosting - 20 MB Space, 10 MB SQL Server 2000 DB, .NET Framework 1.1, Windows Server 2003 hosting, FTP/MMC support

    2. Brinkster - 30 MB Space, No DB support (but I guess Access DB works)

    3. ASPfreeServer - 100 MB Space, Access DB, FTP

    4. InnerHost - ASP.NET Beta 2 trial hosting, 100 MB Space, No DB support

    5. ASPECTO - 50 MB Space, Access DB

    6. MyLittleHost - Access and MSDE 2000 DB, FTP etc.

    Disclaimer: I'm not related or working for any of the above sites/companies. The above suggestions are merely based on personal opinion. Use at your own risk.


  • .NET Framework Class Browser

    I find the .NET Framework Class Browser very convinient. It has saved me a lot of time on a daily basis looking for namespaces, classes and interfaces. I remember the commonly used namespaces and their respective classes but information on rarely used namespaces and their classes is just a click away with this web site. Nice quick reference material!


  • XML Resume Library

    One of the development teams at my office recently used the XML Resume Library for a document management project in ASP.NET. Although it was a pilot project for a HR consultancy but the guys here seem to be appreciating the usefulness of the library. Earlier, we were planning to develop our own custom solution to document management but apparently the time-to-delivery was cut-short by days from using the existing library. The XML Resume Library is an XML and XSL based system for marking up, adding metadata to, and formatting resumes and curricula vitae.

    It consists of these components:

    • An XML Document Type Definition (DTD) for describing resumes.
    • Three XSL stylesheets to transform an XML resume into:
      • Web-ready HTML,
      • Print-ready PDF, or
      • Plain, unformatted text
      • RTF transforms (requires third-party software)
    • A targeting filter that allows you to focus your resumes to a particular employer without manually editing your source resume file.

    Blogging Tip: One may use Google to search Just type after/before the search keywords. Maybe its too obvious.


  • Yahoo Groups blocked in India

    Lately, I haven't been able to access the Yahoo Groups ( from back here in India. There are tons of .NET-related groups which I browse once in a while to respond to queries, get answers to my own questions and share custom code snippets. Unfortunately, following an order by the Government of India, Indian ISP's have blocked access to Yahoo Groups due to some political and anti-national content. However, I figured out a quick “hack” to still access Yahoo Groups by accessing any one of the localized gateways like or

    I still haven't understood the need to ban the entire groups community just because of some violating elements. Instead of censoring the whole thing it would have been more sensible to appoint a task force and restrict those few violating elements. What's next - barring Internet!


  • F# Compiler

    Following an e-mail from a friend, I browsed the information on the F# compiler (a Microsoft Research project). Seems pretty cool but not something I would like to get a taste of right-away. There's already too much - more relevant (atleast for me) to soak. But its good to see that the .NET-based development context is expanding and programmers from “unmanaged” code domains can easily try-out or maybe even migrate to .NET with the help of available resources like this one.

    The F# compiler is an implementation of an ML programming language for .NET. F# is essentially an implementation of the core of the OCaml programming language (see F#/OCaml/ML are mixed functional-imperative programming languages which are excellent for medium-advanced programmers and for teaching. In addition, you can access hundreds of .NET libraries using F#, and the F# code you write can be accessed from C# and other .NET languages. Please visit the F# Compiler Preview web site for more information.