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

Reporting with a Windows Service

24 378 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

Định dạng
Số trang 24
Dung lượng 786,51 KB

Nội dung

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: http://msdn.microsoft.com/library/default.asp?url=/library/ ➥ 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: http://msdn2.microsoft.com/en-us/library/ ➥ 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: 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 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 Figure 8-8. The New Complaints report Business Case Keeping existing customers happy before finding new ones is a common successful business strategy. Usually, transactions between customers and a company are good. However, at times, an unhappy customer may complain. It is important for businesses to take complaints seriously and provide resolutions as soon as possible. When a complaint arises, its severity decides the urgency of action needed. A complaint that 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. This report 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 a customer 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 the solution RSWindowsService101 as a template for this pr oject or cr eate the client from scratch. I t is good idea to cr eate the new application fr om scr atch; y ou can always r efer to the previ- ous solution if you get stuck. CHAPTER 8 ■ REPORTING WITH A WINDOWS SERVICE294 8547ch08final.qxd 8/30/07 3:48 PM Page 294 [...]... Property Value textbox1 Value Complaint ID textbox2 Value Create Date textbox3 Value Customer Name textbox10 Value Complaint Type ComplaintID Value =Fields!ComplaintID.Value CreateDate Value =Fields!CreateDate.Value CreateDate Format d CreateDate TextAlign Left CustomerName Value =Fields!CustomerName.Value ComplaintType Value =Fields!ComplaintType.Value table1 DataSetName dsComplaint_dtComplaintList table1.TableRow1... reports for all newly logged complaints—providing your complaint administrators an easy way to automate the reporting of sensitive data without any manual intervention Summary In this chapter, you learned how to use a Windows service as a client to generate a report in PDF format You also learned how to make use of a Windows service to schedule automated report delivery based on a desired time interval In... ComplaintLevel (System.String) • ComplaintSource (System.Int32) • ComplaintType (System.String) Figure 8-10 The final look of the dtComplaintList data table s Note If you face any issues with adding the dataset or data table, please refer to Chapter 3 for a walkthrough Step 2: Designing the Report Layout All right, we have our dataset in place with its data table and all the necessary columns We’re all... surface and selecting Add ® DataTable 3 Click the header of the newly created data table, and name it dtComplaintList Start adding columns to dtComplaintList by right-clicking the data table and selecting Add ® Column 4 Add the following columns into the data table; your data table should look like the one shown in Figure 8-10: • ComplaintID (System.String) • CreateDate (System.DateTime) • CustomerName... service project with 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 295 8547ch08final.qxd 296 8/30/07 3:48 PM Page 296 CHAPTER 8 s REPORTING WITH A WINDOWS SERVICE Step 1: Creating a Data Table We’ve already added the dataset to the project;... minutes has elapsed So according to that business rule, the service must scan the database to find out fresh complaints with a severity level of three All such complaints must go as a report to complaint administrators by e-mail for prompt and swift resolution 8547ch08final.qxd 8/30/07 3:48 PM Page 301 CHAPTER 8 s REPORTING WITH A WINDOWS SERVICE Adding the timer control to the service is simple: drag Toolbox... set Page Width to 11in and Page Height to 8.5in for a letter-size, landscape report Designing a Page Header Now that we have the header and body sections added to our report, let’s work on the header first, as we always do Please drag and drop the following report items inside the header section: 297 8547ch08final.qxd 298 8/30/07 3:48 PM Page 298 CHAPTER 8 s REPORTING WITH A WINDOWS SERVICEA text... accessing general properties toolbox Select each text box, and specify the values according to Table 8-3 Table 8-3 Report Item Properties for Header Report Item Property Value Name txtReportTitle Value New Complaints Report Name txtCompanyTitle Value Home Decorations Inc Name txtPrintDate Value ="Print Date: " & Today Name txtPageNumber Value ="Page: " & Globals!PageNumber & "/" & Globals!TotalPages textbox1... System.Net.Mail namespace You need to have access to an SMTP mail server to check this part of the function Since a Windows service doesn’t have any interactive user interface, I’m using the StreamWriter to write the logs in a text file 8547ch08final.qxd 8/30/07 3:48 PM Page 307 CHAPTER 8 s REPORTING WITH A WINDOWS SERVICE Building the Project Since this project is a Windows service, we cannot launch it... time to add the data table to it The data table 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-click dsComplaint inside Solution Explorer or right-click the dsComplaint node and select View Designer 2 Add the data table . 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. 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

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

TỪ KHÓA LIÊN QUAN

w