Cinchoo – Simplified Windows Tray Application Development

Download sample – 20.3 KB

Contents

1. Introduction

Cinchoo is the application framework for .NET. One of the main functionalities it provides to the users is application configuration management. Application configuration is the information that application reads and/or writes at run-time from the source.

One another important feature it offers to the developers community is the unified, generic application host to build and run application in different modes. Code once, run the application as either Console, Windows, WPF, Windows Service or Windows Tray application.

In this article, I’m going to illustrate how to use this library to create Windows Systems Tray application. It is a simpler, fluent model for configuring everything about your tray application in one place. Making it as library letting you to concentrate yourself on the core development tasks. Cinchoo provides a clean and easy API to develop and run Windows systems tray applications.

2. Requirement

The application host library is written in C# for the .NET 4.0 Framework. It is part of Cinchoo framework, which is a great library with lot of features like Configuration Management, common ApplicationHost, Shell features etc.

3. “Hello World!” Sample

Lets begin by looking into a simple example of a windows systems tray application displaying ‘Hello World!’ tooltip text.

Download the latest Cinchoo binary here. (Nuget Command: Install-Package Cinchoo)

  • Open VS.NET 2010 or higher
  • Create a sample VS.NET (.NET Framework 4) Console Application project
  • Add reference to Cinchoo.Core.dll
  • Use the Cinchoo.Core namespace
  • Copy and paste the below application host object

Listing 3.1 Defining ApplicationHost object

[ChoApplicationHost]
public class HelloWorldAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.TooltipText = "Hello World!";
    }
}

The code above illustrates about defining ApplicationHost object. First thing define a ApplicationHost (ex. HelloWorldAppHost) class from ChoApplicationHost, it indicates that this object is an ApplicationHost object. And it must be decorated with ChoApplicationHostAttribute to complete the definition.

In this example, we override ApplyGlobalApplicationSettingsOverrides method. In there, we instruct the application to run as Tray Application by setting TurnOn member of TrayApplicationBehaviourSettings object to true. Set the TooltipText value to “Hello World!”, this will display the message when you mouse over the tray icon.

Listing 3.2 Main Method

class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(args);
    }
}

We start by calling ChoApplication.Run() method in the main entry of the application. That all. All the heavy lifting of configuring, running the application as tray application is done by the library under the hood. Now your application is tray application enabled application. Lets try for yourself.

4. Defining Application Host Object

4.1 ChoApplicationHostAttribute

All application host objects must be decorated by ChoApplicationHostAttribute. An application must have atleast one application host object defined. Cinchoo framework will discover them at the application startup.

4.2 ChoApplicationHost

All application host objects must be derived from ChoApplicationHost class. By default, it provides basic wire frame of running tray application without making any customization. Some cases, you may want to customize the way you want. In such cases, override nessasary overrides in them. An application must have one application host object defined either in the entry assembly or referenced assemblies. In this object, you can override number of methods for your needs to customize the tray application.

4.2.1 ApplyGlobalApplicationSettingsOverrides() Method

When implemented in a derived class, executes when a application is launched. In here, you have option to override tray application configuration parameters to customize it. Please refer section TrayApplicationBehaviourSettings for more information.

4.2.2 AfterNotifyIconConstructed() Method

When implemented in a derived class, executes when a application runs in Tray application mode. In this method, you can change the tray icon properies. Please refer section ChoNotifyIcon section for more information.

4.2.3 OnTrayAppAboutMenuClicked() Method

When implemented in a derived class, executes when user clicks the ‘About’ menu item from the context menu. In here, you can display the product information of your application.

4.2.4 OnTrayAppExitMenuClicked() Method

When implemented in a derived class, executes when user clicks the ‘Exit’ menu item from the context menu. In here, you can perform any cleanup action of your application.

4.2.5 OnTrayAppHelpMenuClicked() Method

When implemented in a derived class, executes when user clicks the ‘Help’ menu item from the context menu. In here, you can display help information for your application.

4.2.6 OnTrayAppOpenMenuClicked() Method

When implemented in a derived class, executes when user clicks the ‘Open’ menu item from the context menu. By default, Cinchoo framework will open the main window of your application, if any specified. This default behaviour can be overriable to perform any custom actions.

4.2.7 MainWindowObject Property

It is a property returns the main window of your application. Default is null. In this case, your application is windowless tray application. This property can be overridable to return either System.Windows.Forms.Form or System.Windows.Window object.

4.2.8 ApplicationObject Property

This property mainly used for WPF application. It returns an object of System.Windows.Application object.

5. Configuration

5.1 TrayApplicationBehaviourSettings

This is easiest way to customize your tray application. Either override the ApplyGlobalApplicationSettingsOverrides() method in your Application Host object or open the ChoCoreFrx.xml configuration file to manipulate this object properties. Cinchoo framework uses them to customize the tray application before launching them.

5.1.1 TurnOn

Gets or sets the turn on switch the Tray Application.

Listing 5.1.1.1 Set TurnOn programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.BalloontipText = "Hello World!";
    }
}

Listing 5.1.1.2 Set TurnOn via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the boolean value in ‘turnOn’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="true" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon />
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.2 BalloonTipText

Gets or sets the text to display on the balloon tip associated with the NotifyIcon.

Listing 5.1.2.1 Set BalloonTipText programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.BalloontipText = "Hello World!";
    }
}

Listing 5.1.2.2 Set BalloontipText via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the text in ‘balloonTipText’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon />
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.3 TooltipText

Gets or sets the ToolTip text displayed when the mouse pointer rests on a notification area icon.

Listing 5.1.3.1 Set TooltipText programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.BalloontipText = "Hello World!";
    }
}

Listing 5.1.3.2 Set TooltipText via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the text in ‘tooltipText’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon />
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.4 TrayIcon

Gets or sets the current icon. It will display an icon for an application in the notification area.

Listing 5.1.4.1 Set TrayIcon programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.TrayIcon = @"C:\Sample.ico";
    }
}

Listing 5.1.4.2 Set TrayIcon via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the path to icon file in ‘trayIcon’ element under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.5 ShowInTaskbar

Gets or sets a value indicating whether the main window is displayed in the Windows taskbar.

Listing 5.1.5.1 Set ShowInTaskbar programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.ShowInTaskbar = true;
    }
}

Listing 5.1.5.2 Set ShowInTaskbar via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify boolean value in ‘showInTaskbar’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.6 HideMainWindowAtStartup

Gets or sets a value indicating whether the main window should be displayed or not at the application startup.

Listing 5.1.6.1 Set ShowInTaskbar programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.HideMainWindowAtStartup = true;
    }
}

Listing 5.1.6.2 Set ShowInTaskbar via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify boolean value in ‘hideMainWindowAtStartup’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.7 HideTrayIconWhenMainWindowShown

Gets or sets a value indicating whether the tray icon should be hidden when main window is displayed.

Listing 5.1.7.1 Set HideTrayIconWhenMainWindowShown programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.HideTrayIconWhenMainWindowShown = true;
    }
}

Listing 5.1.7.2 Set HideTrayIconWhenMainWindowShown via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify boolean value in ‘hideTrayIconWhenMainWindowShown’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.8 TurnOnMode

Gets or sets a value indicating when the application is turned on to tray application mode. There are 3 modes to choose from

  1. OnMinimize (Default)
  2. OnClose
  3. OnMinimizeOrClose

Listing 5.1.8.1 Set TurnOnMode programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.TurnOnMode = ChoTrayAppTurnOnMode.OnMinimize;
    }
}

Listing 5.1.8.2 Set TurnOnMode via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the ChoTrayAppTurnOnMode value in ‘turnOnMode’ attribute under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.9 ContextMenu Settings

Gets or Sets the visibility of each of menu items in the default context menu displayed in the tray icon. Below are menu items can be controled via this settings object

  1. About
  2. Help
  3. Exit
  4. AlwaysOnTop
  5. RunAtSystemsStartup
  6. ShowInTaskbar

Listing 5.1.9.1 Set ContextMenuSettings programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.ContextMenuSettings.DisplayShowInTaskbarMenuItem = false;
    }
}

Listing 5.1.9.2 Set ContextMenuSettings via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the boolean values to each attributes in ‘contextMenuSettings’ element under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
      <contextMenuSettings displayAlwaysOnTopMenuItem="true" displayRunAtSystemsStartupMenuItem="true" displayShowInTaskbarMenuItem="true" displayAboutMenuItem="true" displayHelpMenuItem="true" displayExitMenuItem="true" />
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

5.1.10 Font Settings

Gets or Sets the fonts propeties to display text instead of icon in the task tray. Using one of the ShowText() overloads to set this text. These are default application wide settings, can be overriable via one of the ShowText() overloads.

Available properties are

  1. FontColor
  2. FontName
  3. FontSize

Listing 5.1.10.1 Set FontSettings programmatically

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
        obj.TrayApplicationBehaviourSettings.ContextMenuSettings.DisplayShowInTaskbarMenuItem = false;
        obj.TrayApplicationBehaviourSettings.FontSettings.FontSize = 9;
    }
}

Listing 5.1.10.2 Set FontSettings via ChoCoreFrx.xml file

Open ChoCoreFrx.xml file, specify the values to each applicable attributes in ‘fontSettings’ element under ‘trayApplicationBehaviourSettings’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="WindowlessTrayApp.exe" eventLogSourceName="WindowlessTrayApp.exe">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="true" activateFirstInstance="false" showEnvironmentSelectionWnd="true" />
    <trayApplicationBehaviourSettings turnOn="false" showInTaskbar="true" hideMainWindowAtStartup="false" tooltipText="" balloonTipText="Hello World!" hideTrayIconWhenMainWindowShown="false" turnOnMode="OnMinimize">
      <trayIcon>C:\Sample.ico</trayIcon>
      <fontSettings fontName="Helvetica" fontSize="8">
        <fontColor />
      </fontSettings>
      <contextMenuSettings displayAlwaysOnTopMenuItem="true" displayRunAtSystemsStartupMenuItem="true" displayShowInTaskbarMenuItem="true" displayAboutMenuItem="true" displayHelpMenuItem="true" displayExitMenuItem="true" />
    </trayApplicationBehaviourSettings>
  </globalApplicationSettings>
</configuration>

6. Advanced Topics

Now that we learned about configuraring tray application via programmatically as well as configuration file. In this section we dive into more advanced approach to customize your tray application programatically, something seldom used.

6.1 AfterNotifyIconConstructed() Method

When implemented in a derived class, executes after the ChoNotifyIcon object constructed by the framework. In this method, you can manipulate most of the ChoNotifyIcon properties based on your neeeds. Please refer ChoNotidyIcon class help for more information. Besides standard properties exposed via this object, it also provides some additional helper methods to use. 

Listing 6.1.1 AfterNotifyIconContructed() sample

[ChoApplicationHost]
public class ChoAppHost : ChoApplicationHost
{
    protected override void ApplyGlobalApplicationSettingsOverrides(ChoGlobalApplicationSettings obj)
    {
        obj.TrayApplicationBehaviourSettings.TurnOn = true;
    }

    public override object MainWindowObject
    {
        get
        {
            return new MainWindow();
        }
    }

    protected override void AfterNotifyIconConstructed(Cinchoo.Core.Windows.Forms.ChoNotifyIcon ni)
    {
        ni.Text = "AfterConstruct";
        ni.ShowText("R");
    }
}

6.2 Running in Console Mode

The applications created using Cinchoo framework can be run as either Console, Windows, Tray or Service applications. Unified interface to switch application from one mode to another. After successful development of tray application, pass /#AM:Console command line argument in order to run your tray application as console mode.

Listing 6.2.1 Run tray application in console mode

>HelloWorldTrayApp /#AM:Console

7. ChoNotifyIcon Class

Specifies a component that creates an icon in the notification area. This class cannot be inherited. Icons in the notification area are shortcuts to processes that are running in the background of a computer, such as a virus protection program or a volume control. These processes do not come with their own user interfaces. The NotifyIcon class provides a way to program in this functionality. The Icon property defines the icon that appears in the notification area. Pop-up menus for an icon are addressed with the ContextMenu property. ChoNotifyIcon provides property notification to all changes.

7.1 Methods

7.1.1 ShowText() Overloads

Showing text instead of icon in the tray.

7.1.2 SetAnimationClip() Overloads

Sets the animation clip that will be displayed in the tray. After setting the clips, you can control the animation by calling StartAnimation and StopAnimation methods.

7.1.3 ShowBalloonTip() Overloads

Displays a balloon tip with the specified title, text, and icon in the taskbar for the specified time period.

7.1.4 StartAnimation() Method

Start showing the animation. This needs to be called after setting the clip using SetAnimationClip() methods.

7.1.5 StopAnimation() Method

Stop animation started with StartAnimation method.

7.2 Properties

7.2.1 BalloonTipText Property

Gets or sets the text to display on the balloon tip associated with the ChoNotifyIcon.

7.2.2 BalloonTipTitle Property

Gets or sets the title of the balloon tip displayed on theChoNotifyIcon.

7.2.3 ContextMenu Property

Gets or sets the shortcut menu associated with the theChoNotifyIcon.

7.2.4 ContextMenu Property

Gets or sets the shortcut menu for the icon.

7.2.5 ContextMenuStrip Property

Gets or sets the shortcut menu associated with the ChoNotifyIcon.

7.2.6 Icon Property

Gets or sets the current icon..

7.2.7 Tag Property

Gets or sets an object that contains data about the ChoNotifyIcon.

7.2.8 Text Property

Gets or sets the ToolTip text displayed when the mouse pointer rests on a  notification area icon.

7.2.9 Visible Property

Gets or sets a value indicating whether the icon is visible in the notification area of the taskbar..

7.3 Events

7.3.1 BalloonTipClicked Event

Occurs when the balloon tip is clicked.

7.3.2 BalloonTipClosed Event

Occurs when the balloon tip is closed by the user.

7.3.3 BalloonTipShown Event

Occurs when the balloon tip is displayed on the screen.

7.3.4 Click Event

Occurs when the user clicks the icon in the notification area.

7.3.5 DoubleClick Event

Occurs when the user double-clicks the icon in the notification area of the taskbar.

7.3.6 MouseClick Event

Occurs when the user clicks a System.Windows.Forms.NotifyIcon with the mouse.

7.3.7 MouseDoubleClick Event

Occurs when the user double-clicks the System.Windows.Forms.NotifyIcon with the mouse.

7.3.8 MouseDown Event

Occurs when the user presses the mouse button while the pointer is over the icon in the notification area of the taskbar.

7.3.9 MouseMove Event

Occurs when the user moves the mouse while the pointer is over the icon in the notification area of the taskbar.

7.3.8 MouseUp Event

Occurs when the user releases the mouse button while the pointer is over the icon in the notification area of the taskbar.

Cinchoo – Simplified Windows Service Development

 Download Sample.zip

Contents

1. Introduction

Cinchoo is the application framework for .NET. One of the main functionalities it provides to the users is application configuration management. Application configuration is the information that application reads and/or writes at run-time from the source.

One another important feature it offers to the developers community is the unified, generic application host to build and run application in different modes. Code once, run the application as either Console, Windows, WPF, Windows Service or Windows Tray application.

In this article, I’m going to illustrate how to use this library to create Windows Service application. It is very simple and easy. Making it as library letting you to concentrate yourself on the core development tasks. Cinchoo provides a clean and easy API to develop and run Windows Service applications. It allows you

  1. Self installable service application
  2. Install and run multi-instances of services
  3. Able to run as Console application for ease of debugging
  4. Pass service arguments via command line
  5. Arguments are saved and used when service is automatically started

2. Requirement

The application host library is written in C# for the .NET 4.0 Framework. It is part of Cinchoo framework, which is a great library with lot of features like Configuration Management, common ApplicationHost, Shell features etc.

3. “Hello World!” Sample

Lets begin by looking into a simple example of a windows service application printing ‘Hello World!’ message into log file.

Download the latest Cinchoo binary here. (Nuget Command: Install-Package Cinchoo)

  • Open VS.NET 2010 or higher
  • Create a sample VS.NET (.NET Framework 4) Console Application project
  • Add reference to Cinchoo.Core.dll
  • Use the Cinchoo.Core namespace
  • Copy and paste the below application host object

Listing 3.1 Defining ApplicationHost object

[ChoApplicationHost]
public class HelloWorldAppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        ChoProfile.WriteLine("Hello world!");
        base.OnStart(args);
    }
}

The code above illustrates about defining ApplicationHost object. First thing define a ApplicationHost (ex. HelloWorldAppHost) class from ChoApplicationHost, it indicates that this object is a ApplicationHost object. And it must be decorated with ChoApplicationHostAttribute to complete the definition. In this example, we override OnStart method with printing “Hello World!” message to log file.

Listing 3.2 Main Method

class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(args);
    }
}

We start by calling ChoApplication.Run() method in the main entry of the application. That all. All the heavy lifting of installing, running the application as service is done by the library under the hood. Now your application is service enabled application. It can also be run as Console Application for easy debugging the service application.

Listed below are the steps to install, uninstall, start and stop the service

Listing 3.3 Install HelloWorld.exe service

>HelloWorld.exe /@I
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] CreateService SUCCESS

[SC] ChangeServiceConfig SUCCESS

Listing 3.4 Start HelloWorld.exe service

>HelloWorld.exe /@S
HelloWorld [Version 1.0.0.0]
Copyright c  2014

Listing 3.5 Stop HelloWorld.exe service

>HelloWorld.exe /@T
HelloWorld [Version 1.0.0.0]
Copyright c  2014

Listing 3.6 Uninstall HelloWorld.exe service

>HelloWorld.exe /@I
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 3.7 HelloWorld.exe with /@? argument

C:\Personal\WindowsService.Test\HelloWorld\bin\Debug>HelloWorld.exe /@?
HelloWorld [Version 1.0.0.0]
Copyright c  2014

HELLOWORLD [/@SN:<string>] [/@SD:<string>] [/@I] [/@U] [/@S] [/@T] [/@P] [/@C] [
/@E:<int>] [/@SP:<string>]

        /@SN    Service Name.
        /@SD    Service Description.
        /@I     Install Service.
        /@U     Uninstall Service.
        /@S     Start Service.
        /@T     Stop Service.
        /@P     Pause Service.
        /@C     Continue Service.
        /@E     Execute Command.
        /@SP    Command Line Parameters.

‘@?’ argument will print out the service level arguments accepted by HelloWorld application.

Listing 3.8 Install HelloWorld.exe service with ‘Test1′ name

>HelloWorld.exe /@I /@SN:Test1
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 3.9 Run HelloWorld.exe as console application

>HelloWorld.exe
HelloWorld [Version 1.0.0.0]
Copyright c  2014

        Hello world!

4. Defining Application Host Object

4.1 ChoApplicationHostAttribute

All application host objects must be decorated by ChoApplicationHostAttribute. An application must have atleast one application host object defined. Cinchoo framework will discover them at the application startup.

4.2 ChoApplicationHost

All application host objects must be derived from ChoApplicationHost class. Override nessasary overrides in them. An application must have one application host object defined either in the entry assembly or referenced assemblies. In this object, you can override number of methods for your needs.

4.2.1 OnStart() Method

When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically) or when the application passed with ‘/@S’ switch or when application starts as console application.

Use OnStart to specify the processing that occurs when the service receives a Start command. OnStart is the method in which you specify the behavior of the service. OnStart can take arguments as a way to pass data.

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application’s executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Process initialization arguments for the service in the OnStart method, not in the Main method. The arguments in the args parameter array can be set manually in the properties window for the service in the Services console or can be passed via command line argument with ‘/@SP’ switch.

4.2.2 OnStop() Method

When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM) or when the application passed with ‘/@T’ switch. Specifies actions to take when a service stops running. When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.

When the SCM receives a Stop command, it uses the value of ChoServiceInstallerSettings.CanStop to verify whether the service accepts Stop commands. If ChoServiceInstallerSettings.CanStop is true, the Stop command is passed to the service, and the OnStop method is called if it is defined. If OnStop is not implemented in the service, the SCM handles the Stop command. If ChoServiceInstallerSettings.CanStop is false, the SCM ignores the Stop command. 

4.2.3 OnContinue() Method

When implemented in a derived class, OnContinue runs when a Continue command is sent to the service by the Service Control Manager (SCM) or when the application passed with ‘/@C’ switch. Specifies actions to take when a service resumes normal functioning after being paused.

Implement OnContinue to mirror your application’s response to OnPause. When you continue the service (either through the Services console or programmatically), the OnContinue processing runs, and the service becomes active again.

OnContinue is expected to be overridden when the ChoServiceInstallerSettings.CanPauseAndContinue property is true. If ChoServiceInstallerSettings.CanPauseAndContinue is false, the SCM will not pass Pause or Continue requests to the service, so the OnPause and OnContinue methods will not be called even if they are implemented. In the SCM, the Pause and Continue controls are disabled when ChoServiceInstallerSettings.CanPauseAndContinue is false.

4.2.4 OnPause() Method

When implemented in a derived class, executes when a Pause command is sent to the service by the Service Control Manager (SCM) or when the application passed with ‘/@P’ switch. Specifies actions to take when a service pauses.

Use OnPause to specify the processing that occurs when the service receives a Pause command. OnPause is expected to be overridden when the ChoServiceInstallerSettings.CanPauseAndContinue property is true. When you continue a paused service (either through the Services console or programmatically via ‘/@P’ switch), the OnContinue processing is run, and the service becomes active again.

Sending a Pause request to the service can conserve system resources because Pause need not release all system resources. For example, if threads have been opened by the process, pausing a service rather than stopping it can allow the threads to remain open, obviating the need to reallocate them when the service continues. If you define Pause to release all system resources, it behaves like a Stop command.

Set ChoServiceInstallerSettings.CanPauseAndContinue to true, and override OnPause and OnContinue to specify the processing that should occur when the SCM passes a Pause or Continue request to your service. OnContinue should be implemented to undo the processing in OnPause.

If ChoServiceInstallerSettings.CanPauseAndContinue is false, the SCM will not pass Pause or Continue requests to the service, so the OnPause and OnContinue methods will not be called even if implemented. In the SCM, the Pause and Continue controls are disabled when ChoServiceInstallerSettings.CanPauseAndContinue is false.

4.2.5 OnPowerEvent() Method

When implemented in a derived class, executes when the computer’s power status has changed. This applies to laptop computers when they go into suspended mode, which is not the same as a system shutdown.

Use OnPowerEvent to specify the processing that occurs when the system event indicated in the System.ServiceProcess.PowerBroadcastStatus enumeration occurs–for example, when the computer is placed in suspended mode or indicates low battery power.

OnPowerEvent is expected to be overridden when the ChoServiceInstallerSettings.CanHandlePowerEvent property is true.

4.2.6 OnShutdown() Method

When implemented in a derived class, executes when the system is shutting down. Specifies what should occur immediately prior to the system shutting down.

Use OnShutdown to specify the processing that occurs when the system shuts down. This event occurs only when the operating system is shut down, not when the computer is turned off. OnShutdown is expected to be overridden when the ChoServiceInstallerSettings.CanShutdown property is true.

4.2.7 OnCustomCommand() Method

When implemented in a derived class, OnCustomCommand executes when the Service Control Manager (SCM) passes a custom command to the service or when the application passed with ‘/@E’ switch . Specifies actions to take when a command with the specified parameter value occurs.

OnCustomCommand lets you specify additional functionality beyond starting, stopping, pausing and continuing services. The SCM does not examine the custom command to verify whether the service supports the command parameter passed in. It passes the custom command directly to the service. If the service does not recognize the command parameter, it does nothing.

Custom commands are raised by an ExecuteCommand statement in a ServiceController component or by passing command through ‘/@E’ command line switch. Use a switch statement or if..then condition to handle the custom commands you define on your service. The only values for a custom command that you can define in your application or use in OnCustomCommand are those between 128 and 255. Integers below 128 correspond to system-reserved values.

If the ChoServiceInstallerSettings.AutoLog property is true, custom commands, like all other commands, write entries to the event log to report whether the method execution succeeded or failed.

4.2.8 OnSessionChange() Method

Executes when a change event is received from a Terminal Server session. You must set the ChoServiceInstallerSettings.CanHandleSessionChangeEvent property to true to enable the execution of this method.

4.2.9 RequestAdditionalTime() Method

Requests additional time for a pending operation. The RequestAdditionalTime method is intended to be called by the overridden OnContinue, OnPause, OnStart, or OnStop methods to request additional time for a pending operation, to prevent the Service Control Manager (SCM) from marking the service as not responding. If the pending operation is not a continue, pause, start, or stop, an InvalidOperationException is thrown.

4.2.10 ApplyGlobalApplicationSettingsOverrides() Method

When implemented in a derived class, ApplyGlobalApplicationSettingsOverrides executes when the framework initializes. In here you can overrides ChoGlobalApplicationSettings members.

4.2.11 ApplyAppFrxSettingsOverrides() Method

When implemented in a derived class, ApplyAppFrxSettingsOverrides executes when the framework initializes. In here you can overrides ChoAppFrxSettings members.

4.2.12 ApplyMetaDataFilePathSettingsOverrides() Method

When implemented in a derived class, ApplyMetaDataFilePathSettingsOverrides executes when the framework initializes. In here you can overrides ChoMetaDataFilePathSettings members.

4.2.13 BeforeInstall() Method

When implemented in a derived class, BeforeInstall() method executes before the service install happens Note that this action is only executed if the service is being installed.

4.2.14 AfterInstall() Method

When implemented in a derived class, AfterInstall() method executes after the service install happens Note that this action is only executed if the service is being installed.

4.2.15 BeforeUninstall() Method

When implemented in a derived class, BeforeUninstall() method executes before the service uninstall happens Note that this action is only executed if the service is being uninstalled.

4.2.16 AfterUninstall() Method

When implemented in a derived class, AfterUninstall() method executes after the service uninstall happens Note that this action is only executed if the service is being uninstalled.

5. Managing Services

Using Cinchoo framework for developing windows service application provides many options via command line arguments to self-install, execute and control the service application.

5.1 Install Service

If you’re developing a Windows Service by using the .NET Framework, you usually install your service applications by using a command-line utility called InstallUtil.exe. You do not need this utility anymore when using Cinchoo framework for your service development. These services are self-installable.

5.1.1 Install Single Instance Service

By default, a service application developed using Cinchoo framework are single instance service application. It means that you can install and run atmost one instance of it at any time. By passing ‘/@I’ command line argument to service executable will install the service with the executable name as service name. For the sample below, the ‘HelloWorld’ service will be installed in your machine.

Listing 5.1.1.1 Install service

>HelloWorld.exe /@I
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] CreateService SUCCESS

[SC] ChangeServiceConfig SUCCESS

5.1.2 Install Multi Instance Service

Sometime you may want to install multiple services with different names. You can do so by turning off ‘SingleInstanceApp’ flag in the ChoGlobalApplicationSettings class. Please visit the below url on how to turn off this option in the application.

Cinchoo – Allow multi-instance application

The below sample shows how to install a service with a ‘TestService’ name by using ‘/@SN’ command line switch.

Listing 5.1.2.1 Install ‘TestService’ service

>HelloWorld.exe /@I /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] CreateService SUCCESS

[SC] ChangeServiceConfig SUCCESS

5.1.2 Uninstall Service

To uninstall a service, you must use ‘/@U’ command line switch. The below samples shows how to uninstall a service

Listing 5.1.2.1 Uninstall service

>HelloWorld.exe /@U
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.2.2 Uninstall ‘TestService’ service

>HelloWorld.exe /@U /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

5.1.3 Start Service

To start a service, you must use ‘/@S’ command line switch. The below samples shows how to start a service

Listing 5.1.3.1 Start service

>HelloWorld.exe /@S
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.3.2 Start ‘TestService’ service

>HelloWorld.exe /@S /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

5.1.3 Stop Service

To stop a service, you must use ‘/@T’ command line switch. SCM uses the value of ChoServiceInstallerSettings.CanStop to verify whether the service accepts Stop commands. If ChoServiceInstallerSettings.CanStop is true, the Stop command is passed to the service, and the OnStop method is called if it is defined. If OnStop is not implemented in the service, the SCM handles the Stop command. If ChoServiceInstallerSettings.CanStop is false, the SCM ignores the Stop command. 

The below samples shows how to stop a service

Listing 5.1.3.1 Stop service

>HelloWorld.exe /@S
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.3.2 Stop ‘TestService’ service

>HelloWorld.exe /@S /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

5.1.4 Continue Service

To continue a service, you must use ‘/@C’ command line switch.

SCM uses the value of ChoServiceInstallerSettings.CanPauseAndContinue to verify whether the service accepts Continue commands. If ChoServiceInstallerSettings.CanPauseAndContinue is true, the Continue command is passed to the service, and the OnContinue method is called if it is defined. If OnContinue is not implemented in the service, the SCM handles the Continue command. If ChoServiceInstallerSettings.CanPauseAndContinue is false, the SCM ignores the Continue command. 

The below samples shows how to continue a service

Listing 5.1.4.1 Continue service

>HelloWorld.exe /@C
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.4.2 Continue ‘TestService’ service

>HelloWorld.exe /@C /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

5.1.5 Pause Service

To pause a service, you must use ‘/@P’ command line switch.

SCM uses the value of ChoServiceInstallerSettings.CanPauseAndContinue to verify whether the service accepts Pause commands. If ChoServiceInstallerSettings.CanPauseAndContinue is true, the Pause command is passed to the service, and the OnPause method is called if it is defined. If OnPause is not implemented in the service, the SCM handles the Pause command. If ChoServiceInstallerSettings.CanPauseAndContinue is false, the SCM ignores the Pause command. 

The below samples shows how to pause a service

Listing 5.1.5.1 Continue service

>HelloWorld.exe /@C
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.5.2 Continue ‘TestService’ service

>HelloWorld.exe /@C /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

5.1.5 Execute Custom Command

To execute a custom command, you must use ‘/@E’ command line switch with command identifier (integer).

The only values for a custom command that you can define in your application or use in OnCustomCommand are those between 128 and 255. Integers below 128 correspond to system-reserved values.

The below samples shows how to pause a service

Listing 5.1.5.1 Execute Custom Command

>HelloWorld.exe /@E:230
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] DeleteService SUCCESS

Listing 5.1.5.2 Execute Custom Command on ‘TestService’ service

>HelloWorld.exe /@E:230 /@SN:TestService
HelloWorld [Version 1.0.0.0]
Copyright c  2014

5.1.6 Service Arguments

Of course every application needs some arguments to run against occasionally to initialize the process. Windows services are indeed no exceptions. There are two different types of arguments you can define for the services

  • Permanent
  • One-Time

The arguments can be passed to the services using /@SP’ command line switch. There arguments are passed to OnStart() method by the infrastructure automatically.

Arguments passed while installing services will be saved permanently in the registry. All the subsequent runs, these parameters are retrived by SCM and passed to service OnStart() automatically.

Listing 5.1.6.1 Permanent Service Arguments

>HelloWorld.exe /@I /@SP:"/name:Tom /msg:Hello"
HelloWorld [Version 1.0.0.0]
Copyright c  2014

[SC] CreateService SUCCESS

[SC] ChangeServiceConfig SUCCESS

Sometime you may want to override the arguments when starting the services. You can do so by passing the arguments in number of ways

  • By passing arguments via command line when starting service
  • The arguments in the args parameter array can be set manually in the properties window for the service in the Services console.

In the sample below, the arguments passed while starting the service will be a one-time basis arguments.

Listing 5.1.5.2 One-Time service arguments

>HelloWorld.exe /@S /@SP:"/name:Tom /msg:Hello"
HelloWorld [Version 1.0.0.0]
Copyright c  2014

6. Application Host Discovery

To successfully deploy your Windows Service application, you must understand how the Cinchoo framework locates and loads the Application Host object that make up your application. By default, Cinchoo framework attempts to locates and loads Application Host object from entry assembly. This default behavior can be overridden by configuration file settings.

Cinchoo framework performs a number of steps when attempting to locate Application Host object.

  1. Examining the App.Cofig/Web.Config file
  2. Locate the ApplicationHost object in Entry assembly
  3. Locate first discovered ApplicationHost object in the referenced assemblies.

6.1 Examine in App.Config/Web.Config file

Cinchoo framework checks the application configuration file for information that overrides the application host object information. The following code provides a example of specifying application host information in the application configuration file

Listing 6.1.1 App.Config file

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="appFrxSettings" type="Cinchoo.Core.ChoAppFrxSettings, Cinchoo.Core" />
  </configSections>
  <appFrxSettings appEnvironment="" appFrxFilePath="" applicationHostType="HelloWorldApp.TestAppHost, HelloWorld" />
</configuration>

6.2 Locate in Entry Assembly

Cinchoo framework checks for the application host object defined in the entry assembly when there is no type specified in the configuration file.

6.3 Locate first discovered ApplicationHost object

Cinchoo framework scans all the referenced assemblies for the application host object defined in them and use the first discovered such object to manage the Windows Service. This step happens when the framework failed to locate the application host object from previous steps.

7. Customization

There are ways to customize your windows service application, like service start mode, service identify, custom install actions, service dependencies etc. The default settings should be good enough for most applications, but they are there for your customizations if you need to.

Customization can be done in couple of ways

  • Programmatically
  • Configuration file

7.1 Configuration File

All the customizable parameters are defined in the ChoServiceInstallerSettings.xml file under Config folder.

Below is the sample contents of the configuration file

Listing 7.1.1 ChoServiceInstallerSettings.xml file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description />
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

7.2 Programmatically

This is one another way to customize your windows service application programmatically.

Here is the sample on how to do

Listing 7.1.1 Override Service Installer Settings

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        //Customize the parameters
    }
}

8. Configuration

Once Cinchoo framework is added to your project for your services development, you can configure the services using framework API or through configuration file. In this section, will talk about most common configuration parameters used by services and how you can manipulate them via API/Configration file.

8.1 Service Configuration

8.1.1 Service Name

Specify the base name of the service, as it is registered in the services control manager. This setting is optional and by default uses entry assembly (executable) name.

It is recommended that service names does not contains spaces or other whitespace characters.

Listing 8.1.1.1 Set ServiceName programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.ServiceName = "TestService";
    }
}

Listing 8.1.1.2 Set ServiceName via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the service name in ‘serviceName’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description />
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

Listing 8.1.1.3 Set ServiceName via command line option

>HelloWorld.exe /@I /@SN:TestService

The order of taking the service names are as follows,

  1. Command line option (/@SN)
  2. Programmatically
  3. ChoServiceInstallerSettings.xml file

Each service on the system must have a unique name. If you need to run multiple instances of the same service, consider using the InstanceName command-line option when installing the service.

8.1.2 Display Name

Specify the display name of the service in the services control manager. This setting is optional and defaults to the service name.

Listing 8.1.2.1 Set DisplayName programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.DisplayName = "TestServiceDisplayName";
    }
}

Listing 8.1.2.2 Set DisplayName via command line option

>HelloWorld.exe /@I /@DN:TestServiceDisplayName

The order of taking the display names are as follows,

  1. Command line option (/@DN)
  2. Programmatically

8.1.3 Instance Name

Specify the instance name of the service. It is combined with the service name and seperated by $. This setting is optional and only added if specified.

Listing 8.1.3.1 Set InstanceName programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.InstanceName = "instance1";
    }
}

Listing 8.1.3.2 Set InstanceName via command line option

>HelloWorld.exe /@I /@IN:instance1

The order of taking the display names are as follows,

  1. Command line option (/@IN)
  2. Programmatically

This option is typically set to run multiple instances of the same service.

8.1.4 Service Description

Specify the description of the service in the services control manager. This is optional and defaults to the service name.

Listing 8.1.4.1 Set ServiceDescription programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.ServiceDescription = "TestService Description";
    }
}

Listing 8.1.4.2 Set ServiceDescription via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the service description in ‘description’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

Listing 8.1.4.3 Set ServiceDescription via command line option

>HelloWorld.exe /@I /@SD:"TestService Description"

The order of taking the service description are as follows,

  1. Command line option (/@SD)
  2. Programmatically
  3. ChoServiceInstallerSettings.xml file

8.2 Service Start Modes

There are multiple service start modes, each of which can be specified by the configuration. This option is only used if the service is being installed.

  1. DelayedAutomatic
  2. Automatic
  3. Manual
  4. Disabled

Listing 8.2.1 Set ServiceStartMode via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the mode in ‘serviceStartMode’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.3 Service Identity

Services can be configured to run as a number of different identities, using the configuration option that is most appropriate.

Possible identies are

  1. Network Service
  2. Local System (Default)
  3. Local Service
  4. User

8.3.1 Network Service Account

Runs the service using the NETWORK_SERVICE built-in account. The network service account is a predefined local account used by the SCM. A service that runs in the context of the NetworkService account presents the computer’s credentials to remote servers. You can set the service to run on this account as below

Listing 8.3.1.1 Set Identity as Network Service account programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RunAsNetworkService();
    }
}

Listing 8.3.1.2 Set Identity as Network Service account via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the account as ‘NetworkService’ in ‘account’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="NetworkService" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.3.2 Local System Account

Runs the service using the local system account. The LocalSystem account is a predefined local account used by the service control manager.  It has extensive privileges on the local computer, and acts as the computer on the network. A service that runs in the context of the LocalSystem account inherits the security context of the SCM. The account is not associated with any logged-on user account. It is the default account set to when you install a service. You can set the service to run on this account explicitly as below

Listing 8.3.2.1 Set Identity as Local System account programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RunAsLocalSystem();
    }
}

Listing 8.3.2.2 Set Identity as Local System via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the account as ‘LocalSystem’ in ‘account’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.3.3 Local Service Account

Runs the service using the local service account. The LocalService account is a predefined local account used by the service control manager.  It has minimum privileges on the local computer and presents anonymous credentials on the network.

Listing 8.3.3.1 Set Identity as Local System account programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RunAsLocalSystem();
    }
}

Listing 8.3.3.2 Set Identity as Local System via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the account as ‘LocalService’ in ‘account’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="LocalSystem" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.3.4 User Account

Runs the service using the specified username and password. User name may be specified either as “<domain>\<username>” or  “<username>”. It can be configured as follows

Listing 8.3.4.1 Set Identity as User account programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RunAsUser("DOMAIN\XBBA123", "passwd");
    }
}

Listing 8.3.4.2 Set Identity as User Account via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the account as ‘User’ in ‘account’ attribute. Then specify the username and password in the corresponding ‘userName’ and ‘password’ attributes. Keeping password as plain text in the configuration file is not a safe.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="User" userName="DOMAIN\XBBA123" password="passwd" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.3.5 Prompt User Account

When the service is installed, the installer will prompt for the username/password combination used to launch the service. User name may be specified either as “<domain>\<username>” or  “<username>”. It can be configured as follows

Listing 8.3.5.1 Set Identity as User account to be prompted programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RunAsPrompt();
    }
}

Listing 8.3.5.2 Set Identity as User account to be prompted via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the account as ‘User’ in ‘account’ attribute. Then empty the username and password in the corresponding ‘userName’ and ‘password’ attributes.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.4 Service Dependencies

Specifies the names of services that must start before this service starts. The names are separated by forward slashes (/).  This is managed by the windows services control manager.

Listing 8.4.1 Set Service Depend programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.Depend("MSSQL", "IIS");
    }
}

Listing 8.4.2 Set Service Depend via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the dependent service names in ‘depends’ attribute. The names must be seperated by slashes(/).

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5 Advanced Settings

8.5.1 CanPauseAndContinue

Specifies that the service supports pause and continue, allowing the services control manager to pass pause and continue commands to the service.

When a service is paused, it halts what it is doing. When you continue the service (either through the Service Control Manager or programmatically), OnContinue runs. Sending a Pause request to the service can conserve system resources. Pause may not release all system resources, but Stop does. OnPause and OnContinue are often implemented to perform less processing than OnStop and OnStart.

When CanPauseAndContinue is true, override OnPause and OnContinue to specify the processing that should occur when the Service Control Manager (SCM) passes a Pause or Continue request to your service. OnContinue should be implemented to undo the processing in OnPause.

If CanPauseAndContinue is false, the SCM will not pass Pause or Continue requests to the service, so the OnPause and OnContinue methods will not be called even if they are implemented. In the SCM, the Pause and Continue controls are disabled when CanPauseAndContinue is false.

Listing 8.5.1.1 Set CanPauseAndContinue programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.CanPauseAndContinue = true;
    }

    protected override void OnContinue()
    {
    }

    protected override void OnPause()
    {
    }
}

Listing 8.5.1.2 Set CanPauseAndContinue via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the true/false in ‘canPauseAndContinue’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="true" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.2 CanShutdown

Specifies that the service supports the shutdown service command, allowing the services control manager to quickly shutdown the service. If CanShutdown is true, the service is notified when the system is shutting down. At shutdown, the OnShutdown method is called if it has been implemented in your derived class.

Listing 8.5.2.1 Set CanShutdown programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.CanShutdown = true;
    }

    protected override void OnShutdown()
    {
    }
}

Listing 8.5.2.2 Set CanShutdown via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the true/false in ‘canShutdown’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.3 CanHandlePowerEvent

Specifies that the service can handle notifications of computer power status changes. When the computer power status changes, the Service Control Manager (SCM) verifies whether the service accepts power event commands using the value of CanHandlePowerEvent.

If CanHandlePowerEvent is true, the command is passed to the service and the OnPowerEvent method is called if defined. If OnPowerEvent is not implemented in the derived class, the SCM handles the power event through the empty base class ServiceBase.OnPowerEvent method.

Listing 8.5.3.1 Set CanHandlePowerEvent programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.CanHandlePowerEvent = true;
    }

    protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
    {
    }
}

Listing 8.5.3.2 Set CanHandlePowerEvent via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the true/false in ‘canHandlePowerEvent’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="true" canHandleSessionChangeEvent="false" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.4 CanHandleSessionChangedEvent

Specifies that the service can handle session change events received from a Terminal Server session.

Listing 8.5.4.1 Set CanHandleSessionChangedEvent programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.CanHandleSessionChangedEvent = true;
    }

    protected override void OnSessionChange(SessionChangeDescription changeDescription)
    {
    }
}

Listing 8.5.4.2 Set CanHandleSessionChangedEvent via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the true/false in ‘canHandleSessionChanged’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.5 CanStop

Specifies whether the service can be stopped once it has started. When Stop is called on a service, the Service Control Manager (SCM) verifies whether the service accepts Stop commands using the value of CanStop. For most services, the value of CanStop is true, but some operating system services, for example, do not allow the user to stop them.

If CanStop is true, the Stop command is passed to the service and the OnStop method is called if it is defined. If OnStop is not implemented in the derived class, the SCM handles the Stop command through the empty base class ServiceBase.OnStop method.

Listing 8.5.5.1 Set CanStop programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.CanStop = true;
    }

    protected override void OnStop()
    {
    }
}

Listing 8.5.5.2 Set CanStop via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the true/false in ‘canStop’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="0">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.6 ExitCode

Specifies exit code of the service. Set the ExitCode property to a non-zero value before stopping the service to indicate an error to the Service Control Manager.

Listing 8.5.6.1 Set ExitCode programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.ExitCode = -1;
    }
}

Listing 8.5.6.2 Set ExitCode via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify the integer value in ‘exitCode’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="false" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.7 AutoLog

Specifies the service whether to report Start, Stop, Pause, and Continue commands in the event log. Setting AutoLog to true instructs the service to use the Application event log to report command failures, as well as state change information for Start, Stop, Pause, and Continue events on the service. The name of the service is used as the log’s EventLog.Source.

To report information to a custom event log rather than the Application log, set AutoLog to false and write instructions within the command-handling methods OnContinue, OnPause, or OnStop to post to the appropriate log.

Listing 8.5.7.1 Set AutoLog programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.AutoLog = true;
    }
}

Listing 8.5.7.2 Set AutoLog via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify ‘true/false’ in ‘autoLog’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.5.7 Parameters

Specifies the service command line arguments. The command line arguments set during installation service will be saved permanently in the registry and used automatically everyone the service is started.

The command line arguments passed during start of the service will be used temporary during the running session of the service.

Listing 8.5.7.1 Set Parameters programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.SetServiceArguments(@"/name:Mark /msg:Hello");
    }
}

Listing 8.5.7.2 Set Parameters via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify service arguments’ in ‘parameters’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[/name:Mark /msg:Hello]]></parameters>
    <recoverySettings resetFailedCounterAfter="0">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.6 Service Recovery

Windows Services support the ability to automatically perform some defined action in response to a failure. Cinchoo framework allows you to define actions that can be performed on the 1st failure, 2nd failure, and subsequent failures, and also provides support for resetting the failure counters and how long to wait before taking the action. The allowed actions are

  • Take No Action (default)
  • Restart the Service
  • Run a Program
  • Restart the Computer

Having this type of functionality is really helpful from the perspective of a developer of services. Who wants to re-invent the wheel and have to write recovery code in the service if you can get it for free. Plus it allows the recovery to be reconfigured as an IT task as opposed to rebuilding the software.

8.6.1 ResetFailedCounterAfter

Specifies the length of the period (in seconds) with no failures after which the failure count should be reset to 0 (zero). If you want to reset the counters you can set to zero which will cause the counters to reset after each failure.

Listing 8.6.1.1 Set ResetFailedCounterAfter programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RecoverySettings.ResetFailCountAfter(100);
    }
}

Listing 8.6.1.2 Set ResetFailedCounterAfter via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify value in seconds in ‘resetFailedCounterAfter’ attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[/name:Mark /msg:Hello]]></parameters>
    <recoverySettings resetFailedCounterAfter="1000">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.6.2 RestartService

Specifies the failure action to the service as to restart. The service will restart automatically after the specified period (in min) of time lapsed.

Listing 8.6.2.1 Set RestartService programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RecoverySettings.RestartService(10);
    }
}

Listing 8.6.2.2 Set RestartService via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify ‘restart/600000′ in ‘actions’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[/name:Mark /msg:Hello]]></parameters>
    <recoverySettings resetFailedCounterAfter="1000">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[restart/600000]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.6.4 RebootSystem

Specifies the failure action to the service as to reboot the system. SCM will reboot the system automatically after the specified period (in min) of time lapsed.

Listing 8.6.4.1 Set RunProgram programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RecoverySettings.RebootSystem(10, "Service down.");
    }
}

Listing 8.6.4.2 Set RunProgram via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify ‘reboot/600000′ in ‘actions’ element and specify ‘Service down.’ to ‘rebootMessage’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[/name:Mark /msg:Hello]]></parameters>
    <recoverySettings resetFailedCounterAfter="1000">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[]]></command>
      <actions><![CDATA[run/600000]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

8.6.3 RunProgram

Specifies the failure action to the service as to run a specified program. SCM will start the specified program automatically after the specified period (in min) of time lapsed.

Listing 8.6.3.1 Set RunProgram programmatically

[ChoApplicationHost]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine("OnStart");
        base.OnStart(args);
    }

    protected override void ApplyServiceParametersOverrides(ChoServiceInstallerSettings obj)
    {
        obj.RecoverySettings.RunProgram(10, "Notepad.exe", @"C:\sample.txt");
    }
}

Listing 8.6.3.2 Set RunProgram via ChoServiceInstallerSettings.xml file

Open ChoServiceInstallerSettings.xml file, specify ‘run/600000′ in ‘actions’ element and specify ‘Notepad.exe C:\sample.txt’ to ‘command’ element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings serviceName="TestService" serviceStartMode="Automatic" depends="MSSQL/IIS" account="User" userName="" password="" timeoutInTicks="-1" canHandlePowerEvent="false" canHandleSessionChangeEvent="true" canPauseAndContinue="false" canShutdown="true" canStop="true" autoLog="true" exitCode="-1">
    <description>TestService Description</description>
    <parameters><![CDATA[/name:Mark /msg:Hello]]></parameters>
    <recoverySettings resetFailedCounterAfter="1000">
      <rebootMessage><![CDATA[]]></rebootMessage>
      <command><![CDATA[Notepad.exe C:\sample.txt]]></command>
      <actions><![CDATA[run/600000]]></actions>
    </recoverySettings>
  </serviceInstallerSettings>
</configuration>

Please bookmark this article as more updates will come shortly.

Cinchoo – Turn your app to Windows Tray app

In this article, I’ll show you how to turn your console / winform application to Windows System Tray application. Cinchoo framework provides a single hosting infrastructure to turn your application either Windows Service or Windows Tray application through configuration.

Console Application

Here is how you can do it for console application

1. Create a new ‘Console Application‘ from VS.NET

2. Add reference to Cinchoo.Core.dll

3. Add namespace Cinchoo.Core

4. Create a class derived from ChoApplicationHost as below

[RunInstaller(true)]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        //TODO: Application Startup code goes here
        base.OnStart(args);
    }
}

Decorating the above class with RunInstallerAttribute will make the application to be run as Windows Service. And override OnStart method, where application start up code placed there.

5. In the main entry, do as below.

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(new AppHost(), args);
    }
}

That’s all, you application is now ready to run as self installable windows service application or Windows Tray application.

Here is how to turn your application to Windows Tray application. In ChoCoreFrx.xml file, set ‘turnOn’ flag to ‘true’ in trayApplicationBehaviourSettings element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="TestApplication.exe" eventLogSourceName="TestApplication.exe" turnOnConsoleOutput="false">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="false" activateFirstInstance="false" />
    <trayApplicationBehaviourSettings turnOn="true" showInTaskbar="true" hideMainWindowAtStartup="true" hideTrayIconWhenMainWindowShown="false" trayAppTurnOnMode="OnMinimize" />
    <appConfigPath />
  </globalApplicationSettings>
</configuration>

Other parameters

  • showInTaskbar – true, will show the application in Taskbar. false, otherwise.
  • hideMainWindowAtStartup – true, will hide the window at the application startup. Otherwise false.
  • hideTrayIconWhenMainWindowShown – true, tray application icon will hidden when the main windows shown. Otherwise false.
  • trayAppTurnOnMode – This option is applicable to WinForm application only. Possible options are OnMinimize, OnClose, OnMinimizeOrClose.

WinForm Application

Below are the steps to turn your winform application into Windows Tray application

1. Create a new ‘WinForm Application‘ from VS.NET

2. Add reference to Cinchoo.Core.dll

3. Add namespace Cinchoo.Core

4. Create a class derived from ChoApplicationHost and IChoWinFormApp as below

[RunInstaller(true)]
public class AppHost : ChoApplicationHost, IChoWinFormApp
{
    MainForm form = new MainForm();
    public AppHost()
    {
    }

    public Form MainFormWindow
    {
        get { return form; }
    }

    public ContextMenu GetContextMenu(ContextMenu contextMenu)
    {
        //Build the context menu items
        return contextMenu;
    }

    public string TooltipText
    {
        get { return null; }
    }

    public System.Drawing.Icon TrayIcon
    {
        get { return null; }
    }

    public string BalloonTipText
    {
        get { return null; }
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
    }
}

Decorating the above class with RunInstallerAttribute will make the application to be run as Windows Service. And override OnStart method, where application start up code placed there.

5. In the main entry, do as below.

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(new AppHost(), args);
    }
}

Thats all. Try it.

Cinchoo – Application Host, Part 2

ChoApplicationHost

Using Cinchoo framework, you can set your application to run at windows start-up easily. Here is how you can do it

1. Add reference to Cinchoo.Core.dll

2. Add namespace Cinchoo.Core

[RunInstaller(true)] //Optional attribute, to host your application as Windows Service
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        //TODO: Application Startup code goes here
    }
}

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run<AppHost>(args);
    }
}

Open the Global Application Settings section in ChoCoreFrx.xml file (you can find it in application binary directory), set runAtStartup to true.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <globalApplicationSettings applicationId="TestApplication.exe" eventLogSourceName="TestApplication.exe" turnOnConsoleOutput="false">
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="false" activateFirstInstance="false" />
    <trayApplicationBehaviourSettings turnOn="true" showInTaskbar="true" hideMainWindowAtStartup="true" hideTrayIconWhenMainWindowShown="false" trayAppTurnOnMode="OnMinimize" />
    <logSettings traceLevel="4">
      <logFolder />
      <logFilename>TestApplication.exe</logFilename>
      <logTimeStampFormat>yyyy-MM-dd hh:mm:ss.fffffff</logTimeStampFormat>
    </logSettings>
    <appConfigPath />
  </globalApplicationSettings>
</configuration>

Override programmatically

Some scenarios you may want to control it programmatically. When it arises, you can do so as below

Method 1:

Subscribe to ApplyFrxParamOverrides eventhandler before ChoApplication.Run() as below.

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.ApplyFrxParamsOverrides += new EventHandler<ChoFrxParamsEventArgs>(ChoApplication_ApplyFrxParamsOverrides);
        ChoApplication.Run<AppHost>(args);
    }
    static void ChoApplication_ApplyFrxParamsOverrides(object sender, ChoFrxParamsEventArgs e)
    {
        e.GlobalApplicationSettings.ApplicationBehaviourSettings.RunAtStartup= true;
    }
}

Method 2:

You can override ApplyFrxParamsOverrides method in your AppHost class as below.

[RunInstaller(true)]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
    }

    protected override void ApplyFrxParamsOverrides(ChoGlobalApplicationSettings globalApplicationSettings, ChoMetaDataFilePathSettings metaDataFilePathSettings)
    {
        globalApplicationSettings.ApplicationBehaviourSettings.RunAtStartup = true;
    }
}
public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run<AppHost>(args);
    }
}

Cinchoo – Application Host, Part 1

ChoApplicationHost

Building single instance application is easy with Cinchoo framework. Create your application and run using ChoApplicationHost as below. Turning your application to Single Instance application is easy through configuration. Here is how you  can do it. Cinchoo framework uses Mutex to perform the singleton application check by default. It can be overridden to perform custom check.

1. Add reference to Cinchoo.Core.dll

2. Add namespace Cinchoo.Core

[RunInstaller(true)] //Optional attribute, to host your application as Windows Service
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        //TODO: Application Startup code goes here
    }
}

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(new AppHost(), args);
    }
}

Open the Global Application Settings section in ChoCoreFrx.config file (you can find it in application binary directory), set singleInstanceApp to true.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <globalApplicationSettings applicationId="TestApplication.exe" eventLogSourceName="TestApplication.exe" turnOnConsoleOutput="false" >
    <behaviourSettings hideWindow="false" bringWindowToTop="false" alwaysOnTop="false" runAtStartup="false" runOnceAtStartup="false" singleInstanceApp="false" activateFirstInstance="false" />
    <logSettings traceLevel="4" useApplicationDataFolderAsLogFolder="false">
      <logFolder />
      <logFilename>TestApplication.exe</logFilename>
      <logTimeStampFormat>yyyy-MM-dd hh:mm:ss.fffffff</logTimeStampFormat>
    </logSettings>
    <appConfigPath />
  </globalApplicationSettings>
</configuration>

Override programmatically

Some scenarios you may want to control it programmatically. When it arises, you can do so as below

Method 1:

Subscribe to ApplyFrxParamOverrides eventhandler before ChoApplication.Run() as below.

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.ApplyFrxParamsOverrides += new EventHandler<ChoFrxParamsEventArgs>(ChoApplication_ApplyFrxParamsOverrides);
        ChoApplication.Run(new AppHost(), args);
    }
    static void ChoApplication_ApplyFrxParamsOverrides(object sender, ChoFrxParamsEventArgs e)
    {
        e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = true;
    }
}

Method 2:

You can override ApplyFrxParamsOverrides method in your AppHost class as below.

[RunInstaller(true)]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
    }

    protected override void ApplyFrxParamsOverrides(ChoGlobalApplicationSettings globalApplicationSettings, ChoMetaDataFilePathSettings metaDataFilePathSettings)
    {
        globalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = true;
    }
}
public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(new AppHost(), args);
    }
}

Custom Singleton Instance Check

By default, Cinchoo framework carries out the Singleton instance check using Mutex. In case, if you want to perform your own custom singleton check for your application, it can be done through by hooking your custom routine to ChoApplication type as below

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.VerifyAnotherInstanceRunning = (() =>
            {
                //TODO: Do your custom singleton instance check here

                return true; //true, already another instance running. Otherwise false.
            });

        ChoApplication.Run<AppHost>(args);
    }
}

Cinchoo – Windows Service made easy

Cinchoo framework simplifies the Windows service development. An application developed in this approach is ready to run as Console application as well as self install-able Service application. In this article, I’m going to walk over the steps of creating service development.

1. Create a new ‘Console Application‘ from VS.NET

2. Add reference to Cinchoo.Core.dll

3. Add namespace Cinchoo.Core

4. Create a class derived from ChoApplicationHost as below

[RunInstaller(true)]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        //TODO: Application Startup code goes here
    }
}

Make sure the type is decorated with RunInstallerAttribute. And override OnStart method, where application start up code placed there. Implement any other service related (OnStop, OnShutdown etc) methods by overriding them.

5. In the main entry, do as below.

public class Program
{
    static void Main(string[] args)
    {
        ChoApplication.Run(new AppHost(), args);
    }
}

That’s all, you application is self install able windows service application.

You can run it as console application or install it as Windows service also.

To Install as windows service, pass /@i command line argument

[AppExeName].exe /@i

To uninstall as windows service, pass /@u command line argument

[AppExeName].exe /@u

To start the service, pass /@s command line argument

[AppExeName].exe /@s

To stop the service, pass /@t command line argument

[AppExeName].exe /@t

To pause the service, pass /@p command line argument

[AppExeName].exe /@p

To continue the service, pass /@c command line argument

[AppExeName].exe /@c

To execute a command in the service, pass /@e:{command_id} command line argument

[AppExeName].exe /@e:2

To get the help on Windows service commands, pass /@?

C:\>TestServiceApp.exe /@?
TestServiceApp [Version 1.0.0.0]
Copyright c  2014

TESTSERVICEAPP [/@SN:<string>] [/@SD:<string>] [/@I] [/@U] [/@S] [/@T] [/@P]
[/@C] [/@E:<int>] [/@SP:<string>]

        /@SN    Service Name.
        /@SD    Service Description.
        /@I     Install Service.
        /@U     Uninstall Service.
        /@S     Start Service.
        /@T     Stop Service.
        /@P     Pause Service.
        /@C     Continue Service.
        /@E     Execute Command.
        /@SP    Command Line Parameters.

Controlling Service Installation

There are couple of settings classes which controls the service process behavior during installation. It can configured through configuration file or can be overridden programmatically. They are

  • ChoServiceInstallerSettings – service process parameters used during installation of service.
  • ChoServiceProcessInstallerSettings – service credential parameters used during installation of the service.

First, let take a look at the way configuring them through configuration file.

ChoServiceProcessInstallerSettings

These setting can be maintained in ChoServiceProcessInstallerSettings.xml file. If the file not exists, it will created by Cinchoo framework in application configuration directory. The file look as below

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;serviceProcessInstallerSettings account=&quot;LocalSystem&quot; userName=&quot;&quot; password=&quot;&quot;&gt;
    &lt;helpText /&gt;
  &lt;/serviceProcessInstallerSettings&gt;
&lt;/configuration&gt;

If you want more information about each attribute/element in the above xml section, please visit ServiceProcessInstaller Class in MSDN.

ChoServiceInstallerSettings

These setting can be maintained in ChoServiceInstallerSettings.xml file. If the file not exists, it will created by Cinchoo framework in application configuration directory. The file look as below

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;serviceInstallerSettings delayedAutoStart=&quot;false&quot; displayName=&quot;ChoServiceHost.Test&quot; serviceName=&quot;ChoServiceHost.Test&quot; serviceStartMode=&quot;Automatic&quot; /&gt;
&lt;/configuration&gt;

If you want more information about each attribute/element in the above xml section, please visit ServiceInstaller Class in MSDN.

Next, let take a look at the way of overriding them programmatically.

Override ApplyServiceInstallParamsOverrides method in your ApplicationHost class, where you can changes service installation parameters.

[RunInstaller(true)]
public class AppHost : ChoApplicationHost
{
    protected override void OnStart(string[] args)
    {
        Console.WriteLine(&quot;Application started...&quot;);
    }

    protected override void ApplyServiceInstallParamsOverrides(ChoServiceProcessInstallerSettings serviceProcessInstallerSettings, ChoServiceInstallerSettings serviceInstallerSettings)
    {
        serviceInstallerSettings.DisplayName = &quot;Test&quot;;
        serviceInstallerSettings.ServiceName = &quot;Test&quot;;
    }
}

In the above sample code, we are trying to override the ServiceName and DisplayName as ‘Test’. When you install the service, it will be created as ‘Test’ service.