Showing posts with label windows service. Show all posts
Showing posts with label windows service. Show all posts

Tuesday, November 12, 2013

Windows Service & App.Config changes

You may also like to see:
Create Windows Service Step-by-Step Guide

Recently I was working on windows-service, which contains scheduling functionality reports sends to the subscriber.

For step-by-step guide to create new windows service read this post.

Windows-service contains the config settings for time interval to send the reports. I changed WindowsService.exe.config after installation but I noticed it was not getting updated. So I searched and found some interesting facts, which I want to share with you.

If you have one of following question in your mind:

  1. I changed app.config while the application is running. But the application does not read the change, unless I restart the application. What should I do?
  2. Do you have to restart a windows service if you change the app.config?
Then YES!!!, config changes not get implemented until you restart the windows service because DotNet framework will read the app.config once, at the start of application. That is why you have to restart the application to update the settings.

Now you must be thinking why it is not getting auto-refresh?

let see the reasons step by step:

what exactly will it need to do if it has to update the settings?

First, it will have to know that the app.config file has changed. This can be done by registering file change notification. so any change in file notify the application.

Once it get notified that app.config has changed then it has to notify all the components or modules using these settings, but issue is how come service know which module is currently using these settings.

Now if we say we register all components using these settings and notify these application. What these application needs to do?


To take effect of updated changes i.e, new value for a key, the component will have to “restart” itself. This means, the component needs to be able to flush the old config data, stop current execution as it was using old value and restart it with refresh values.

This is not always possible. Take binding policy as an example. If the old binding policy says I want version 1.0.0 for assembly A, the new policy says I want version 2.0.0 for assembly A. There is no way for .Net framework to recover with the new binding policy, if assembly A version 1 is already loaded.

Only those part of application can be refreshed which have state-less effects or their effect can easily be removed. like Cache size on change of cache size, you can re-size the cache (and still keep the data), or simply remove the old cache and start a new cache fresh.

In general when the app.config changes, the only safe way to make sure all components are consistent is to restart the application.

Asp.Net has the web.config change detection built in. It watches changes on web.config. Once it detects a change, it will shutdown the old application, and starts a new application which causes data loss for currently logged-in users.

Since .Net framework won’t provide the config data refresh feature, if this is important to you, you have to roll your own implementation.

Fortunately the Enterprise Library folks understand there is a need for this. They developed “Configuration Application Block” in the latest Enterprise Library release.

You may also like to see:
Create Windows Service Step-by-Step Guide

Wednesday, November 6, 2013

Create Windows Service Step-By-Step

Introduction

This step by step guide will help you to create simple Windows Service in Visual Studio.

Note: to enlarge image click on it.
Step 1:

Start Visual Studio and add new project Windows Service:


Your Solution Explorer should now look like this:


Step 2:

Set project properties as follow:





Step 3:

Add new component file and name it ‘XXXXInstaller.cs’ [XXXX= Windows Service name]


Step 4:

Open your WindowsService.cs ie DistributionService file and add:

using System;
using System.ServiceProcess;
using System.Timers;

namespace DistributionWindowsService
{
    partial class DistributionService : ServiceBase
    {
        private Timer _timer = null;
        public DistributionService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                EventLog.WriteEntry("Email service started : " + DateTime.Now);
                _timer = new Timer();
                _timer.Interval = 10000; //in milliseconds

                 EventLog.WriteEntry("Timer Interval is : " + _timer.Interval);

                // attach a function to elapsed event whenever time interval occur it will call this function
                _timer.Elapsed += timer_Elapsed;

                _timer.Start(); 
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Email service error : " + ex);
            }
            
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry("Email service Stopped : "+DateTime.Now);
        }

        protected void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                _timer.Stop();
                //perform your action here 
                // It will be occur on each time elapsed
            }
            catch (Exception ex)
            {

            }
            finally
            {
                //restart the timer
                _timer.Start();
            }
        }
     
    }
}


Step 5:

Open your WindowsServiceInstaller.cs ie DistributionServiceInstaller.cs file and add:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace DistributionWindowsService
{
    [RunInstaller(true)]
    public partial class DistributionServiceInstaller : Installer
    {     

        public DistributionServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

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

            //# Service Information
            serviceInstaller.DisplayName = "MyPerformance Distribution Service";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.Description = "Distribution of scheduled Emails.";

            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "DistributionWindowsService";
            serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;   
            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);

        }
        private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            ServiceController sc = new ServiceController("DistributionWindowsService");
            sc.Start();
        }
    }
}


Step 6:

Build your solution

Step 7:

Open visual studio command prompt(if not works try run as administrator):


Step 8:

Open the physical folder and copy the path of WindowsService.exe file from

WindowsService>>Bin>>Debug>> WindowsService.exe

Step 9:

Write command in command prompt:

Installutil –i “complete path of file”

Step 10:

Check Service in “control panel>>Administrative services>>Service” and start the service if it is stop.


Step 11:

To uninstall windows service goto command prompt and write:

Installutil –u “complete path of file”


Step 12:

It is an optional step, if you don't want to run the application from command line then you can create a batch file Installer and Uninstaller for windows service. Add a file installer.bat open it with notepad or any editor:

@ECHO OFF
 
echo Installing WindowsService...
echo ---------------------------------------------------
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "complete path of exe"
echo ---------------------------------------------------
echo Done.
pause

And for uninstaller add uninstaller.bat file and add:


@ECHO OFF
 
echo Un-Installing WindowsService...
echo ---------------------------------------------------
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u "complete file path of exe"
echo ---------------------------------------------------
echo Done.
pause 

Double click installer and uninstaller for particular actions(if not works try run as administrator).

You may also like to see:
For changing app.config you would need to restart windows service, for details and reasons please visit this page.
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,