Thứ Ba, 31 tháng 3, 2009

Cận cảnh thảm kịch bóng đá ở Bờ Biển Ngà

Lượng CĐV quá đông và một bức tường trên sân Houphouet-Boigny đổ sụp chưa phải là tất cả nguyên nhân làm 22 người thiệt mạng và hơn 130 người khác bị thương, hôm chủ nhật.

Theo lý giải của nhà chức trách sở tại, do quá nhiều người tìm cách vào sân, một bức tường trong sân bị đổ, tạo nên cảnh hỗn loạn dẫn đến thương vong.
Tuy nhiên, nhiều nhân chứng cho biết cảnh sát cũng góp một tay khiến tình hình thêm bi kịch bằng cách dùng đạn hơi cay để giải tán đám đông, khiến các CĐV này càng bấn loạn, giẫm đạp lên nhau, khiến nhiều người thiệt mạng và bị thương.
Cảnh sát sau đó rất tích cực tham gia vào công tác cứu hộ, cùng các nhân viên y tế và một số CĐV chuyển các nạn nhân xấu số và những người bị thương khỏi khu vực hỗn loạn.
Số CĐV thiệt mạng được tập trung ở một khu vực trên sân.
Những người bị thương được đưa ra xe cấp cứu đển bệnh viện.
Bất chấp sự cố vừa diễn ra trước trận, Drogba cùng các đồng đội của anh vẫn chơi tưng bừng, đè bẹp Malawi 5-0 và hân hoan đón nhận đại thắng.
Các CĐV Bờ Biển Ngà cũng đốt pháo sáng, nhảy múa như chưa hề có thảm kịch vừa xảy ra với nhiều đồng bào họ.
Trong khi đó, tại bệnh viện, những bà mẹ mất con và đám đông người nhà của các nạn nhân xấu số gào thét trong nỗi đau.

Simple Windows Service Sample

Introduction

As a matter of fact Microsoft Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.

Windows services don�t have any interface to the user, so it can not be debugged like any regular application, but it�s debugged as a process. .NET has a very nice tool that enables processes debugging while it�s in the run status, by easily pressing Ctrl + Alt + P shortcut.

Background

I�ve searched well so many sites about a code that I can with the help of it, build a simple Windows service, but I found a lot of code on how to manage the current Windows services of the system and that�s through the ServiceController class.

After searching the MSDN, I�ve found some nice code that helped me to create this simple Windows service. Hope it can help as a basic architecture for and usage of such a Windows service.

Using the code

At first you should simply open VS.NET and then at the File menu click on New, Project. From the New Project Dialog Box, choose the Windows service template project and name it MyNewService like shown below:

Winows Service New Project

The project template automatically adds a component class that is called Service1 by default and inherits from System.ServiceProcess.ServiceBase.

Click the designer. Then, in the Properties window, set the ServiceName property for Service1 to MyNewService.

Set the Name property to MyNewService. Set the AutoLog property to true.

In the code editor, edit the Main method to create an instance of MyNewService. When you renamed the service in step 3, the class name was not modified in the Main method. To access the Main method in VC#, expand the Component Designer generated code region.

Collapse
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
//Change the following line to match.

ServicesToRun = new
System.ServiceProcess.ServiceBase[] { new MyNewService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

In the next section, you will add a custom event log to your Windows service. Event logs are not associated in any way with Windows services. Here the EventLog component is used as an example of the type of components you could add to a Windows service.

To add custom event log functionality to your service:

  1. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.
  2. From the Components tab of the Toolbox, drag an EventLog component to the designer.
  3. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.
  4. Edit the constructor to define a custom event log.

To access the constructor in Visual C#, expand the Component Designer generated code region.

Collapse
public MyNewService()
{

InitializeComponent()
if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
"DoDyLog");

eventLog1.Source = "DoDyLogSourse";
// the event log source by which


//the application is registered on the computer


eventLog1.Log = "DoDyLog";
}

To define what happens when the service starts, in the code editor, locate the OnStart method that was automatically overridden when you created the project, and write code to determine what occurs when the service begins running:

Collapse
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("my service started");
}

The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

To define what happens when the service is stopped, in the code editor, locate the OnStop procedure that was automatically overridden when you created the project, and write code to determine what occurs when the service is stopped:

Collapse
protected override void OnStop()
{
eventLog1.WriteEntry("my service stoped");
}

You can also override the OnPause, OnContinue, and OnShutdown methods to define further processing for your component. For the method you want to handle, override the appropriate method and define what you want to occur. The following code shows what it looks like if you override the OnContinue method:

Collapse
protected override void OnContinue()
{
eventLog1.WriteEntry("my service is continuing in working");
}

Some custom actions need to occur when installing a Windows service, which can be done by the Installer class. Visual Studio can create these installers specifically for a Windows service and add them to your project. To create the installers for your service.

  1. Return to design view for Service1.
  2. Click the background of the designer to select the service itself, rather than any of its contents.
  3. In the Properties window, click the Add Installer link in the gray area beneath the list of properties. By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
  4. Access design view for ProjectInstaller, and click ServiceInstaller1.
  5. In the Properties window, set the ServiceName property to MyNewService.
  6. Set the StartType property to Automatic.

Tip

To avoid being asked about the system username and password you must change the Account for the serviceProcessInstaller to LocalSystem. This is done by opening the ProjectInstaller design and then selecting the serviceProcessInstaller, press F4 and then change the Account property to LocalSystem. Or you can manually do that by creating a class that inherits from System.Configuration.Install.Installer like this:

Collapse
[RunInstaller(true)]

public class ProjectInstaller : System.Configuration.Install.Installer
private System.ServiceProcess.ServiceProcessInstaller
serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
/// <summary>

/// Required designer variable.

/// </summary> private System.ComponentModel.Container components = null;


public ProjectInstaller()
// This call is required by the Designer.

InitializeComponent();

// TODO: Add any initialization after the InitComponent call

}
private void InitializeComponent()
{
this.serviceProcessInstaller1 =
new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 =
new System.ServiceProcess.ServiceInstaller();
// serviceProcessInstaller1

//

this.serviceProcessInstaller1.Account =
System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//

// serviceInstaller1

//

this.serviceInstaller1.ServiceName = "MyNewService";
this.serviceInstaller1.StartType =
System.ServiceProcess.ServiceStartMode.Automatic;

//

// ProjectInstaller

//

this.Installers.AddRange
(new System.Configuration.Install.Installer[]
{
this.serviceInstaller1,
this.serviceInstaller1});
}
}

To build your service project

  1. In Solution Explorer, right-click your project and select Properties from the shortcut menu. The project's Property Pages dialog box appears.
  2. In the left pane, select the General tab in the Common Properties folder.
  3. From the Startup object list, choose MyNewService. Click OK.
  4. Press Ctrl+Shift+B to build the project.

Service Project Property Page

Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers needed to run the Windows service. To create a complete setup project, you will need to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed.

To create a setup project for your service

  1. On the File menu, point to Add Project, and then choose New Project.
  2. In the Project Types pane, select the Setup and Deployment Projects folder.
  3. In the Templates pane, select Setup Project. Name the project MyServiceSetup.

A setup project is added to the solution. Next you will add the output from the Windows service project, MyNewService.exe, to the setup.

Service Setup Project

To add MyNewService.exe to the setup project

  1. In Solution Explorer, right-click MyServiceSetup, point to Add, then choose Project Output. The Add Project Output Group dialog box appears.
  2. MyNewService is selected in the Project box.
  3. From the list box, select Primary Output, and click OK.

    A project item for the primary output of MyNewService is added to the setup project. Now add a custom action to install the MyNewService.exe file.

To add a custom action to the setup project

  1. In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.
  2. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.
  3. Double-click the application folder in the list box to open it, select primary output from MyNewService (Active), and click OK. The primary output is added to all four nodes of the custom actions � Install, Commit, Rollback, and Uninstall.
  4. Build the setup project.

To install the Windows Service

Browse to the directory where the setup project was saved, and run the .msi file to install MyNewService.exe.

Service Setup

To start and stop your service

  1. Open the Services Control Manager by doing one of the following:
    • In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.

      - Or -

    • In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.

      Note: In Windows NT version 4.0, you can open this dialog box from Control Panel.

  2. You should now see MyNewService listed in the Services section of the window.
  3. Select your service in the list, right-click it, and then click Start.

Right-click the service, and then click Stop.

Admin tools Services

To verify the event log output of your service

  1. Open Server Explorer and access the Event Logs node. For more information, see Working with Event Logs in Server Explorer.

    Note: The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET.

    Sample screenshot

To uninstall your service

  • On the Start menu, open Control Panel and click Add/Remove Programs, and then locate your service and click Uninstall.
  • You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.

Windows Services in Action I

Download SimpleWindowsService.zip - 427 KB

Introduction

While we were developing our Corporate Portal, I was asked for a functionality, which congratulates the birthday of our stuff sending an e-mail message. There was a congratulating message doing the same task at the main page of Intraweb but it was only for whom opens that. But we wanted that when they open their mailbox, they see a congratulating message of their own birthdays.
There fore I realised that this cannot be accomplished with a web application and I decided to create a windows Service which will run on the server and search once in a day the stuffs birthdays and then send them the message if there is(are) a match(any matches.)
Shorly, the task is to search database for the stuff table and if there is(are) birthday(s) matching on the day, send them a congratulation message (e-mail). I thought that it could be achieved best using a windows service.

The basics of Windows services are given in this article. If you feel your knowledge enough, you can just skip this one and step on next article here. Windows Services in Action II.

Background

Some tasks can be solved with only windows services effectively.So every developer should decide when to use them and how to use them. I have searched about windows services because i needed in numerous cases. After all code work i decided to share it with other coders.

Windows Services in .NET

Firstly I will try to give you basic information about Windows Services in .NET and show how we can use in a real-world task. Steps:

1. What are windows services?

2. The Architecture

3. The Methods

4. The Components

5. Create a windows service application

6. Installation process

7. Monitoring and administration

1. What are windows services?


Windows services are used to create long-running executable applications that run in their own Windows sessions in the background. Windows services do not have a user interface because they are not meant to interact with users. They can be configured to start automatically when the computer boots, we can start them manually or some start when needed. They can be started, paused, restarted or stopped using the Service Control Manager which is the central utility provided to control them.
They must be installed to system to run in a normal manner. We cannot run or debug Window services without installation.We need a special component to install them or take special steps to have them ready to run.Windows service applications run in a different window station than the interactive station of the logged-on user. Because the station of the Windows service is not an interactive station they should be logged in the Windows event log instead of using a user interface.
Windows service applications run in their own security context and are started before any users log on into the computer which they are installed.Some examples to Windows service applications:
Network Connections, Print Spooler, Net Logon…You can see them typing services.msc on the Run menu item of Windows Start Menu if you have an NT Based OS like Windows 2000, XP, 2003 Server…

2. The Architecture of Windows services in .NET

  • ServiceBase Class To create a new service class, it inherited from SerciveBase class. The methods of the class can be overridden to change their functionality if needed.
  • ServiceProcessInstaller
    A windows service must be represented using ServiceProcessInstaller class in obtain to communicate and control the service.

  • ServiceInstaller
    A windows service must be expanded using ServiceInstaller class to be able to use the standart .NET installation method.
  • The namespace of these classes is System.ServiceProcess and their assembly is System.ServiceProcess. So they can be found in system.serviceprocess.dll.

3. The Methods

There are several methods exposed by the ServiceBase class These methods can be overridden to add custom behavior.

OnStart: This is called when the service starts running. So we can override it if we need to take an action in this step.
OnPause: This is called when the service is paused.
OnStop: This is called when the service is stopped.
OnContinue: This is called when the service is resumed after being paused.
OnShutdown: This is called when the service is just prior to your system shutting down.
OnCustomCommand: This is called when your service receives a custom command.
OnPowerEvent: This is called when a power management event is received.

4. The Components

  • First of all, the service has some properties like CanStop(true by default), CanShutdown, CanPauseAndContinue, ServiceName(Service1 by default)
  • EventLog component is widely used in windows services. Logs can be created by this component very simply. Log is the name of the log. Source property is to spesify the application name to use when writing to the eventlog. There will be some code examples related to eventlog component.
  • ServiceInstaller and ServiceProcessInstaller components are necessary to make the windows service ready to use standard setup project. These two components are added automatically if we add installer to the service. ServiceInstaller’s mostly set properties are ServiceName which is shown in the services tool and StartType which determines when the service is started. The most important property of ServiceProcessInstaller component is account. Usually this property is set to LocalService.

5. Create a windows service application

We can create a windows service writing code or using Windows service project template.


Creating a windows service

  • Open Visual Studio 2005, click File, New and choose Project menu item. You will see the window below.

Screenshot - S-0000.jpg

  • Select Windows Service project template and rename project name as “SimpleWindowsService” or whatever you want.
  • Then VS will create all basic classes for you and you will see the environment like below.
Screenshot - S-0001.jpg
  • You can change the name of service1 as SimpleService. If you do this, a small window will apear and ask you whether you change related refences. Click yes.
  • If you double click the workspace of SimpleService[Design], you can see the code page where you can work when necessary. Illustrated below.
Screenshot - S-0002.jpg
  • As you see, most of the codes and classes created automatically. Program.cs is where the service created and run. It uses ServiceProcess. So you can see using System.ServiceProcess; code at the top.
  • Usually you don’t have to anything here.
Screenshot - S-0003.jpg

Now, our SimplewWindowsService is ready to go. You can build it (by pressing F6) But we cannot run it because it is not installed. And even it is installed it doesn’t have any functionlities except starting, stoping.


Therefore we will add some simple functonalities to our SimpleService.

Adding some functionalities to a Windows Service

  • Open SimpleService.cs in Design mode.
    The is task is to write into a log when the service starts and stops so that we will be simply informed using Windows standard Eventviewer.
  • When in Design mode of SimpleService.cs Drop an eventLog component from the Components tab in the Toolbox to design area.
    (To switch to Design mode press Shift+F7 and to switch to code view press F7)
Screenshot - S-0000a.jpg
  • Rename eventLog1 component’s name as eventLogSimple · The eventlog component must be initialized in SimpleService method which is already created automatically in SimpleService.cs. After we modified the code, it will look like below:
Collapse
public SimpleService()
{
InitializeComponent();
// Initialize eventLogSimple
if(!System.Diagnostics.EventLog.SourceExists("SimpleSource"))
System.Diagnostics.EventLog.CreateEventSource("SimpleSource","SimpleLog");
eventLogSimple.Source= "SimpleSource";
eventLogSimple.Log = "SimpleLog";
}
  • Add the line below to OnStart Method which is already created.
Collapse
eventLogSimple.WriteEntry("Hello world from Simple Service!");
  • Add the line below to OnStart Method which is already created also.
Collapse
eventLogSimple.WriteEntry("Simple Service stopped!");

  • Press F6 to build our windows service if you see “Build succeded” message at the bottom on the satus bar, you are done. Now, our windows service is ready to be installed.

6. Installation process

Install the Windows Service
The easiest way of installing a windows service is using the installer components and the Setup Project of Visual Studio 2005.

  • Right-click SimpleService.cs in Solution Explorer and select View Designer.
  • Right-click the design area and select Add Installer. Then ProjectInstaller.cs page will appear in design view. And there will be replaced two components in it: serviceProcessInstaller1 and serviceInstaller1 like below:

    Screenshot - S-0006.jpg
  • Rename them as serviceProcessInstallerSimple and serviceInstallerSimple respectively. · Find the ServiceName property of serviceInstallerSimple in Properties windows.
  • Rename its value as SimpleService. It is Service1(default value). The service will be presented by this value. So it is better to set to a meaningful name.
  • Another important property of serviceInstallerSimple component is StartType. It has three values: Manual, Automatic and Disabled. It is set to Manual by default. This means we must start the Service manually. Let’s set the property to Automatic so that it starts when windows starts.

Screenshot - S-0007.jpg

  • After that, select serviceProcessInstallerSimple in the designer and set the Account Property to LocalService. Therefore the service will be installed and run on a local account.
  • In Solution explorer, select SimpleWindowsService project, right-click it and select Properties.
  • The Property Designer of the project will appear. Chose SimpleWindowsService.Program from the Startup object on Application page.

Screenshot - S-0008.jpg

  • In Solution explorer, select Solution “SimpleWindowsService” and right-click and select Build Solution. If everything went OK, you see “Build succeded” message at the bottom.

The service is now can be installed. There are two installation methods:

  • Windows service can be on your system using InstallUtil.exe. The utility must be run on the Visual Studio 2005 Command Prompt (Usually found in "C:\Program Files\Microsoft Visual Studio 8\VC\ ". For instance, C:\Program Files\Microsoft Visual Studio 8\VC\installutil C:\SimpleWindowsService\SimpleWindowsService\bin\Debug\ SimpleWindowsService.exe in our case.

Screenshot - S-0009.jpg

And to uninstall the service the utility must be used with –u parameter: C:\Program Files\Microsoft Visual Studio 8\VC\installutil -u C:\SimpleWindowsService\SimpleWindowsService\bin\Debug\ SimpleWindowsService.exe

  • Another method is to add a setup project to the solution and use the result package to install and uninstall the windows service. In this case, the Add or Remove programs tool in the Control Panel of the windows system can be used to uninstall it.

Adding a setup project to our solution

  • Right-click SimpleWindowsService solution in Solution Explorer, select Add, New Project and select Deployment project. Give a meaningful title to the project as seen below.

Screenshot - S-0011.jpg

  • Right-click SetupSimpleWindowsService In Solution Explorer, select add, then choose Project Output.

Screenshot - S-0012.jpg

  • From the list box, select Primary Output, and click OK.

Screenshot - S-0013.jpg

  • To add a custom action right-click the setup project In Solution Explorer, select View, and then click Custom Actions.

Screenshot - S-0014.jpg

  • Right-click the Custom Actions node and choose Add Custom Action.

Screenshot - S-0016.jpg

  • Double-click the Application Folder in the list box to open it, select Primary Output from SimpleWindowsService (Active), and click OK.

Screenshot - S-0017.jpg

  • The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.

Screenshot - S-0018.jpg

  • In Solution Explorer, right-click the SimpleWindowsServiceSetup project and click Build. After building the solution there can be found setup project SetupSimpleWindowsService.msi in the setup folder. (C:\SimpleWindowsService\SetupSimpleWindowsService\Debug in our case.)

Screenshot - S-0019.jpg

  • It can be double-clicked to run the setup program and it is used to install, uninstall, commit and rollback. Finally the Setup Wizard of our solution be appeared and followed familiar setup steps.
  • Or the setup project can be started by right-clicking the setup project in Solution Explorer and selecting Install.

Screenshot - S-0020.jpg

  • After finished the installation, it can be seen in Services on our Windows System.
  • To view Services, from Control Panel choose Administrative Tools and click Services.

Screenshot - S-0021.jpg

  • To start the service right-click on it and select Start.

Screenshot - S-0022.jpg

  • To view the logs of our windows service click Event Viewer in Administrative Tools. You can see SimpleLog item in the treeview at the left which is created by our service and this item is where our services logs are kept. If you started the service, you can see an event log at the right.

Screenshot - S-0023.jpg

  • Double-click on it to open then you can see the message "Hello world from Simple Service!" here.

Screenshot - S-0024.jpg

  • To uninstall it you can use Add or Remove Programs in Control Panel.

Screenshot - S-0025.jpg

Ofcourse you can use the Setup Project to uninstall the service but be careful to use the same Build which is used for installation. If you built solution, installed it and then rebuilded it again the Setup Project changes and cannot uninstall the service. In this situation you can keep the Setup file which is used for installation or just use Add or Remove Programs tool.

7. Monitoring and administration

We said that windows services don’t need a user interface. Therefore we have to manage them using other tools. There are three ways:
1. Microsoft Services : The Services tool in Administrative Tools is also used to monitor and manage the services.
2. The console: Services can be managed by using the command prompt: The line below is used to start the service:
C:\net start SimpleWindowsService
3. Yes, we can manage them programmatically. I think this is out of the scope of this article.

Conclusion

I think, the solution is simple but of course should be improved to overcome your real-time problems. I am planning to improve my solution in the future and expect your help. I am planning to write another article to show you how a windows service can be used.

History

21 Aug 2007 Initial revision.

Sources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)