Tải bản đầy đủ (.pdf) (24 trang)

Reporting with a Windows Service

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (786.51 KB, 24 trang )

Reporting with a
Windows Service
I
n Chapter 7, we produced reports with a console application; the console application is sig-
nificant because it lacks a GUI. Now, let me introduce you to a host client that doesn’t even
have a text-based interface. You might be wondering how a user will communicate with a
client that has no user interface. Well, our report’s production will remain the same, but
instead of live keyboard input, we’ll make use of an automatic data feed using configuration
files or another data source.
A Windows service application is versatile—it has the ability to start, stop, and pause
according to user demand. Think of this: if you want to suspend the report production, all
you need to do is stop the service.
Let’s get started by building a Windows service application. After that, we’ll work on the
real-world practical reporting project.
This chapter covers
• “Windows Services 101,” a step-by-step tutorial
• Producing a report in PDF format and sending it as an e-mail attachment
• Scheduling report delivery
Windows Services 101
How does a Windows service help users of client-side reporting? Like all the clients we’ve
used in previous chapters, a Windows service has its own merits to qualify as a good client
host. A Windows service application runs in the background as long as the operating sys-
tem (Windows) is running, so a user can start, stop, or customize the service using the
Control Panel.
A Windows service application with a timer control hosted inside it is a killer solution to
produce and deliver time-sensitive reports. In such cases, delivering the report without requir-
ing any human intervention is the key factor in increasing efficiency. There are a few choices
of delivery: the report can be sent as an e-mail attachment, uploaded to an FTP site, or deliv-
ered in just about any way the business case demands.
A Windows service application can be installed on either an individual’s PC or a server. If
installed on a server, a single instance can service many different report delivery destinations


based on settings provided to the application.
285
CHAPTER 8
8547ch08final.qxd 8/30/07 3:48 PM Page 285
Creating a Windows Service Project
Please open Visual Studio, and use the following steps to create a Windows service application
project; Figure 8-1 illustrates these steps:
1. Click File

New

Project, or press Ctrl+Shift+N.
2. In the “Project types” pane of the New Project dialog box, select Visual C#

Windows.
3. In the Templates pane, select

Windows Service.
4. Give the application a name; I’ve called the project RSWindowsService101. You may
choose a different location for storing the application files according to your prefer-
ence.
5. Click the OK button to finish the process. VS will create a new Windows service project.
Figure 8-1. Create a new Windows service project.
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE286
8547ch08final.qxd 8/30/07 3:48 PM Page 286
Figure 8-2. Newly created Windows service
Figure 8-2 shows the code and files produced inside Solution Explorer. As you may notice
in Figure 8-2, a new class with the name

Service1.cs is part of the project. Now, you can drag
and drop different controls, like the timer control, from the toolbox on to the design surface.
Adding an Installer to the Windows Service Project
What is this installer? Well, each Windows service application needs some basic settings to
run; for example, you might set how a service will run—via a user account or the local system
account. Or you might dictate how a service should behave after booting Windows: should it
automatically start, or must a user go to the service’s Control Panel to manually start it?
We need to add an installer to our project for setting up these special parameters. Adding
the installer is simple: right-click the open area inside the service designer, and select Add
Installer. Figure 8-3 illustrates the steps for adding an installer.
A new file
ProjectInstaller.cs is part of the project now. You’ll also notice that two
processes
serviceProcessInstaller1 and serviceInstaller1 have become part of the
ProjectInstaller design surface. What important properties should we know for both
serviceProcessInstaller and serviceInstaller?
Let’s begin with
serviceProcessInstaller. Here, you need to define how your service
will run, that is, which account to use. By default, the choice is User, but you can select any-
thing fr
om the av
ailable choices, shown in Figure 8-4, according to the demands of your
business case.
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE 287
8547ch08final.qxd 8/30/07 3:48 PM Page 287
Figure 8-3. Adding an installer to the project
Figure 8-4. P
roperties of serviceProcessInstaller

N
ow, let’s look at
serviceInstaller1.
Two important properties of
serviceInstaller
worth mentioning are DisplayName , which appears in the Windows service control to help
identify the service, and
StartType, which defines how the service should start when Windows
is booted.
The default choice of
StartType is Manual, but in most cases, you’ll want to set it to Auto-
matic. Setting it to Automatic guarantees that the service will run every time Windows runs.
Figure 8-5 shows the available properties.
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE288
8547ch08final.qxd 8/30/07 3:48 PM Page 288

Note
You can set the
Account
property to User if the service is performing actions that need special
security privileges, for example, to impersonate a domain account to access database resources.
Figure 8-5. Properties of serviceInstaller
Please make sure you set the properties as indicated in Table 8-1.
Table 8-1. Properties Settings for the Windows Service Application
Object Property Value
serviceProcessInstaller1
Account LocalSystem
serviceInstaller1

DisplayName RS Windows Service for Reports
StartType
Automatic
P
lease check the
follo
wing MSDN link for fur
ther infor
mation on project installers:
/>➥
en-us/vbcon/html/vbtskAddingInstallersToYourServiceApplication.asp
User Interaction with a Windows Service
Typically, a Windows service application has no live user intervention through the keyboard or
the mouse. The service starts to work in the background after its installation. To allow user
input to the service, we have to use a text- or XML-based configuration file. Common data
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE 289
8547ch08final.qxd 8/30/07 3:48 PM Page 289
sources, such as MS Access or SQL Server, can also provide data as input to the service.
U
sually, a service produces logs for health or progress checks.
The
Service class is inherited from the ServiceBase class, which provides the base for
the service that is part of the Windows service application that calls the
ServiceBase con-
structor of the derived class. This is done by making a call to the
Start method when the
service is started. Immediately after this, the
OnStart method is called. In simple words, all

the functions to handle the service are encapsulated within the
ServiceBase class, leaving
developers to focus on the function of the service application, not how to coordinate the
service with the OS. You can find out more at this MSDN link:
/>➥
system.serviceprocess.servicebase_members.aspx
Let’s examine the code that is produced after creating the project. You can switch to code
view by right-clicking anywhere on the design surface and selecting View Code.
Typically, the
OnStart and OnStop methods are key pieces of functionality for any Windows
service application. The default code should look similar to the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
namespace RSWindowsService101
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary
// to stop your service.
}
}
}
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE290
8547ch08final.qxd 8/30/07 3:48 PM Page 290
The default code produced for the project installer should look as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
namespace RSWindowsService101
{
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
}
Building the Project
All the clients we developed in the previous chapters had some default behavior when we
ran them. However, Windows services are different; we can build the project, but we cannot

immediately run it within the VS IDE to watch the behavior.
The code used in this tutorial doesn’t do much. I’ve just shown you how you can build a
skeleton Windows service. When we start with the reporting project later, you’ll see that we
can write code using the timer control to produce the report and automate its delivery.
For now, let’s just get our Windows service application ready for client-side reporting. You
can build a Windows service by selecting Build

Build Solution from Visual Studio’s main
menu. If you press F5 on the keyboard, as you usually can to build projects, you will get an
error that says, “Cannot start service from the command line or a debugger . . .”
If all goes well, your project should compile without any issues, and you should be able to
see the Windows service application executable
RSWindowsServer101.exe in the bin folder of
the project, as shown in Figure 8-6.
Figure 8-6. The project’s bin folder contents after the build
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE 291
8547ch08final.qxd 8/30/07 3:48 PM Page 291
Installing the Windows Service Application
As I mentioned to you already, we cannot run a Windows service executable by double-
clicking it or running from the command prompt. You’ll need to make use of the utility
i
nstallutil.exe
,
which is part of the .NET framework 2.0.
So, what is this
installutil.exe? This tool ships with the .NET framework to perform
the tasks of installing and uninstalling server resources. This tool automatically finds all the
installer components from a given assembly and executes them. Recall that we added

ProjectInstaller in our project (see Figure 8-3)? This information will be used later on by
this tool to add or remove our service application. You can get more information on this
utility here:
/>I assume that the service file
RSWindowsService.exe is inside the folder C:\myservice.
I’m using this short folder name to keep it simple; please replace it with the name of the folder
containing the file on your machine when you try this example. Use the following steps to
install the service and check the status:
1. Click Start

Run

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

c:\myservice\RSWindowsService101.exe
2. Check if the service is installed correctly by clicking Start

Control Panel

Adminis-
trative Tools

Services.
3. Your service should be in the Service dialog box with name RS Windows Service for
Reports, and your screen should look similar to the one shown in Figure 8-7.
Figure 8-7. Newly created service inside the service control panel
Uninstalling a Windows Service Application
It is important to know how to uninstall a service, in case you need to uninstall the existing
service to install a new version. It is common for a developer to develop several builds and
several unit tests for each build; in that case, the developer needs to install the new build and

uninstall the previous one each time a new service is registered.
CHAPTER 8

REPORTING WITH A WINDOWS SERVICE292
8547ch08final.qxd 8/30/07 3:48 PM Page 292
Use the following steps to uninstall the service and check the status:
1. Make sure to stop the Windows service: click Start

Control Panel

Administrative
Tools

Services, select the service name, and click the stop button. Close the Windows
Service dialog box once the service is stopped.
2. Click Start

Run

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /u

c:\myservice\RSWindowsService101.exe

Note
We use
InstallUtil.exe
to both install and uninstall Windows services—you need to use the
switch
/u
before the service name to uninstall.

Creating the New Complaints Report
Assume that you’re working for Home Decorations, Incorporated as a developer, and you have
the task of developing a report that must run as a Windows service every ten minutes. The
report should list new complaints and e-mail them to the customer complaints escalation
administrator. It should group data by complaint level and source of the complaint. The report
should meet all the characteristics described in Table 8-2 and its output, in PDF format,
should match Figure 8-8.
Table 8-2. Report Characteristics
Characteristics Value
Report title New Complaints Report (Header, aligned center)
Company title Home Decorations Inc. (Header, aligned center)
Logo No
Print date Yes (Header, aligned center)
D
ata source
Complaints
Columns to report ComplaintID, CreateDate, CustomerName, ComplaintLevel,
ComplaintSource, ComplaintType
Page size Letter
P
age or
ientation
Landscape
P
age number
Page: n/n (Header, aligned left)
P
age footer
No
Output format PDF

CHAPTER 8

REPORTING WITH A WINDOWS SERVICE 293
8547ch08final.qxd 8/30/07 3:48 PM Page 293

×