Create GUI with Gtkmm - Setup Eclipse for Gtkmm

gtkmm is the official C++ interface for the popular GUI library GTK+. You can create user interfaces either in code or with the Glade User Interface designer, using Gtk::Builder.
Still you can use gtk on C++, but C++ is the Object Oriented Programming language then Gtkmm enable you to use some OOP techniques such as inheritance, polymorphism, etc... Also enable you to use standard C++ libraries on Gtkmm calls. Also gtkmm can be use to create GUI in C++ with the large number of widgets which you need to decorate your GUI.

I am willing to write a series of articles/tutorials about Gtkmm and its variance widgets with practical examples. Because I used gtkmm for my final year project and I would like to share the knowledge that I garbed with you all. This article describe the initial steps that you should follow to setup gtkmm library on Ubuntu and configure eclipse for gtkmm developing. I am using Eclipse Helios on Ubuntu 11.04 (64-bit).

Step 1 (Install required packages)
As you know there are several ways to install packages on Ubuntu. I am using Synaptic package manager for that.
So open synaptic from application menu and search for gtkmm-dev and install the latest version from the search result. I have installed libgtkmm-2.4-dev package. When you install synaptic will indicate some dependencies such as gtk++, install them all to complete the installation. I hope that you have the working eclipse with CDT (C/C++ Development Tooling).


Step 2 (Setup Eclipse for Gtkmm)
I am using CDT installed Eclipse IDE‌ for C++ developments. Because it has more features which are more helpful to developer to write programs effectively and rapidly.
Eclipse needs to be setup in order to create gtkmm project. Eclipse needs to complete these setups to compile the program successfully and fill the auto complete menu with all the functions, variables, data types, etc...
Initially you need to select Linux GCC as the toolchain when you create a C++ project on eclipse.
  1. Right click on the project that you need to be configure and select Properties from the menu.
  2. Expand C/C++ Build from the left side pane and click on Settings.
  3. Then click on GCC C++ Compiler.
  4. Paste following command line options between ${COMMAND} and ${FLAGS} to Command line pattern: text box.
    `pkg-config --cflags --libs gtkmm-2.4`
    Note - 2.4 holds the installed version, replace it with your version, if you installed different version.

    Now you may have the full text of the Command line pattern as,
    ${COMMAND} `pkg-config --cflags --libs gtkmm-2.4` ${FLAGS} ${OUTPUT_FLAG}${OUTPUT_PREFIX}${OUTPUT} ${INPUTS}
  5. Click on GCC C++ Linker and follow the same procedure as previous step.
  6. Now click on Includes under GCC C++ Compiler.
  7. Add include paths to the list and let eclipse find the header files on these paths. Click on add button and add following paths to the list. You should change the location by considering your location which includes installed on and version.

    /usr/include/gtkmm-2.4
    /usr/include/gdkmm-2.4
    /usr/include/glibmm-2.4

    Somehow finally you should include paths for gtkmm, gdkmm and glibmm libraries header files.

Now Eclipse ready for gtkmm development. Let's write a simple testing program to check the gtkmm.

First you should include following header files to the program. As,
#include <gtkmm.h>

Your main function should look like this,

int main(int argc, char **argv) {
    Gtk::Main kit(argc,argv);//The constructor for this object initializes gtkmm
    Gtk::Window frmMain;

    kit.run(frmMain);

    return 0;
}

Code explained,
All the gtkmm programs accepts command line arguments list as above (int argc, char **argv). Therefore all the gtkmm programs should follow the same argument list as describe in here.

Gtk::Main kit(argc,argv);//The constructor for this object initializes gtkmm

This line will initialize the basic gtkmm functionalities and let program to run gtkmm functions. Also checks the arguments passed to your application on the command line, looking for standard options such as -display.


Gtk::Window frmMain;

This will create a new widget of Gtk::Window type as frmMain to hold the main window of the program.


kit.run(frmMain);

This is the main loop of gtkmm and let user to use the widgets. This line will display the window which we already created.

You can download the complete source code of this testing program. Resultant of the program is an empty window as,

Next article will describe the OO behavior of gtkmm and introduce the Glade UI designer for gtkmm.
Continue Reading...

Cteate Stack in C++ using template

Stack is a data structure that allows access to only one data item at a time. If you remove this data item from the stack you can access to the next to last data item of the stack. Also stack perform a Last-In-First-Out(LIFO) operation on the stack. You may find more on stack here.

I will explain basic stack operations and then let's move to code.

Push - Insert a data item to the top of the stack.

Pop - Remove a data item from the top the stack.

Peek - Retrieve the data item from the top of the stack.

Other stack operations can be understand by just looking at the code simply.




This is the stack created by using template of C++. So that you can set any data or class type for stack data. Further more this post will answer the question, How to create template stack in C++?

The Stack.h source file is,

#include <stdlib.h>

#ifndef STACK_H_
#define STACK_H_

template<class T> class Stack{

private:
    unsigned int maxSize;
    T *stackData;
    int top;

public:
    Stack(int size){
        stackData = new T[size];//to hold the T ‌type data items
        top = -1;//no items on the stack
        maxSize = size;//set maximum size that stack can hold
    }


    virtual ~Stack(){}

    int count(){
        return top + 1;
    }


    bool isEmpty(){
        return top == -1 ? true : false;
    }


    bool isFull(){
        return top == maxSize - 1 ? true : false;
    }


    T* peek(){
        if(!isEmpty())//check for empty
            return &stackData[top - 1];
    }


    T* pop(){
        if(!isEmpty()){
            top -= 1;//decrease the top by 1 to indicate the delete
            return &stackData[top];//return deleted item
        }
        return NULL;
    }


    void push(T* item){
        stackData[top++] = *item;//insert to data array and increase the top by one
    }
};


#endif /* STACK_H_ */

Then the demonstration code,

#include <iostream>
#include "Stack.h"

using namespace std;

int main() {

    int data;
    Stack<int> intStack(10);//create integer stack with maximum 10 items

    //insert data to stack
    data = 1;
    intStack.push(&data);
    data = 2;
    intStack.push(&data);
    data = 3;
    intStack.push(&data);
    data = 5;
    intStack.push(&data);

    //get top item
    cout << *intStack.peek() << endl;

    intStack.pop();
    intStack.pop();

    //get top item
    cout << *intStack.peek() << endl;
   
    return 0;
}


I expect this will help anybody who want to create stack with the template!

Continue Reading...

Style source codes on the web page

Is there any way to change style of the source code that you include in the web page with simple method? Yes, there is. If you read my previous posts such as hibernate operations, ant build file, you can see the way my source codes are presented. Key words, variable names, and class names, etc are formatted according to the language that source code belongs.

How did I formatted these text on the web page? Did I change font color of each words on the text? No there is a easy method to do that. Thanks to google code prettify on google code.

This is the method that you should follow to format your source code snippets in an html page.

You can simply download their zip file and add those source file to your web page by uploading to the hosting server.

But I will explain an easy way to do that using online resources itself without downloading and uploading.

Step 1
Okay first you have to add reference CSS and JavaScript file to your web page's head section. Copy following code to head section on your web page.

<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/>
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>

If you are a google blogger you should copy the above code to blog's layout head section.
Here we use their online resource of CSS and JavaScript file to load styles and functions to our web page.

Step 2
Now just only one initialization for our code formatter. Copy the following code to body tag on your page.
You should use the layout as same as previous step, if you are a google blogger.

onload="prettyPrint()"

As an example

<body onload="prettyPrint()">

Step 3
Now just surround your text which you want to format with code or pre tag and set the Prettier class to specify the language. that is all. following example show you how to do that.

Example -
Normal text of your source code is,

//This is JAVA source code
import java.util.Scanner;
class keyboardDemo {
    public static void main(String[] arg) {
        //read from System.in = normally keyboard
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter two integers : ");
        int x;
        //read the inputs
        x=keyboard.nextInt();
    }
}

Now surround this text with code tag and particular style on your HTML source code.

<code class="prettyprint lang-java">
//This is JAVA source code<br />
import java.util.Scanner;<br />
class keyboardDemo {<br />
&nbsp;&nbsp; public static void main(String[] arg) {<br />
&nbsp;&nbsp; &nbsp;&nbsp; //read from System.in = normally keyboard<br />
&nbsp;&nbsp; &nbsp;&nbsp; Scanner keyboard = new Scanner(System.in);<br />
&nbsp;&nbsp; &nbsp;&nbsp; System.out.print("Enter two integers : ");<br />
&nbsp;&nbsp; &nbsp;&nbsp; int x;<br />
&nbsp;&nbsp; &nbsp;&nbsp; //read the inputs<br />
&nbsp;&nbsp; &nbsp;&nbsp; x=keyboard.nextInt();<br />
&nbsp;&nbsp; }<br />
}<br />
</code>

Now you can see the formatted source code as follows on your web page,

//This is JAVA source code
import java.util.Scanner;
class keyboardDemo {
    public static void main(String[] arg) {
        //read from System.in = normally keyboard
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter two integers : ");
        int x;
        //read the inputs
        x=keyboard.nextInt();
    }
}


If you need you can surround code with a div tag to change background color and wrapping style.

My div tag looks like this,

<div style="background: none repeat scroll 0% 0% rgb(209, 206, 206); border: 2px none; overflow: auto; white-space: nowrap;">

</div>

Now final styled text is,

//This is JAVA source code
import java.util.Scanner;
class keyboardDemo {
    public static void main(String[] arg) {
        //read from System.in = normally keyboard
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter two integers : ");
        int x;
        //read the inputs
        x=keyboard.nextInt();
    }
}

Code prettify support several language for style them. To change the language that you need to style just change the class of the style to your language.


For JAVA,

<code class="prettyprint lang-java">

Example -

//This is JAVA source code
import java.util.Scanner;
class keyboardDemo {
    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter two integers : ");
        int x;
    }
}

For xml,

<code class="prettyprint lang-xml">

Example -

<project default="final" name="yourProjectName">
           <target name="final" description="this is a function to echo some text">
                    <echo message="Hello world..."/>
           </target>
</project>


For HTML,

<code class="prettyprint lang-html">

Example -

<!DOCTYPE html>
<html>
    <body>
        <h1>My First Heading</h1>
        <p>My first paragraph.</p>
    </body>
</html>

You can refer this page for further more support languages. So that's all have fun with this!



Continue Reading...

Migrating from Visual SourceSafe to Team Foundation (VSS to TFS)

This post will describe how to totally migrate a Visual Sorcesafe database to Team Foundation Server. After migration the database you will have all the details on VSS database such as your source codes, users, and version history, etc...

There are some prerequisites which you should consider before start the migration process. Those are,
  • Team Explorer on Visual Studio.
  • Log on to the computer by using administrative credentials.
  • SQL Server Express.
  • Visual SourceSafe 2005 or later versions.
  • The Visual SourceSafe database that you want to analyze.
  • The administrator’s password for the Visual SourceSafe database.
And also some permissions, Therefore To perform the procedures in this post, you must have the following permissions.
  • In the Visual SourceSafe database that contains the data that you want to migrate, you must know the password of the Admin account.
  • On the migration machine (the machine where Visual Studio is installed), you must be a member of the Administrators group.
  • On the database that VSSConverter uses, you must have "create database" permission.
  • Be a member of the sysadmin server role for SQL Express. (By default, you are a member of the sysadmin server role if you are a member of the Administrators security group on the computer where SQL Express is installed.)
  • On your application tier for Team Foundation, you must be a member of the Team Foundation Administrators security group. For more information, see Team Foundation Server Permissions on MSDN.
Basically there are 3 main steps involved on migration.
  1. Preparing the Visual SourceSafe Database
  2. Analyzing the Projects for Migration.
  3. Migrating SourceSafe Project Folders to TFS
1. Preparing the Visual SourceSafe Database
This step also can be break down into three steps.

  1. Ask all database users to check in their files.
  2. Create a backup copy of your Visual SourceSafe Database to migrate.
  3. Use the Visual SourceSafe Analyze utility to locate and fix data integrity issues in the database.
a. Ask all database users to check in their files.
You should make sure that all the users are not loged-in to the VSS and all the files are checked in to the VSS.

So you can check loged in users from "Microsoft Visual SourceSafe Administration" tool. (Start --> All programs --> Microsoft Visual Sorcesafe --> Microsoft Visual SourceSafe Administration).

Also you can list all the check out files with the checked out user by issuing following command on cmd.
Here we are using ss.exe which is supplied by VSS therefore you should change the directory to VSS installation path.
Ex:- cd "C:\Program Files\Microsoft Visual SourceSafe"
If you need user wise list, type following command on cmd
ss status -R -Umilinda > "C:\Users\milinda\Desktop\VSS Checkouts\milindaCheckouts.txt"
This command will save all the files those checked out by milinda to the C:\Users\milinda\Desktop\VSS Checkouts\milindaCheckouts.txt file.
If you need all the checked out files list, type following command on cmd
ss status -R > "C:\Users\milinda\Desktop\VSS Checkouts\allCheckouts.txt"
This command will save all the files those checked out by all users to the C:\Users\milinda\Desktop\VSS Checkouts\milindaCheckouts.txt file.

b. Create a backup copy of your Visual SourceSafe Database to migrate.
Make sure that no one is using the database and that Analyze will not begin to run while you are backing up the database. To backup the VSS database just copy the following folders and files which are located on sorcesafe's database path. (You may find this database path from Visual SourceSafe Explorer File --> Open sorcesafe databse or press Ctrl+P).
  • \DATA
  • \Temp
  • \USERS
  • user.txt
  • srcsafe.ini
When you follow this procedure, you can do a full restore of the database by replacing the existing Users, Temp and Data folders as well as the Users.txt and Srcsafe.ini files with the copied versions.
You can also use this procedure to move the database to another location by placing the copied files into a new folder. To open the database, on the File menu in the Visual SourceSafe Explorer, click Open SourceSafe Database to browse to the new location.


c. Use the Visual SourceSafe Analyze utility to locate and fix data integrity issues in the database.

Just run analyze.exe on command prompt as “analyze -F -V3 <sourcesafe data directory>” which is located onC:\Program Files\Microsoft Visual SourceSafe”

-F stands for fix, This will automatically repairs inconsistencies and corruption that are detected, as long as no users are logged in.

-V3 to displays all errors.

More command line options can be found here.

Remember you should give the data path (\DATA) as argument not the database path which you found from Visual SourceSafe Explorer.

As my experience it will take 3 hours to 4 hours time duration to complete the analysis on 4.2GB database. Somehow this duration depends on errors on your database also.

Now preperation of Visual SourceSafe Database is finished. Let's move to next step.

2. Analyzing the Projects for Migration.

This process is based on xml input file. After running this step you will get an user mapping file and analyze report file which are needed for next step.

VSSConverter.exe tool is used to analyze the VSS projects that located on “C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE”. But still you can be invoked it from the Visual Studio command prompt. Or simply cd to the above path from cmd and follow the following commands.

My recommendation is copy VSSConverter.exe and VSSConverter.exe.config file to a different location and perform following commands.

VSSConverter.exe accepts following inputs to perform its operations
  • A path of the folder that contains the srcsafe.ini file for the Visual SourceSafe database under migration.
  • An XML-based file that contains settings.
This path you may find on Visual SourceSafe Explorer (File --> Open sorcesafe databse or press Ctrl+P)

The XML-based file format is,


<?xml version="1.0" encoding="utf-8"?>
<SourceControlConverter>
      <ConverterSpecificSetting>

            <Source name="VSS">
                  <VSSDatabase name="VSSDatabase_name"></VSSDatabase>
            </Source>

            <ProjectMap>
            <Project Source="$/FolderA"></Project>
            <Project Source="$/FolderB"></Project>
            </ProjectMap>

      </ConverterSpecificSetting>

      <Settings>
       <Output file="Analysis.xml"></Output>
     </Settings>
</SourceControlConverter>

  • Modify the VSSDatabase_name to point to the path to your VSS database.
  • In the <projectmap> section, specify the Visual SourceSafe folders to analyze. 
    • To analyze the whole database, use <Project Source="$/"></Project>
  • Save above XML file as settingsAnalyze.xml to the directory where VSSConverter.exe and VSSConverter.exe.config file located.
Now you can run the converter tool to analyze VSS projects. The user who is performing the analysis must be a system administrator for SQLExpress. By default, the user who installs Visual Studio will receive the required permissions for SQLExpress.
  • cd to directory where VSSConverter.exe and VSSConverter.exe.config file located and run following command
    • VSSConverter Analyze settingsAnalyze.xml
  • When you are prompted, provide the Visual SourceSafe administrator password.
The converter tool displays the status of the pre-conversion analysis. When it is completed, it generates a report (VSSAnalysisReport.xml) and a user mapping file (usermap.xml), and saves them in the current directory.

You can use this user mapping file to map Visual SourceSafe users to Team Foundation users.

3. Migrating SourceSafe Project Folders to Team Foundation Server


The converter also needs an xml file. It is most similar to settings.xml file which is created at analyze step. Therefore,

  1. Copy settingsAnalyze.xml file content and save it as settingsMigration.xml. (Ensure that the system drive has sufficient space to hold the largest file size under migration.)

  2. Change the settings file as follows.
    • In the <ProjectMap> sections, for each Visual SourceSafe folder, add the destination folders in TFS. This destination should be already created on TFS.
      <Project Source="$/FolderA" Destination="$/Team_ProjectA"> </Project>

    • To migrate everything in your Visual SourceSafe database, insert the following XML instead.
      <Project Source="$/" Destination="$/Team_Project/"> </Project>

    • Under the <Settings> section, add a <TeamFoundationServer> section, and specify the name, port, and protocol for the Team Foundation Server to which you are migrating. Use the following format. Here you should set the collection to a collection that you created on TFS insted of 'DefaultCollection'.
      <TeamFoundationServer name="TFS_server_name" port="port_number" protocol="http" collection="tfs/DefaultCollection"></TeamFoundationServer>

    • Remove <Output file="Analysis.xml"></Output> from the <Settings> section, or rename the output file to "migrationAnalysis.xml".
  3. Overall structure of a migration settings file as follows

    <?xml version="1.0" encoding="utf-8"?>
    <SourceControlConverter>
       <ConverterSpecificSetting>
          <Source name="VSS">
             <VSSDatabase name="VSSDatabase_name"></VSSDatabase>
             <UserMap name="c:\Migrate\Usermap.xml"></UserMap>
          </Source>
          <ProjectMap>
             <Project Source="$/FolderA" Destination="$/TeamProjectA">
             </Project>  
             <Project Source="$/FolderB" Destination="$/TeamProjectB/ProjectB">
             </Project>
          </ProjectMap>
       </ConverterSpecificSetting>
       <Settings>

          <TeamFoundationServer name="server_name" port="port_number" protocol="protocol" collection="tfs/DefaultCollection"></TeamFoundationServer>

        </Settings>
    </SourceControlConverter>

  4. Edit the Source Control Migration User Mapping File
    If you want to map user name to TFS from VSS as it is, you can keep usermapping.xml file remain unchanged and go to next step.

    The analysis phase generated a user map file. The user map file consists of all Visual SourceSafe users who have performed any source control operation on the folders that you specified for the migration. You use this file to map Visual SourceSafe users to Team Foundation users.

    For each Visual SourceSafe username you want to map, add a valid Windows user name or Team Foundation Server user name in To field, as shown in the following example. The ADMIN user in VSS should be mapped to a real user in TFS, typically the project administrator. Users in VSS who are no longer with the company should be mapped to existing users.

    For example,

    <?xml version="1.0" encoding="utf-8"?>
    <UserMappings>
        <UserMap From="Admin" To="MYDOMAIN\Jennifer"></UserMap>
        <UserMap From="guest" To="TestAlias1"></UserMap>
        <UserMap From="Jane" To="Jane"></UserMap>
        <UserMap From="Mike" To=""></UserMap>
    </UserMappings>

    If you provide a user name mapping similar to <UserMap From="Mike" To=""></UserMap> where "Mike" is a valid Windows user name, Team Foundation maps "Mike" to "MYDOMAIN\Mike," where MYDOMAIN is the default domain.

  5. Before you run the following command you should create the team project as you define on settingsMigration.xml file. You can refer this to create new team project

  6. Execute following command on cmd to migrate the VSS database to TFS as you define in above xml files.
              VSSConverter Migrate settingsMigration.xml

  7. When you are prompted, provide the password for the Visual SourceSafe admin user.

So that is it.........
After long post, you may have a totally migrated TFS database from VSS with all the VSS data such as source files, histories, users, etc..

The whole process takes 6-7 hours time duration to migrate 4.2GB VSS database. But this may change up to your database size, users, histories, network speed, etc.

I apologize, If this post is getting too long but these are the basic step that you should follow to migrate. Have a nice day thanks.
Continue Reading...

Microsoft Team Foundation Server (TFS)


Why do we need version controller or source controller? This post will answer this question and introduce a version controller which is introduced by Microsoft (Team Foundation Server) and compare it with the Microsoft visual sourcesafe.

This is a compact post of all above things, most of the things had refer on internet. Thanks every one who write these things on the web.

Let's try to answer above question. Actually why do we need a Version Control System (VCS)? Let's assume you are working on a large project and each single module developed by single programmer and also they need to share their source or builds among each others when they needed. So simply you can suggest a shared folder to hold all the sources and builds which every one can access it. But what's happen when two programmers open same project and edit it by both of them? Exactly it will complicated for both programmers. And also there are no way to control versions ~ can not roll back to previous version. Now you understood the needs of VCS.

You may find available VCS here

Now let's move to TFS.

What is TFS?

Team Foundation is a client-server source control system that uses a .NET Web service to access items stored in a SQL Server database.
  • Version control, for managing source code and other deliverables that require versioning.
  • Work item tracking, for keeping track of such things as defects, requirements, tasks, and scenarios.
  • Project management functions, which allow the shaping of a team project based on a user-specifiable software process, and which enable planning and tracking using Microsoft Excel and Microsoft Project.
  • Team build, for enabling a common process for building executable products.
  • Data collection and reporting, which aid in the assessment of a team project's state, based on information gleaned from Team Foundation Server tools.
  • The Team Project Portal, which provides a central point of communication for a team project packaged as a Microsoft Windows SharePoint Services site.
  • Team Foundation Shared Services, which provide a number of common infrastructure services that invisible to end users but that, are important to tool smiths and extenders.

Ways to access TFS

  • From Visual Studio – through Team Explorer
  • From the command line
  • From the web browser
  • From Microsoft Office products
  • From other platforms or IDEs
  • From Windows Explorer
There are some other products also to access to TFS.

Following figure shows the web interface of the TFS



Comparison between Visual Source Safe and TFS.

Visual source safe is an old software that Microsoft developed for version control. Most of the visual studio programmers are still use SourceSafe. But there is a way to completely migrate from VSS to TFS. We will see that method later. Now let's move to comparison.







VSS
TFS
Description
Security and Project Rights
Low
High

Reliability

Low
High
VSS does not have a server component, while TFS is client server application. TFS writes operations occur in the database by way of stored procedures that are not subject to network connectivity issues.
Scalability
Low
High
TFS can support teams of up to 2000 users whereas VSS is recommended for teams of 20 or less.
Sharing and Pinning
Yes
No
Share or Pin features not in TFS. When you migrate VSS projects to Team Foundation, Pins in a Visual SourceSafe database are replaced by labels.
Check-Out and Check-In
Yes
Yes
In Visual SourceSafe, you must do an explicit check-out and check-in only if you are editing a file. In Team Foundation, every action requires an explicit check-out and check-in.

Team Foundation Features that Do Not Exist in Visual SourceSafe

Visual SourceSafe Features that Do Not Exist in Team Foundation

  • Share
  • Pin
  • Archive and Restore
  • Destroy
  • Keyword expansion
  • Rollback
 Next post will be a complete guidance to migrate VSS database to TFS.



Continue Reading...

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.

Complete project can be downloaded from here.
Continue Reading...

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.


Continue Reading...

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.


Complete Visual studio C# project can be download from here.

My next post will describe how to check your event log to ensure your program.
Continue Reading...