1. Trang chủ
  2. » Công Nghệ Thông Tin

Reporting with a Windows Service

24 379 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Reporting with a Windows Service
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài luận
Năm xuất bản 2007
Thành phố City Name
Định dạng
Số trang 24
Dung lượng 786,51 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

A Windows service application is versatile—it has the ability to start, stop, and pauseaccording to user demand.. A Windows service application runs in the background as long as the oper

Trang 1

Reporting with a

Windows Service

In 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 pauseaccording 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 thereal-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 toproduce 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 Ifinstalled on a server, a single instance can service many different report delivery destinations

based on settings provided to the application

285

C H A P T E R 8

Trang 2

Creating a Windows Service Project

Please open Visual Studio, and use the following steps to create a Windows service applicationproject; 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 maychoose 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.

Trang 3

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 Addingthe 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 twoprocesses 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 servicewill run, that is, which account to use By default, the choice is User, but you can select any-

thing from the available choices, shown in Figure 8-4, according to the demands of your

business case

Trang 4

Figure 8-3.Adding an installer to the project

Figure 8-4.Properties of serviceProcessInstaller

Now, let’s look at serviceInstaller1 Two important properties of serviceInstallerworth mentioning are DisplayName , which appears in the Windows service control to helpidentify 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 matic Setting it to Automatic guarantees that the service will run every time Windows runs.Figure 8-5 shows the available properties

Trang 5

Auto-■ Note You can set the Accountproperty 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

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

Trang 6

sources, such as MS Access or SQL Server, can also provide data as input to the service.Usually, a service produces logs for health or progress checks.

The Service class is inherited from the ServiceBase class, which provides the base forthe 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 theservice is started Immediately after this, the OnStart method is called In simple words, allthe functions to handle the service are encapsulated within the ServiceBase class, leavingdevelopers to focus on the function of the service application, not how to coordinate theservice with the OS You can find out more at this MSDN link:

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

}}}

Trang 7

The default code produced for the project installer should look as follows:

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 askeleton 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 Youcan 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 tosee 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

Trang 8

Installing the Windows Service Application

As I mentioned to you already, we cannot run a Windows service executable by clicking it or running from the command prompt You’ll need to make use of the utilityinstallutil.exe, which is part of the NET framework 2.0

double-So, what is this installutil.exe? This tool ships with the NET framework to performthe tasks of installing and uninstalling server resources This tool automatically finds all theinstaller components from a given assembly and executes them Recall that we addedProjectInstaller in our project (see Figure 8-3)? This information will be used later on bythis tool to add or remove our service application You can get more information on thisutility here: http://msdn2.microsoft.com/en-us/library/50614e95(vs.71).aspx

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 foldercontaining the file on your machine when you try this example Use the following steps toinstall 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 ➤trative Tools ➤Services

Adminis-3. Your service should be in the Service dialog box with name RS Windows Service forReports, 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 existingservice to install a new version It is common for a developer to develop several builds andseveral unit tests for each build; in that case, the developer needs to install the new build anduninstall the previous one each time a new service is registered

Trang 9

Use the following steps to uninstall the service and check the status:

1. Make sure to stop the Windows service: click Start ➤Control Panel ➤AdministrativeTools ➤Services, select the service name, and click the stop button Close the WindowsService 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.exeto both install and uninstall Windows services—you need to use the

switch /ubefore 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 reportshould 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)

Print date Yes (Header, aligned center)

Columns to report ComplaintID, CreateDate, CustomerName, ComplaintLevel,

ComplaintSource, ComplaintType

Page orientation Landscape

Page number Page: n/n (Header, aligned left)

Trang 10

Figure 8-8.The New Complaints report

Business Case

Keeping existing customers happy before finding new ones is a common successful businessstrategy Usually, transactions between customers and a company are good However, attimes, an unhappy customer may complain It is important for businesses to take complaintsseriously and provide resolutions as soon as possible

When a complaint arises, its severity decides the urgency of action needed A complaintthat a product is defective when it arrives is more severe than a missing sales invoice Busi-nesses must track all logged complaints, and this New Complaints report will just do that Thisreport will be automatically generated and make sure that administrators get proper notifi-cations for swift complaint resolution

A complaint can be received through any channel: A customer can log it online or acustomer service representative can create one Automating the extraction of all the new com-plaints helps administrators prioritize serious complaints Since the output is in PDF format,the information can be easily shared and delivered as an e-mail attachment

Getting the Windows Service Ready

Now it’s your turn to practice getting a Windows service client ready You may make use of thesolution RSWindowsService101 as a template for this project or create the client from scratch

It is good idea to create the new application from scratch; you can always refer to the ous solution if you get stuck

Trang 11

previ-Use the following steps to create a Windows service project:

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 Complaint You may choose a ferent location for storing the application files according to your preference

dif-5. Let’s add the Installer to the project by right-clicking the open area inside the servicedesigner and selecting Add Installer (see Figure 8-3) Please make sure to useLocalSystem as the Account and Automatic as the StartType

6. Click the OK button to finish the process VS will create a new Windows service projectwith the name Complaint

Please add a new dataset to the project, and name it dsComplaint Before continuing,please make sure your solution looks similar to Figure 8-9

Figure 8-9.The Windows service, Solution Explorer view

Trang 12

Step 1: Creating a Data Table

We’ve already added the dataset to the project; now, its time to add the data table to it The datatable should have six columns, which are identified in the report characteristics in Table 8-2.Use the following steps to add the data table inside the dataset:

1. You can go to the dataset designer in either of the usual two ways: double-clickdsComplaint inside Solution Explorer or right-click the dsComplaint node and selectView Designer

2. Add the data table by right-clicking the design surface and selecting Add ➤DataTable

3. Click the header of the newly created data table, and name it dtComplaintList Startadding columns to dtComplaintList by right-clicking the data table and selectingAdd➤Column

4. Add the following columns into the data table; your data table should look like the oneshown in Figure 8-10:

Figure 8-10.The final look of the dtComplaintList data table

Note If you face any issues with adding the dataset or data table, please refer to Chapter 3 for a through

walk-Step 2: Designing the Report Layout

All right, we have our dataset in place with its data table and all the necessary columns We’reall set to start designing the report layout Add the report by selecting the project in SolutionExplorer, right-clicking it, and selecting Add ➤New Item Select Report from the Add New

Ngày đăng: 05/10/2013, 08:48

TỪ KHÓA LIÊN QUAN

w