Tag Archives: Typed

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 – 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 ready 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

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

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceProcessInstallerSettings account="LocalSystem" userName="" password="">
    <helpText />
  </serviceProcessInstallerSettings>
</configuration>

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

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <serviceInstallerSettings delayedAutoStart="false" displayName="ChoServiceHost.Test" serviceName="ChoServiceHost.Test" serviceStartMode="Automatic" />
</configuration>

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("Application started...");
    }

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

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.


Cinchoo – Framework Tips

Here I’m going to talk about couple of tips on using Cinchoo framework in your project.

At the start of the application, you must call ChoFramework.Initialize() to initialize the framework and start necessary services. Usually you must place this statement in application Main entry point as below.

Calling ChoFramework.Shutdown() method is not mandatory to call. But it is safe to make this call for graceful shutdown of all the background services.

static void Main(string[] args)
{
    ChoFramework.Initialize();
    try
    {
        ChoApplication.ApplyFrxParamsOverrides += new EventHandler<ChoFrxParamsEventArgs>(ChoApplication_ApplyFrxParamsOverrides);

        SampleConfigSection ApplicationSettings = new SampleConfigSection();
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR: " + ex.Message);
    }
    finally
    {
        ChoFramework.Shutdown();
    }
}

ChoAppDomain.


Cinchoo – Overriding Framework Configuration Parameters

In this section, I’ll go over the list of Cinchoo framework configuration parameters can be overridden to control the run-time environment of the framework either through configuration or programmatically.

Framework will run fine without overriding these parameters. Only when you need, you can override them. In those situation, it can be done through configuration or programmatically.

First, we will see how to override them through configuration. All the framework parameters must be stored in ChoCoreFrx.config file under application executable folder. This is the default behavior of discovering this file by the framework. But this can be overridden by specifying the path to this file through appFrxSettings custom configuration section in App.config file as below

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="appFrxSettings" type="Cinchoo.Core.ChoAppFrxSettings, Cinchoo.Core" />
    </configSections>
    <appFrxSettings appFrxFilePath="C:\ConfigFolder" />
</configuration>

GlobalApplicationSettings

There are the application level settings used by framework. Below are the attributes and their usages.

  • globalApplicationSettings – Global application parameters used by framework. All the variables are optional.
    • singleInstanceApp [bool] – true, to ensure there is only one instance of the application running at any point in time. false, lets you to run multiple instances of the application. Default is false.
    • applicationId [string] – the custom application name. Default value is the executable name.
    • eventLogSourceName [string] – Event log source name where all the errors are posted on this name, default value is applicationId.
    • useApplicationDataFolderAsLogFolder [bool] – true, it uses the current roaming user directory. Default is false.
    • logFolder [string] – A log directory, where all the log files are created by framework. Default is ‘[appExePath]\Logs’.
    • appConfigPath [string] – configuration file path. If not specified, this will be [appExeFolder].[appExeName].xml
    • logTimeStampFormat [string] – A time stamp format used when logging information to log files. Default value is “yyyy-MM-dd hh:mm:ss.fffffff”
    • traceLevel [int] – Specifies what message to output for the Trace/ChoTrace classes. 0-Off, 1-Error, 2-Warning, 3-Info, 4-Verbose.

Here is the sample Global Application Settings section in ChoCoreFrx.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <globalApplicationSettings singleInstanceApp="false" applicationId="TestApplication" eventLogSourceName="TestApplication" useApplicationDataFolderAsLogFolder="false">
    <logFolder>C:\Logs</logFolder>
    <appConfigPath>c:\config\TestApplication.xml</appConfigPath>
    <logTimeStampFormat>yyyy-MM-dd hh:mm:ss.fffffff</logTimeStampFormat>
  </globalApplicationSettings>
</configuration>

MetaDataFilePathSettings

Cinchoo framework creates as well as uses number of Meta-Data files, these file paths can be configured through ChoCoreFrx.config file.

  • configurationMetaDataFilePath – meta data file path used by Configuration manager. By default, it’s value is [appExeName].config.meta
  • pcMetaDataFilePath – meta data file path used by Performance Counter manager. By default, its value is [appExeName].perf.meta

Here is the sample xml section looks like

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <metaDataFilePathSettings>
    <configurationMetaDataFilePath>c:\Config\configurationMetaFile.meta</configurationMetaDataFilePath>
    <pcMetaDataFilePath>c:\Config\PCMetaFile.meta</pcMetaDataFilePath>
  </metaDataFilePathSettings>
</configuration>

Run-Time approach

Lets see how we can override the system parameters at run-time in here. Cinchoo framework exposes ChoApplication.ApplyFrxParamsOverrides event. By subscribing to this event, you have a chance to override the framework parameters at run-time. See below the sample code on how to override some of the system parameters

static void Main(string[] args)
{
    try
    {
        ChoApplication.ApplyFrxParamsOverrides += new EventHandler<ChoFrxParamsEventArgs>(ChoApplication_ApplyFrxParamsOverrides);
        XmlApplicationSettings ApplicationSettings = new XmlApplicationSettings();
    }
    finally
    {
        ChoAppDomain.Exit();
    }
}

static void ChoApplication_ApplyFrxParamsOverrides(object sender, ChoFrxParamsEventArgs e)
{
    e.GlobalApplicationSettings.SingleInstanceApp = true;
    e.MetaDataFilePathSettings.ConfigurationMetaDataFilePath = @"C:\Config\MetaDataFilePath.meta";
}

Cinchoo – Configuration framework, part 15

Available Configuration Section Handlers

Here is the list of available configuration section handlers in Cinchoo framework. This list will keep changing based on the more support to other data sources. Keep looking for new configuration section handlers.

  • ChoNameValueSectionHandler (Default)

Cinchoo – Using Performance Counters, Part 2

This article is the continuation of previous one. So far you learned how to create and use performance counters in your application. In this section, I’ll show you how to control them through configuration.

Cinchoo framework generates meta data configuration file for all the performance counters you created in your application. This file will be created automatically in the application configuration folder. The file name will be [appExeName].perf.meta.

If you application executable name is HelloWorld.exe, this meta data file will be created in the name of HelloWorld.perf.meta. This is the default behavior.

This file name can be overridden. Please visit Framework Configuration Parameters section on how to achieve it.

For the samples from the previous sections, the meta data file will be created as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <PerformanceCounterCategory name="Random Single Instance Test">
    <PerformanceCounter name="Random Rate" turnOn="true" />
    <PerformanceCounter name="Random Average" turnOn="true" />
  </PerformanceCounterCategory>
  <PerformanceCounterCategory name="Random Multiple Instance Test">
    <PerformanceCounter name="Random Value" instanceName="Standard" turnOn="true" />
    <PerformanceCounter name="Random Value" instanceName="Inverted" turnOn="true" />
  </PerformanceCounterCategory>
</configuration>

PerformanceCounterCategory section will be created for corresponding performance counter category. A PerformanceCounter element will be created for each performance counter in the category.

At present, turnOn is the only fact used by the framework to enable or disable the counter. You can touch this attribute any time (run-time as well), application pick up the changes and act accordingly.

If turnOn is true, the performance counter will be enabled. Otherwise it is disabled. This feature helps you to control the performance counter in the production environment as Performance Counters will affect your application performance.


Cinchoo – Using Performance Counters, Part 1

In this section I’ll discusses about how we can use Cinchoo framework’s performance counter helper class to gather data from an application. So we will first understand the fundamentals and then we will see a simple example from which we will collect some performance data.

Before we begin, if you like to know more information about Performance Counter, please visit below links

MSDN Performance Counter Class

An Article on Performance Counter in CodeProject

Cinchoo framework provides nifty performance counter helper classes to makes it easier for developers to develop applications that use Performance Counter to monitor the health of the application.

There are two types of Performance Counter Categories

  • SingleInstance – The performance counter category can have only a single instance.
  • MultipleInstance – The performance counter category can have multiple instances.

Creating and using SingleInstance Performance Counters

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Instrumentation.Performance

[ChoPerformanceCounterCategory("Random Single Instance Test", PerformanceCounterCategoryType.SingleInstance)]
public sealed class SingleInstancePerfCounters : ChoPerformanceCounterCategory
{
    #region Performance Counters

    [ChoPerformanceCounter("Random Rate", "", PerformanceCounterType.RateOfCountsPerSecond32)]
    public readonly ChoPerformanceCounter PCRandomRate = null;

    [ChoPerformanceCounter("Random Average", "", PerformanceCounterType.AverageCount64)]
    public readonly ChoPerformanceCounter PCRandomAverage = null;

    #endregion
}
 Now lets see how to instantiate and use them
[STAThread]
static void Main(string[] args)
{
    SingleInstancePerfCounters perfCounter = new SingleInstancePerfCounters();

    Random rand = new Random(42);
    int randMax = 100;

    while (true)
    {
        int r = rand.Next(randMax);

        if (perfCounter.PCRandomRate != null)
            perfCounter.PCRandomRate.Increment();
        if (perfCounter.PCRandomAverage != null)
            perfCounter.PCRandomAverage.IncrementBy(r);

        Thread.Sleep(1000);
    }
}

Creating and using MultipleInstance Performance Counters

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Instrumentation.Performance

[ChoPerformanceCounterCategory("Random Multiple Instance Test", PerformanceCounterCategoryType.MultiInstance)]
public sealed class MultipleInstancePerfCounters : ChoPerformanceCounterCategory
{
    #region Performance Counters

    [ChoPerformanceCounter("Random Value", "", PerformanceCounterType.NumberOfItems64, "Standard")]
    public readonly ChoPerformanceCounter PCRandomValue;

    [ChoPerformanceCounter("Random Value", "", PerformanceCounterType.NumberOfItems64, "Inverted")]
    public readonly ChoPerformanceCounter PCRandomInvertedValue;

    #endregion
}

Please remember that the above two Performance counter members are given same category name ‘Random Value’ and different instance names. It qualifies them to create multiple instances of performance counters.

Now lets see how to instantiate and use them

[STAThread]
static void Main(string[] args)
{
    MultipleInstancePerfCounters perfCounter = new MultipleInstancePerfCounters();

    Random rand = new Random(42);
    int randMax = 100;

    while (true)
    {
        int r = rand.Next(randMax);

        if (perfCounter.PCRandomValue != null)
            perfCounter.PCRandomValue.RawValue = r;
        if (perfCounter.PCRandomInvertedValue != null)
            perfCounter.PCRandomInvertedValue.RawValue = randMax - r;

        Thread.Sleep(1000);
    }
}

In the next part, will see how to control the Performance Counters through configuration.


Follow

Get every new post delivered to your Inbox.