How to run a service as a windows application


In this article , author explains about How to run a service as a windows application

Windows services are usefull to run any process un attended. However, it is a pain to debug and test services during development. This code sample shows how to run your application as either a Windows NT service or as Windows application based on a condition in the app.config file.

Since Windows services will not have references to System.Windows.Forms.Dll, you must add a reference to it from your project so that you can use Windows Forms.

Next step is, create an entry in your config file as shown below:


<appSettings>
<add key="RunAs" value="service"/>
</appSettings>


Now, look at your service class file and locate the code something like below:

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


The above piece of code starts your application as a Windows Service. All you have to do is, based on the key in your app.config, execute above code or launch the Windows Form.

Add new Form to your project called "MyForm". Now change the above code as shown below:


Dim runAs As String = System.Configuration.ConfigurationSettings.AppSettings("RunAs")
If runAs = "service" Then
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
Else
System.Windows.Forms.Application.Run(New MyForm)
End If


The above code looks for the key in your app.config and based on teh value, it either starts the service or launches the window form application.

If you do not like to use the app.config entry, an alternative approach is to use the compiler directive #DEBUG


#If DEBUG Then
System.Windows.Forms.Application.Run(New MyForm)
#Else
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
#End If


In this case, when the code is compiled in debug mode, it will run as a window application and run as a service in all other cases. In most cases, during development, you will be using DEBUG mode and RELEASE mode when deployed to QA or client.


Comments

Author: priyadharshini22 Feb 2010 Member Level: Bronze   Points : 0

can u explain this in c# plz suggest me



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: