asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating an Extensible Windows Service
By Robert Chartier
Rating: 3.9 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    The first article in this series shows how to create a Windows Service that never needs modification and that allows system administrators and developers to develop and deploy custom plug-ins (although changing any of the plug-ins means stopping and restarting the service).

    The second article covers actual plug-in development.

    The code in this article is written with the aid of Visual Studio .NET (VS .NET), but it is not a requirement if you're familiar with the command line compilers that ship with the .NET Framework SDK.

    Downlaod source code

    Step One: Creating the Windows Service

    The first step describes the process of setting up the actual Windows Service class. It will be based on a timer control, which has an interval set by the administrator via the configuration file.

    Open up Visual Studio .NET (VS .NET) and create a New C# Windows Service.


    Figure 1.1 - Creating a New C# Windows Service in VS.NET.

    VS .NET will default to the designer for the Service. We won't need the designer for anything except changing the Service name. Change both "(Name)" and "ServiceName" to "scheduler". Also, switch to the "Solution Explorer", and rename the default file from "Service1.cs" to "Scheduler.cs".

    By default VS .NET will implement a lot of code that is essential for the Service to execute normally. Notice that our Service class derives from the framework's "System.ServiceProcess.ServiceBase" class.

    We must first implement a timer control to run our plug-in at given intervals.

    1. Create a timer object at class scope:

    
    private System.Timers.Timer timer=null;
    
    
    2. Set up the timer within the class constructor:
    
    public scheduler() {
    
    string servicepollinterval = System.Configuration.ConfigurationSettings.AppSettings
    ["servicepollinterval"];
    
    	double interval=10000;
    	try {
    		interval = Convert.ToDouble(servicepollinterval);
    	}catch(Exception) {}
    	
    timer = new System.Timers.Timer(interval);
    	timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );
    
    }
    
    
    Notice that we are getting the timer's interval value by using
    
    System.Configuration.ConfigurationSettings.AppSettings
    ["servicepollinterval"];
    
    
    I will cover the configuration file in more detail in step three.
    
    timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );
    
    
    This sets up the event handler for when the timer elapses. It will be fired when the timer runs for the duration of the set interval. I'll get into more detail on this further down.

    3. Next we need to start and stop the timer based on our Service's events.

    
    protected override void OnStart(string[] args) {
    	timer.AutoReset = true;
    	timer.Enabled=true;
    	timer.Start();
    }
    
    protected override void OnStop() {
    	timer.AutoReset = false;
    	timer.Enabled = false;
    }	
    
    Optionally you can define the OnPause and OnContinue members:
    
    protected override void OnPause() {
    	this.timer.Stop();
    }
    
    protected override void OnContinue() {
    	this.timer.Start();
    }
    
    
    4. The timer's Elapsed Event handler.
    
    timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );
    
    
    This line instructs the Framework to call the "ServiceTimer_Tick" method within our current class when the timer elapses -- that is, when its interval runs its course. So we must implement this method in our class as such:
    
    private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e) {
    	this.timer.Stop();
    	//IMPLEMENT YOUR TIMER TICK HERE
    	this.timer.Start();
    }
    
    
    This is a bare bones version of our timer's elapsed event. Notice that we first "Stop()" the timer, execute the task, and then "Start()" it again. This prevents running into any problems if the code takes longer than the interval. This is optional, of course.

    This is all we need for now in our Windows Service. The next step is to finish creating an installer class so we can install the Service into our system.

    Step Two: Creating the Project Installer

    The Project Installer is responsible for taking our Windows Service class and installing it into our system. We first need to create a class in our current project. Please name it "ProjectInstaller.cs".

    Now I want to review each relevant line marked "//**'X'**" in the entire Project Installer code.

    
    public class ProjectInstaller {
    
    [RunInstaller(true)]  //**1**
    	public class ProjectInstaller : System.Configuration.Install.Installer {  //**2**
    	private System.ComponentModel.Container components;
    	private System.ServiceProcess.ServiceInstaller serviceInstaller1; //**3**
    	private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; //**4**
    
    		public ProjectInstaller() {
    			InitializeComponent();
    		}
    
    	private void InitializeComponent() {
    		this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    		this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    
    		this.serviceInstaller1.DisplayName = "Scheduler_Net";  //**5**
    		this.serviceInstaller1.ServiceName = "Scheduler_Net";  //**6**
    
    		this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;  //**7**
    
    		this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;  //**8**
    		this.serviceProcessInstaller1.Password = null;  //**9**
    		this.serviceProcessInstaller1.Username = null; 
    
    		//**10**
    		this.Installers.AddRange(new System.Configuration.Install.Installer[] {
    
    	this.serviceProcessInstaller1,
    	this.serviceInstaller1});
    		}
    
    	}
    }
    
    
    #1. Taken right out of the VS .NET documentation:

    "Specifies whether an installer should be invoked during installation of an assembly." (ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemComponentModelRunInstallerAttributeClassTopic.htm)

    #2. Notice that our ProjectInstaller class must be derived from the Framework-supplied "System.Configuration.Install.Installer"

    #3. The Install Utility needs a ServiceInstaller when it installs the Service application. It contains properties for such things as the Service Display Name, the Service name, Start Type, etc.

    #4. A ServiceProcessInstaller is the actual class that will install the ServiceInstaller and its executable into the system, typically through the use of a tool such as "InstallUtil.exe" (more on this later).

    If you would like to read more on these, please refer to the documentation (ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemServiceProcessServiceInstallerClassTopic.htm).

    #5 and #6. Demonstrates how to use the ServiceInstaller to set the desired DisplayName and ServiceName of the Service that is going to be installed.

    #7. Demonstrates how to set the StartType of the Service. Your options include:

    1. Automatic
    2. Disabled
    3. Manual
    #8. Demonstrates how to use the ServiceProcessInstaller to specify the desired default user account this Service will use once installed.

    #9. Demonstrates how we could set the username and password if we were to choose the option, "System.ServiceProcess.ServiceAccount.User", for the desired user account.

    #10. This binds the ServiceProcessInstaller, along with our ServiceInstaller, into our Installers. Installers are inherited from our derived class. Again, if you want more information on this, please consult the documentation (ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemConfigurationInstallInstallerClassInstallersTopic.htm).

    Step Three: Creating the Configuration File

    The easiest way to configure the service is though the standard "APPNAME.EXE.config" (config) file, which the Framework automatically allows you to use through the "System.Configuration.ConfigurationSettings" class. With this class, we can actually create separate sections within the same configuration file, one for the service itself and others for any plug-ins we create. This simplifies administration to one XML file.

    As mentioned in step one, #2, we are using the "System.Configuration.ConfigurationSettings" class to read the Timer interval into our class. It is using the standard "appSettings" section in the config file. See the XML snippet in Figure 1.2 below.

    For our purposes we want to create and use different sections for our plug-ins. We first need to create a "configSections" node with a "sectionGroup" for our plug-ins. The easiest way to describe this is to look at a slimed down version of the config file.

    
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <!-- application specific settings -->
      <configSections>
        <sectionGroup name="PlugInSettings">
          <!--notice we have an entry for each plugin's settings node below-->
            <section name="TemplatePluginSettings" type="System.Configuration.NameValueSectionHandler" />
        </sectionGroup>
      </configSections>
      
      <appSettings>
        <add key="servicepollinterval" value="10000" />       
      </appSettings>
      
      <PlugInSettings>
        <TemplatePluginSettings>
          <add key="whatever" value="whatever-value" />
        </TemplatePluginSettings>
      </PlugInSettings>
    </configuration>
    
    
    Figure 1.2 A snippet of the XML Configuration File

    To use the different sections for each item under the PlugInSettings node, you will need to create a special collection for that section. In part 2, we will develop custom plug-ins to interface with the Windows Service.

    About the Author

    Robert Chartier has developed IT solutions for more than nine years with a diverse background in both software and hardware development. He is internationally recognized as an innovative thinker and leading IT architect with frequent speaking engagements showcasing his expertise. He's been an integral part of many open forums on cutting-edge technology, including the .NET Framework and Web Services. His current position as vice president of technology for Santra Technology (http://www.santra.com) has allowed him to focus on innovation within the Web Services market space.

    He uses expertise with many Microsoft technologies, including .NET, and a strong background in Oracle, BEA Systems, Inc.'s BEA WebLogic, IBM, Java 2 Platform Enterprise Edition (J2EE), and similar technologies to support his award-winning writing. He frequently publishes to many of the leading developer and industry support Web sites and publications. He has a bachelor's degree in Computer Information Systems.

    Robert Chartier can be reached at rob@aspfree.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 28, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 2
    In the second part of his series on building N-tier web applications using ASP.NET 2.0 and SQL Server 2005, Thiru Thangarathinam covers the business logic and user interface layers. In the process, he also examines some new features in ASP.NET 2.0 that greatly simplify the development process.
    [Read This Article]  [Top]
    Jul 14, 2005 - An Innovative Technique for Creating Reusuable Page Templates in ASP.NET 1.x
    Code reusuability is one of the major goals of any good object-oriented programmer. While the ASP.NET framework has made code reusuability easier and more elegant than it was in classic ASP, one area where reusuability could be improved is at the UI level. This article outlines a technique that you can use in ASP.NET 1.x that allows every page in your web application to inherit not only the functionality of a base page, but its UI as well.
    [Read This Article]  [Top]
    Jun 23, 2005 - Monitoring SharePoint Usage through an ASP.NET Web Application
    In this article, Gayan Peiris looks at creating an ASP.NET web application that will display the usage details of a selected SharePoint site. Building such an application enables SharePoint administrators to gather all SharePoint usage data from a central location.
    [Read This Article]  [Top]
    May 12, 2005 - Retrieving SharePoint Site Information in an ASP.NET Web Application
    In this article, Gayan Peiris examines using the SharePoint Object Model to access SharePoint site information from an ASP.NET web application. It should be of particular interest to SharePoint administrators who can use the included code as a starting point for development of their own web-based SharePoint administration application.
    [Read This Article]  [Top]
    Dec 23, 2004 - Automated Deployment for Side By Side .NET Web Apps for Visual Studio .NET 2003
    In this article, David Every outlines a step-by-step account of how he solved the problems he encountered while implementing an auto-deployment process. He also describes how to create a stable process for automated remote .NET deployment featuring "side-by-side" capability.
    [Read This Article]  [Top]
    Sep 29, 2004 - Developing Web Parts with ICellConsumer Interface
    Most default SharePoint Server Web Parts can be connected across organizations. The third article in this series shows how to develop connectable Web Parts that consume information provided by other Web Parts.
    [Read This Article]  [Top]
    Aug 10, 2004 - Implementing and Promoting Daily Builds
    Automatic daily builds is a well known software engineering best practice. This article introduces a strategy for implementing and promoting daily builds and offers tips and tricks for preventing and fixing breaks.
    [Read This Article]  [Top]
    Jun 21, 2004 - Using Open Source .NET Tools for Sophisticated Builds
    Building an application can be more than pressing F5. With an increasing number of quality packages being released, developers for the .NET platform now have options to create a very sophisticated build process. Aaron Junod describes a sample build environment and shows how a number of tools can work together to make reliable, predictable, and value-added builds.
    [Read This Article]  [Top]
    Jun 24, 2003 - Programming for the Palm Part 1 - Creating the Palm Application
    The first part of this three part series walks through the process of creating a mobile blog application using a BASIC development environment for Palm OS devices called NS Basic. Subsequent articles will focus on synchronizing the data to the desktop using C# and creating an installer.
    [Read This Article]  [Top]
    Jun 18, 2003 - Online Database Functions Testing Tool
    This short article provides source code for a classic ASP online database functions testing application and shows how to configure and use the tool for either SQL Server or Oracle.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES