Monday, July 16, 2012

Windows Service in C# with Setup


Today I'll show how to build Windows Service in C# using Visual Studio 2010.
First, open Visual Studio and create Windows Service project.

Windows Service Project in Visual Studio 2010


Visual Studio will create a WindowsService.cs file, let's add some code to it:
public WindowsService()
{
    this.ServiceName = "My Windows Service";
    this.EventLog.Source = "My Windows Service";
    this.EventLog.Log = "Application";            
    this.CanHandlePowerEvent = true;
    this.CanHandleSessionChangeEvent = true;
    this.CanPauseAndContinue = true;
    this.CanShutdown = true;
    this.CanStop = true;

    if (!EventLog.SourceExists("My Windows Service"))
        EventLog.CreateEventSource("My Windows Service", "Application");
}

static void Main()
{
    ServiceBase.Run(new WindowsService());
}

protected override void OnStart(string[] args)
{            
    base.OnStart(args);
    File.Create(@"C:\servicefile.txt");            
}
My windows service simply creates a file when it starts, you can write any other logic instead. Now we need to add an Installer for our service. Mouse right-click on the project to add another class, let's call it WindowsServiceInstaller.cs, put this code inside of it:
[RunInstaller(true)]
public class WindowsServiceInstaller : Installer
{        
    public WindowsServiceInstaller()
    {
        ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
        ServiceInstaller serviceInstaller = new ServiceInstaller();

        //# Service Account Information
        serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
        serviceProcessInstaller.Username = null;
        serviceProcessInstaller.Password = null;

        //# Service Information
        serviceInstaller.DisplayName = "My Windows Service";
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        // This must be identical to the WindowsService.ServiceBase name
        // set in the constructor of WindowsService.cs
        serviceInstaller.ServiceName = "My Windows Service";

        this.Installers.Add(serviceProcessInstaller);
        this.Installers.Add(serviceInstaller);
    }
}
Ok, we have the Installer, so our service can be registered in Windows OS. Now we need to add to our solution a Setup Project which will actually install and uninstall our windows service.

Setup Project in Visual Studio 2010

Once you done, mouse right click on the setup project and choose Add Project Output:

Visual Studio 2010 Add Project Output

Then click on Primary Output and choose your Windows Service project as shown below:

Add Project Output Group (Windows Service project)

Then, mouse right click on Setup Project and click View -> Custom Actions:


Setup Project - View - Custom Actions

Add Primary Output to each folder in Custom Actions as shown below:


Custom Actions - Primary Output

Now build your Windows Service project and then build Setup Project. Once build succeeded you are ready to install your windows service. Mouse right click on Setup project and choose Install (you can also choose then Uninstall when needed):
Click Install on windows service setup project

To check if you have installed your windows service, run Service manager:

Administrative Tools - Services

Look if the service exists in the service list:

Windows Services

Download the source code of this example (Visual Studio 2010 project).

11 comments:

  1. Thank you for this clear and understandable article. I usually find that it's simpler to explore something by example, rather than reaching the guides.

    ReplyDelete
  2. Thanks , very clear and concise.

    ReplyDelete
  3. Very easy to understand the first part but could you explain how to get the Setup Project? I'm using VS 2012 and I do not have it.

    ReplyDelete
    Replies
    1. MSDN has a tutorial that can be used on VS2012 at "http://msdn.microsoft.com/en-us/library/zt39148a.aspx". Just a word of caution, skip the custom action for the uninstaller using the "InstallUtil.exe /u ..." command. It will cause problems with uninstalling the service application and you'll end up having to clean the Registry manually.

      Delete
    2. Any final solution with full source code using VS 2012 and InstallShield Limited Edition or Windows Installer XML ?

      Delete
  4. Attention to details??
    I have never tryed to create a service before.
    I get some errors I think you asume some other code will be there

    Can you provide the sample code?
    Thanks in advance.

    ReplyDelete
    Replies
    1. You are welcome to download the sample code.
      The link is at the bottom of the article.

      http://www.mediafire.com/?o5aak8h5tdop4eh

      Delete
  5. The install option is disabled. I am not able to install it.

    ReplyDelete
  6. Build your setup first then try to install.

    ReplyDelete
  7. Nice to read your article! I am looking forward to sharing your adventures and experiences. COMPUTER Folder Lock App Download - Don't Spend Moment Searching, Study All Regarding PC Desktops Right here password protect files freeware

    ReplyDelete