Creating Windows Services in .NET

Creating Windows Services in .NET

uppose that your company’s field reps regularly upload files to the server, and the proper people need to be notified when these files arrive. Perhaps you need to monitor and log the creation of new folders, to ensure that certain files remain read-only, or to gather use data for reports. These and many other similar tasks are certainly within the capabilities of a standard Windows desktop application, and this is the approach that many developers and system administrators take, either running the application continuously or at regular intervals with the help of the Windows Scheduler. While common, this approach is a pretty sure invitation to headache-city. Being desktop apps, such programs are susceptible to intentional or unintentional fiddling from users. In addition, they require some account to be logged on in order to run.

Fortunately there’s a much better alternative for applications that run for extended periods and do not require user interaction: a Windows service. While Windows service applications (previously called NT Services) have been around for a while, they were a real bear to program. With .NET, this has changed. The .NET Framework provides classes that greatly simplify the tasks of creating, installing, and controlling Windows service applications.

While Windows service applications (previously called NT Services) have been around for a while, they were a real bear to program.

A Windows service is a highly specialized type of application designed to run for extended periods in its own Windows session, usually with no user interface. Tasks for which you might use a Windows service include network connection management, disk access monitoring, and certain security tasks. Windows itself always has a variety of services running, most of which the user is never directly aware of. In Windows 2000 you can view a list of services by opening Administrative Tools from the Control Panel, and then opening Computer Management and selecting Services on the navigation tree. The ability to create and deploy Windows services is not something that developers need to do on a regular basis, but in some situations it is by far the best solution.

The .NET Framework’s System.ServiceProcess.ServiceBase class encapsulates essentially all of the “plumbing” required to create and control service applications. By basing your application on this class, most of the difficult work is already done for you. Some versions of Visual Studio .NET (VS.NET) provide a Windows Service application template that creates the skeleton of your application. Note that Visual Basic Standard Edition and Visual C# Standard Edition do not include the Windows Service application template, so you’ll have to start from scratch.

At a minimum , you must add code to two methods in your service class. The Main() method is the entry point for the service and handles instantiating and running the service. Assuming a service named MyService, the code would look like this:

   Shared Sub Main()        Dim ServicesToRun() As _        System.ServiceProcess.ServiceBase     ServicesToRun = New _        System.ServiceProcess.ServiceBase() _        {New MyService()}     System.ServiceProcess.ServiceBase.Run _        (ServicesToRun)      End Sub 

The other method you must code is OnStart(), which executes when the service is started. Code in this method sets your service in motion so it can perform the tasks for which it is designed. For example, if your service monitors disk activity, your OnStart() method would instantiate one or more FileSystemWatcher objects.

Note that running a service and starting a service are two different things.

Note that running a service and starting a service are two different things. Running a service makes it available but does not start it. Once available, a service can be started or stopped either automatically, manually, or programmatically. Depending on the setting of the ServiceBase object’s CanPauseAndContinue property, a service may also be able to pause and continue.

Logging Information
Services typically have no user interface. One of the only ways that you can provide information about the service to administrators is by writing entries to a Windows event log. Thanks to the .NET Framework’s EventLog class, the procedure is quite simple. First, you instantiate an EventLog instance?typically in your service’s Main() method, providing the log name as an argument to the class constructor. You must also specify the Source property for the log?usually a string that identifies your application. For example:

   Dim MyLog As New EventLog(LogName)   MyLog.Source = SourceName  

Then, at other locations in your service, you call the WriteEntry() method to write information to the log. For example:

   MyLog.WriteEntry(LogMessage)  

You can use the Windows Event Viewer applet to view event logs, or you can use the EventLog class in an application to read existing logs. Be aware that creating and writing to a log consumes processor time and system resources, so this technique is best reserved for recording service-related events that are both important and occasional. You would not want to use an event log to record events that happen frequently, as would be the case with a service that monitors disk activity. In this type of situation it would be preferable to maintain information internally within the service and access it as needed..

Some services don’t need controlling; they start when the system boots and run until the system is shut down. You can set a service to start automatically either by setting the ProjectInstaller object’s StartType property or through the Services window of the Computer Management applet.

You can control a service using the ServiceController class. By including an instance of this class in your application (this must be a separate application from the Windows service application itself), you can:

  • Start or stop the service
  • Pause and continue the service (only if the service’s CanPauseAndContinue property is True)
  • Send custom commands to the service
  • Retrieve information from the service

There are three ways to add an instance of the ServiceController class to your project:

  • In the VS.NET Server Explorer, open the Servers node, open the desired server, then open the Services list. Drag the desired service onto your form.
  • Open the Components tab of the Toolbox and drag the ServiceController component onto your form. Set the component’s MachineName property to the name of the server where the service resides (use “.” for the local machine), and set the ServiceName property to the name of the service.
  • Create an instance of the ServiceController class in code, then set its MachineName and ServiceName properties as described above.

Because the Servers node of the Server Explorer is not available in Visual Basic Standard Edition or Visual C# Standard Edition, you must use the second or third technique to add a ServiceController component to your project.

After connecting your ServiceController component to the service, you can:

  • Use the ExecuteCommand() method to send a custom command to the service. The service responds to these commands in the OnCustomCommand() method.
  • Set the service’s CanPauseAndContinue, CanStop, and CanShutDown properties.
  • Use the Start(), Pause(), Continue(), and Stop(), methods to control the service.
  • Create a proxy through which you can communicate with and retrieve information from the service.

The controlling application can be a standard Windows application, or can display itself as an icon in the system tray from which the user can select commands and options. It could also be an ASP.NET application that permits a remote user to monitor and administer a service running on a remote system.

Unlike other types of .NET applications, you must explicitly install a Windows service application on the target system. Fortunately, VS.NET makes this task quite easy. For service projects, the IDE displays a link in the Properties window titled “Add Installer.” When you click the link VS.NET adds the necessary installer classes to your project, as part of a separate module. You can set various properties, the most important of which is the Account property of the ServiceProcessInstaller class. The Account property determines the security context under which the service will run.

The choices are:

  • LocalService: The service has extensive local privileges and presents the computer’s credentials to remote servers.
  • LocalSystem: The service has limited local privileges and presents anonymous credentials to remote servers.
  • NetworkService: The service has limited local privileges and presents the computer’s credentials to remote servers.
  • User: You specify a local or network account, and provide the username and password either as properties or during installation. The service uses the security context of the specified user account.

To install a service you must compile the service project into an exe file, and then run the utility program InstallUtil.exe (installed with the .NET Framework). At a command prompt enter the command:

   installutil servicename.exe 

You must provide the complete path to the service’s exe file. The InstallUtil application installs the specified service. will be installed. After installing the new service, you can find it in the Services window of the Computer Management applet. (You can use the InstallUtil program to uninstall a service as well.)

Windows services are an often overlooked type of application. They are relatively specialized, but for certain type of tasks, usually in the administrative category, they fit the bill perfectly. The .NET Framework provides classes designed specifically for creating and controlling Windows service applications. Given that the required programming is relatively simple, you should take advantage of Windows services.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1