Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Windows Services » Passing parameters to C# Windows Services

Passing parameters to C# Windows Services

This article explains how to create C# windows service and pass parameters to it.

Technologies: .NET 1.0/1.1, .NET 1.0/1.1,Visual C# .NET
Total downloads :
Total page views :  75451
Rating :
 3.2/5
This article has been rated :  5 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Introduction

Microsoft Windows services enable you to create long-running executable applications that run in their own Windows sessions. These services (e.g. SQL server Service) can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. Whenever you need long-running functionality that does not interfere with other users who are working on the same computer, you should go for windows service

You create windows service in C# as a Microsoft Visual Studio .NET project; defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. Commands that can be sent to a service include starting, pausing, resuming, and stopping the service, and executing custom commands.

After you create and build the application, you can install it by InstallUtil.exe/making setup project/ServiceInstaller.exe and passing the path to the service's executable file

We will create a windows service here which will make a log file and append that log file after specified time interval, we will pass two parameters to windows service, first is the name of the log file to be created and second is time interval in seconds after which new entry will be logged into log file

Creating Windows Service

To create a windows service, in visual studio click on new project and select windows service as shown in following figure.

  • Rename project name to AnandService
  • Add one class and rename it to AnandServiceMain.cs.
  • Rename service.cs class to AnandServiceHandler.cs. Note the main method of services.cs, later on we will move this method to AnandServiceMain.cs
  • Add one more class and rename it to AnandServiceInstaller.cs
  • Add reference to System.Configuration.Install and
  • Right click on project, select properties and change assemble name to AnandService.

Now project explorer should look like this.

Now open AnandServiceMain.cs and paste the following code on it

using System;

using System.Collections;

using System.ComponentModel;

using System.Diagnostics;

using System.ServiceProcess;

using System.IO;

 

namespace AnandService

{

    /// <summary>

    /// Summary description for EventLogWriter.

    /// </summary>

    public class AnandServiceMain

    {

        public string _strLogPath;

        public int _intSleepTime;

 

        public AnandServiceMain()

        {

            //

            // TODO: Add constructor logic here

            //

        }

        public static void Main(System.String[] args)

        {

            AnandServiceMain anandServiceMain = new AnandServiceMain();

            anandServiceMain._strLogPath = args[0];

            anandServiceMain._intSleepTime = Convert.ToInt32(args[1]);

            System.ServiceProcess.ServiceBase.Run(new AnandServiceHandler(anandServiceMain));

        }

    }

}

 

Now open AnandServiceHandler.cs and paste the following code on it

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Diagnostics;

using System.ServiceProcess;

using System.IO;

 

namespace AnandService

{

    public class AnandServiceHandler : System.ServiceProcess.ServiceBase

    {

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.Container components = null;

        AnandServiceMain m_AnandSvs = null;

        System.Threading.Thread AnandThread = null;

 

        int i = 0;

        public AnandServiceHandler(AnandServiceMain AnandSvs)

        {

            m_AnandSvs = AnandSvs;

            // This call is required by the Windows.Forms Component Designer.

            InitializeComponent();

            // TODO: Add any initialization after the InitComponent call

        }

 

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            components = new System.ComponentModel.Container();

            this.ServiceName = "AnandService";

        }

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                if (components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose(disposing);

        }

 

        /// <summary>

        /// Set things in motion so your service can do its work.

        /// </summary>

        protected override void OnStart(string[] args)

        {

            System.Threading.ThreadStart AnandThreadStart = new System.Threading.ThreadStart(WriteToLog);

            AnandThread = new System.Threading.Thread(AnandThreadStart);

            AnandThread.Start();

        }

 

        /// <summary>

        /// Stop this service.

        /// </summary>

        protected override void OnStop()

        {

            // TODO: Add code here to perform any tear-down necessary to stop your service.

        }

        public void WriteToLog()

        {

            bool blnLog = true;

            while (blnLog == true)

            {

                i = i + 1;

                StreamWriter w = File.AppendText(m_AnandSvs._strLogPath);

                Log(i.ToString(), w);

                System.Threading.Thread.Sleep(m_AnandSvs._intSleepTime);

                if (i > 10)

                {

                    blnLog = false;

                }

            }

        }

        public void Log(string logMessage, TextWriter w)

        {

            w.WriteLine("+----------------------------------------------------------------+");

            w.Write("      Log Entry " + logMessage + ": " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n");

            w.Flush();

            w.Close();

        }

    }

}

 

You may have noted that we have removed the main from services.cs (now AnandServiceHandler.cs) and make the separate file AnandServiceMain.cs, so that we can handle the parameters in better and clean way. And pass back them back to AnandServiceHandler.cs.

 

Now open AnandServiceInstaller.cs and paste the following code on it

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Configuration.Install;

 

namespace WindowsService1

{

    /// <summary>

    /// Summary description for ProjectInstaller.

    /// </summary>

    [RunInstaller(true)]

    public class ProjectInstaller : System.Configuration.Install.Installer

    {

        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;

        private System.ServiceProcess.ServiceInstaller serviceInstaller1;

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.Container components = null;

 

        public ProjectInstaller()

        {

            // This call is required by the Designer.

            InitializeComponent();

 

            // TODO: Add any initialization after the InitializeComponent call

        }

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                if (components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose(disposing);

        }

 

 

        #region Component Designer generated code

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();

            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();

            //

            // serviceProcessInstaller1

            //

            this.serviceProcessInstaller1.Password = null;

            this.serviceProcessInstaller1.Username = null;

            this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);

            //

            // serviceInstaller1

            //

            this.serviceInstaller1.ServiceName = "AnandService";

            this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);

            //

            // ProjectInstaller

            //

            this.Installers.AddRange(new System.Configuration.Install.Installer[] {

                       this.serviceProcessInstaller1,

                       this.serviceInstaller1});

 

        }

        #endregion

 

        private void serviceInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)

        {

 

        }

 

        private void serviceProcessInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)

        {

 

        }

    }

}

 

Now compile the project . You will find AnandService.exe in your bin/debug folder, now our exe is ready to install as windows services

Installing Windows Service

Windows Service exe cannot be run directly from the development environment or by clicking on exe. This is because the service in the project must be installed before the project can run.

You can quickly install your service application by using a command line utility called InstallUtil.exe. You can also create a setup project that contains your project's output and create a custom action with it that will run the installers associated with the project and install your service

But here, I am using the utility program ServiceInstaller.exe. ServiceInstaller.exe is a free utility and easy to use. Open on ServiceInstaller.exe you will prompting to enter text in textboxes

  • Service Name - AnandSevice
  • Service Label - AnandSevice
  • Full Path to Executable - D:\DotNet\CSharp\WindowsService1\bin\Debug\AnandService.exe D:\DotNet\CSharp\WindowsService1\AnandService.log 30

Full Path to Executable consists of following values.

D:\DotNet\CSharp\WindowsService1\bin\Debug\AnandService.exe is the path to service exe
D:\DotNet\CSharp\WindowsService1\AnandService.log is name of the log file to be created
30 is the time interval in seconds

Now click on Register service and you will get the confirmation message. Close ServiceInstaller.exe. Now a service has been installed.  Now open on the services from computer management console and you can see the newly created services there. Right click on service and click on Start menu.

Now go to the folder, which you have passed the parameter to create log file (D:\DotNet\CSharp\WindowsService1\AnandService.log). You will see the log file there. Open log file, you can see the entries like following figure.

Conclusion

Windows service application is designed to be long running which don't required user interface. The .NET framework has a great support for windows services, all the code that is required for building, initializing, running, logging and performance is built into the classes on .NET framework. You can explore System.ServiceProcess and System.Diagnostics further.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Anand Thakur

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Compilation ErrorsScott2/2/2007
What can I do to correct this compilation error: Missing partial modifier on declaration of type 'AnandService.AnandServiceHandler'; another partial declarion of this type exists. I am using VS 2005. Thanks!
Reply | Email | Delete | Modify | 
SQL database upload in a windows service?ananth2/28/2007
Hello Sir! I am currently trying sql db updation using the windows service. Do you have any example code for that. I am able to update the db in visual studio. Unable to do it after converting into windows service. can you pls post a code or example for this? thanks Ananth
Reply | Email | Delete | Modify | 
 
 
Re: SQL database upload in a windows service?bhohman3/21/2007

You might try using a try catch block and send the error to the event log.  This might tell you what the error is (could be permissions for the service user).

try

{

//execute query code

}

catch (Exception eSQL)

{

EventLog.WriteEntry(
"UpdatePTSExchLimsValue: SQL - " + eSQL.Message,
EventLogEntryType.Error, 3, 1011);

}

Reply | Email | Delete | Modify | 
Windows Installer WoesJ4/12/2007
In the article you say "You can quickly install your service application by using a command line utility called InstallUtil.exe. You can also create a setup project that contains your project's output and create a custom action with it that will run the installers associated with the project and install your service." I have tried to use the InstallUtil and the ServiceInstaller to create an installation that will pass parameters to my service at startup. I cannot figure out how to do it without resorting to changing the registry keys after the installation. Do you know how to make this work without directly messing with the registry?
Reply | Email | Delete | Modify | 
Windows Installer WoesJ4/12/2007
In the article you say "You can quickly install your service application by using a command line utility called InstallUtil.exe. You can also create a setup project that contains your project's output and create a custom action with it that will run the installers associated with the project and install your service." I have tried to use the InstallUtil and the ServiceInstaller to create an installation that will pass parameters to my service at startup. I cannot figure out how to do it without resorting to changing the registry keys after the installation. Do you know how to make this work without directly messing with the registry?
Reply | Email | Delete | Modify | 
Windows Service in VS 2005Irina4/26/2007
How do you do the same thing in VS 2005. Ther are many examples on how to write Windows Services in 2003, but not in VS 2005. I've spend over a week trying to figure it out, still cannot ...
Reply | Email | Delete | Modify | 
How to Install a software without rebooting the operating systemshruthi9/4/2007
I have a software in c# 1.1 that must be installed on the system with out rebooting the operating system. If you have any idea please let me know as early as possible.
Reply | Email | Delete | Modify | 
Prompt for username and password during service installationsuvarna9/18/2007
Hi Anand, I have a windows service, my requirement is the service shouldn't prompt for any username and password during installation and it should prompt for the same, when the user manually starts the service for the first time. Is there any way to do this. Thanks for u r help.
Reply | Email | Delete | Modify | 
Load Dll From Windows SericeSenthil Rajan10/6/2007
sir, I Created windows Service in C# .net. the Service contain one dll called "Sample.Dll". through another program i want to load that "Sample.Dll". help me Sir. Thank you, Senthil Rajan
Reply | Email | Delete | Modify | 
Where is ServiceInstaller.exeQiming1/16/2008
Hello. I followed the article and try to see if this is working. However, i couldn't find the mentioned software named ServiceInstaller.exe. Can you provide a link for it? Thanks,
Reply | Email | Delete | Modify | 
Cannot find ServiceInstaller.exekarthi8/27/2008
Hi, I couldn't find the serviceinstaller.exe utility. Any one please tell me where i could get that utility. Thanks in advance
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved