Tuesday, 27 October 2015

Delete all files & Folders from the given path

private void clearFolder(string FolderName)
    {
        DirectoryInfo dir = new DirectoryInfo(FolderName);

        foreach(FileInfo fi in dir.GetFiles())
        {
            fi.Delete();
        }

        foreach (DirectoryInfo di in dir.GetDirectories())
        {
            clearFolder(di.FullName);
            di.Delete();
        }
    }

If you want delete the current folder with all the files and sub folders in one shot.
Directory.Delete(@"c:\Projects", true);

Monday, 26 October 2015

Create Window service project in C# - Part 3 (Using Timers in a service)

Create Window service project in C# - Part 3 (Using Timers in a service)


So now we know how to create, launch and view event log for a Windows service using C#. If you do not have a clear idea please refer following two posts.

 Now let's create a windows service application which use Timers. Because most of the windows services are running to execute specific task periodically. That's mean execute a code after specific time period without user interaction. 

For that purpose you can use Timer component in C# which enables you to execute a code segment periodically. Let's see how this thing worked...

First you have to create a timer object on your service class. I am not going to further describe these things, because you will be able to understand by looking on following code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace MyWinService
{
    public partial class MyService : ServiceBase
    {
        System.Timers.Timer tmrDelay;
        int count;

        public MyService()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("MyLogSrc"))
            {
                System.Diagnostics.EventLog.CreateEventSource("MyLogSrc", "MyLog");
            }

            //set our event log to system created log
            myEventLog.Source = "MyLogSrc";
            myEventLog.Log = "MyLog";

            tmrDelay = new System.Timers.Timer(5000);
            tmrDelay.Elapsed += new System.Timers.ElapsedEventHandler(tmrDelay_Elapsed);
        }

        void tmrDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string str = "Timer tick " + count;
            myEventLog.WriteEntry(str);
            count++;
        }

        protected override void OnStart(string[] args)
        {
            myEventLog.WriteEntry("MyService started");
            tmrDelay.Enabled = true;
        }

        protected override void OnStop()
        {
            myEventLog.WriteEntry("MyService stoped");
            tmrDelay.Enabled = false;
        }
    }
}

This code was placed on "Service1.cs" file on my project.

Code explained

 System.Timers.Timer tmrDelay;
 int count;
Declare timer variable for timing purpose and count variable for counting purpose.

 tmrDelay = new System.Timers.Timer(5000);
 tmrDelay.Elapsed += new System.Timers.ElapsedEventHandler(tmrDelay_Elapsed);
Create timerDelay object for 5000ms(5 seconds) delay. Then event handler so that timer will execute the code within the "tmrDelay_Elapsed" method in every five seconds. (Do not worry this event handler code line will automatically generate when you type '+=' and press tab)

 void tmrDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
    string str = "Timer tick " + count;
    myEventLog.WriteEntry(str);
    count++;
 }
This is the event handler for timer elapsed event. When timer elapsed a specific 'interval' time it will execute code within this event handler.

Here adds a new entity on event logger as "Timer tick 1" , 2, 3, 4 ....

Other codes are as it is on previous post. Therefore I am not going to explain those here.


Now build and install your solution as describe in Part 1. Then you will see some thing similar to this in "Event Viewer" or "Visual Studio".


As you can see when each time timer elapsed it will add new entity to logger. So now it's your turn place any code in timer elapsed event to execute it periodically.




Create Window service project in C# - Part 2 (View event logs)

Create Window service project in C# - Part 2 (View event logs)

This article series describes about creation of windows service application using C#.net. My previous post describe about the creation and installing of the windows service using C#. This article will introduce you to the way to check logs on windows system.

Can you can remember, we create an event log for our windows service project. But where should I look for these logs to view those. This article will answer for that question.

You can check whether our new windows service is installed or not from Computer management and also you can start you service from here by clicking on "start". As we write on our program there is a action when starting the service to write "MyService started" on event log. (in OnStart method)

You can check these logs using either Visual studio or event viewer on windows.

Visual studio

Just open Server Explorer from visual studio to view all services. If you unable to find the server explorer, you can select it from view menu. (Or press Ctrl+W then L in VS 2010). You will find your event log under Servers --> [Your PC name] --> Event logs. When you expand your event log you will see all the logs which are loged by your service. (nor Refresh the list)



Event Viewer
Just open "Event viewer" from start menu and you will find your event log and its details. Also you can clear your logs from here.

Create Window service project in C# - Part 1 (Create and launch)

Create Window service project in C# - Part 1 (Create and launch)


Windows service is a running executable on windows which perform a specific functions without user interaction. So you can even create a windows service to do a specific function without your interaction. There is an easy way to create a windows service application in C#. This article describe step by step of creating windows service application in C#.net. and my next parts will describe further more about...

Step 1
Open visual studio and File--> New --> Project. then select "Windows service" and type name and location of your project.


Step 2
Then go to "Service1.cs" file's design view. Then Properties of Service1 and change the 'Name' and 'Service name' as you wish. I changed those as "MyService" as you can see on following screenshot. Then click "Add Installer" to add an installer for this service.


Step 3
Then click on 'serviceInstaller1' component on 'ProjectInstaller.cs' file's design view then get its properties. Now you can change the properties of serviceInstaller1 as shown in following figure.


Make sure the Service name is equal to the service name that you enter for Service1.cs's properties and select StartType as Automatic. Then let's see properties for serviceProcessInstaller1 on ProjectInstaller.cs. You should change the Account as LocalSystem. It will prevent asking username and passward from the user when install this windows service.


Step 4
Now let's see how to get notified whether our service is running or not. For that you can use EventLog component as describe as followings. First go to Service1's design view and the add a eventlog component from tool box.



I changed added event log's name as 'myEventLog'. So then move to the coding... (switch to the code view of Service1.cs file)
Add following code segment to immediately following to the initialize component method calling on the constructor of the MyService class.

 if (!System.Diagnostics.EventLog.SourceExists("MyLogSrc"))
 {
    System.Diagnostics.EventLog.CreateEventSource("MyLogSrc", "MyLog");
 }

 //set our event log to system created log
 myEventLog.Source = "MyLogSrc";
 myEventLog.Log = "MyLog";


This will create a system event log and bind our event log to created log.
Then add following code segment to the override method of OnStart. There are more override methods which are on ServiceBase class as our class extends the ServiceBase class. You can try those methods also for further more actions.

 myEventLog.WriteEntry("MyService started");


OnStart override method can be use to execute actions when our service starts. Because OnStart method 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).

Let's try OnStop method also. So enter following code segment in OnStop method.

 myEventLog.WriteEntry("MyService stoped");


Now your code should like this,


Now our event logger part finished. You can build this project by pressing F6. (If you try to run this project you will receive an error message which notify you "cannot run or debug... first install this service.." like that) So let's move to install our service on windows.

Step 4
To install the service first create an installation project for our project. Let's create it...
Right click on your solution (not project) from solution explorer window and point to the Add then click on New Project...


Then select Setup Project from the list which can be found under Setup and Deployment category. Then type name for your project then Ok.


Now you can see the new project on solution explorer, right click on it and point to Add then click on Project Output... . Then select your project name and select Primary Output.


Then again right click on setup project and point to View then click on Custom Actions. You will see the custom action window. Then right click on Custom Actions then Add Custom Action . You will see the Select Items from Project window. Select Application folder from the Lock in combo box and select Primary output from (active) then Ok.


No you can see, it will add Primary output for all four actions (Install, Commit, Rollback, and Uninstall).


Now we are ready to install our new windows service on windows. Just right click on setup project and select Install from the drop down menu. Now you will see the installation wizard just like normal installation.

That's all for creating basic Windows and installing windows application in C#.net. You can see your service on windows service list. Just go to Computer management by selecting it from start menu. And navigate to Services which can be find under  Services and application category.


If useful to you comment on this.


Tuesday, 20 October 2015

Tutorial to create a simple Windows Service with sample example in C#

This article I will explain a tutorial to create a simple Windows Service with sample example in C#.


The Windows service will support two modes
1. Interval mode: where Windows Service execute a task at regular intervals after some delay.
2. Daily mode: where the Windows Service will execute a task at specific (certain) time of day only.
Creating a Windows Service Project
The very first step is to add a new project of type Windows Service as shown below.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net

Adding App.Config File
Next you need to add an Application Configuration File (App.Config file). This file will be used to control the Windows Service and make it work in different modes.

After adding the file, you will need to copy the following AppSettings to the App.Config file.

<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key ="Mode" value ="Daily"/>
        <!-- <add key ="Mode" value ="Interval"/>-->
        <add key ="IntervalMinutes" value ="1"/>
        <add key ="ScheduledTime" value ="18:41"/>
    </appSettings>
</configuration>

Below is the description of each AppSetting.
Mode: It is used to set the Mode. There are two types of modes namely Daily and Interval.
IntervalMinutes: It is used when Mode is set to Interval. It consist of the Interval value in Minutes after which the Windows Service will perform a task. In other words it is the delay value.
ScheduledTime: This setting is used when the Mode is set to Daily. It is used to notify the Windows Service the time it should perform a task. The value specified is in 24 hour time format.
Timer Configuration
The following code has to be placed in the Service.cs Class. I am making use of a Timer class belonging to the System.Threading namespace in order to execute the Windows Service periodically at regular intervals and as well as once a day at specific (certain) time of day.
The Timer has a Callback method which gets triggered automatically when the due time is elapsed.
We will start with importing the following namespaces.
C#
using System.IO;
using System.Threading;
using System.Configuration;

Below is the Windows Service class with the OnStart and OnStop event handlers.
When the Windows Service starts it calls the ScheduleService method which first reads the Mode AppSetting.. There’s a ScheduledTime variable which is set in both modes.
When the Mode is set to Daily then the ScheduledTime is read from the AppSettings. In the case when the scheduled time is passed, it is updated to same time on the next day.
When the Mode is set to Interval then the IntervalMinutes is read from the AppSettings and the schedule time is calculated by adding the IntervalMinutes to the Current Time.
Finally the Timer is set to run the scheduled time. When the scheduled time is elapsed, the Timer’s Callback method is triggered which logs the current date and time to a Text file.

Note: While using the above code, you could encounter the following error: The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration' (are you missing an assembly reference?).The solution is provided in my article The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration’.

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }
 
    protected override void OnStart(string[] args)
    {
        this.WriteToFile("Simple Service started {0}");
        this.ScheduleService();
    }
 
    protected override void OnStop()
    {
        this.WriteToFile("Simple Service stopped {0}");
        this.Schedular.Dispose();
    }
 
    private Timer Schedular;
 
    public void ScheduleService()
    {
        try
        {
            Schedular = new Timer(new TimerCallback(SchedularCallback));
            string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
            this.WriteToFile("Simple Service Mode: " + mode + " {0}");
 
            //Set the Default Time.
            DateTime scheduledTime = DateTime.MinValue;
 
            if (mode == "DAILY")
            {
                //Get the Scheduled Time from AppSettings.
                scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
                if (DateTime.Now > scheduledTime)
                {
                    //If Scheduled Time is passed set Schedule for the next day.
                    scheduledTime = scheduledTime.AddDays(1);
                }
            }
 
            if (mode.ToUpper() == "INTERVAL")
            {
                //Get the Interval in Minutes from AppSettings.
                int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
 
                //Set the Scheduled Time by adding the Interval to Current Time.
                scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
                if (DateTime.Now > scheduledTime)
                {
                    //If Scheduled Time is passed set Schedule for the next Interval.
                    scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
                }
            }
 
            TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
            string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
 
            this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
 
            //Get the difference in Minutes between the Scheduled and Current Time.
            int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
 
            //Change the Timer's Due Time.
            Schedular.Change(dueTime, Timeout.Infinite);
        }
        catch(Exception ex)
        {
            WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
 
            //Stop the Windows Service.
            using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
            {
                serviceController.Stop();
            }
        }
    }
 
    private void SchedularCallback(object e)
    {
        this.WriteToFile("Simple Service Log: {0}");
        this.ScheduleService();
    }
 
    private void WriteToFile(string text)
    {
        string path = "C:\\ServiceLog.txt";
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
            writer.Close();
        }
    }
}

Adding an Installer to the Windows Service
Once the Windows Service is ready to go we need to add the Installer class to our Windows Service as without it, the Windows Service will not install.
Following are the steps to add Installer class.
1. Right Click the Service1.cs class and click View Designer in the context menu.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net

2. Once the Design View is show, you need to right click and then select Add Installer in the context menu.

Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net


Setting the Windows Service Name and StartType
The above action will add an Installer class named ProjectInstaller. Now you need to open the ProjectInstaller.Designer class and look for InitializeComponent Method.
In this method we will modify the ServiceName of the Windows Service and also set its StartType to Automatic, so that along with the computer the Windows Service will start automatically.

Note: If you don’t set the StartType to Automatic, the default value is Manual and hence the Windows Service will not start automatically when the machine is started.

private void InitializeComponent()
{
    this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    //
    // serviceProcessInstaller1
    //
    this.serviceProcessInstaller1.Password = null;
    this.serviceProcessInstaller1.Username = null;
    //
    // serviceInstaller1
    //
 
    //Set the ServiceName of the Windows Service.
    this.serviceInstaller1.ServiceName = "SimpleService";
 
    //Set its StartType to Automatic.
    this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
 
    //
    // ProjectInstaller
    //
    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
    this.serviceProcessInstaller1,
    this.serviceInstaller1});
}

Making the Windows Service Automatically start after Installation
After the installation one has to start the Windows Service manually through the Services section of My Computer Management.
We can start the Windows Service automatically after installation by making use of the AfterInstall event handler which triggers immediately after Windows Service is installed.
You will need to open the ProjectInstaller class and override the AfterInstall event handler and add the code to start the Windows Service.

[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }
 
    protected override void OnAfterInstall(IDictionary savedState)
    {
        base.OnAfterInstall(savedState);
 
        //The following code starts the services after it is installed.
        using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            serviceController.Start();
        }
    }
}


Installing the Windows Service using InstallUtil.exe
Once all the processes are complete, we can now build the Windows Service. Once the Windows Service is build you need to find the EXE file in the Debug folder of the Project.
Note: Once the Windows Service is ready for deployment, it is recommended to make use of the Release version of the EXE file instead of the Debug version.
To find the EXE, simply right click Project and select Open Folder in Windows Explorer. Now navigate to Bin => Debug folder and look for the EXE file with name same as that of the project.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net

Now copy and build the path in a Notepad (Text) file.
Note: I would recommend to build the command in a Notepad and save it somewhere so that you can use it multiple times.
InstallUtil Syntax
InstallUtil /i <Path of Windows Service EXE file>
Example:
InstallUtil /i C:\Users\Mudassar\Projects\WindowsService\bin\Debug\WindowsService.exe
Now you need to open Programs => Microsoft Visual Studio 2010 => Visual Studio Tools => Visual Studio Command Prompt (2010).
Note: I am making use of Visual Studio 2010, and hence you need to use the appropriate version installed on your computer. And make sure you are logged in as Administrator. Without Administrator rights it would not allow you to install the Windows Service.
In the command prompt window, copy the InstallUtil command from Notepad and right click in the Command Prompt and click Paste and then press Enter key.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net
Now the Installer will ask for Logon permissions to run the Windows Service and hence you will need to add Windows Username and Password of user who has appropriate permission.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net
Note: Username must include Domain Name or the Computer name
After successful installation you will see the following message.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net

You can find the Windows Service in the Services window. In order to open Services window in the Run Command type, services.msc and hit enter.

Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net
Uninstalling the Windows Service using InstallUtil.exe
The syntax for uninstalling a Windows Service is very similar to the installation syntax.
InstallUtil Syntax
InstallUtil /u <Path of Windows Service EXE file>
Example:
InstallUtil /u C:\Users\Mudassar\Projects\WindowsService\bin\Debug\WindowsService.exe
After successful uninstallation you will see the following message.
Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net
Please comment.