PageRenderTime 6ms CodeModel.GetById 2ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/Visual Studio 2008/CSWindowsService/ReadMe.txt

#
Plain Text | 258 lines | 196 code | 62 blank | 0 comment | 0 complexity | b6ad278b988950bc60759f3c18f20865 MD5 | raw file
  1=============================================================================
  2           WINDOWS SERVICE : CSWindowsService Project Overview
  3=============================================================================
  4
  5/////////////////////////////////////////////////////////////////////////////
  6Summary:
  7
  8This code sample demonstrates creating a very basic Windows Service 
  9application in Visual C#. The example Windows Service logs the service start 
 10and stop information to the Application event log, and shows how to run the 
 11main function of the service in a thread pool worker thread. You can easily 
 12extend the Windows Service skeleton to meet your own business requirement.
 13
 14
 15/////////////////////////////////////////////////////////////////////////////
 16Demo:
 17
 18The following steps walk through a demonstration of the Windows Service 
 19sample.
 20
 21Step1. After you successfully build the sample project in Visual Studio 2008, 
 22you will get a service application: CSWindowsService.exe. 
 23
 24Step2. Run Visual Studio 2008 Command Prompt as administrator, navigate to 
 25the output folder of the sample project, and enter the following command to 
 26install the service.
 27
 28  InstallUtil.exe CSWindowsService.exe
 29
 30The service is successfully installed if the process outputs:
 31
 32  Beginning the Install phase of the installation.
 33  ......
 34  Installing service CSWindowsService...
 35  Service CSWindowsService has been successfully installed.
 36  Creating EventLog source CSWindowsService in log Application...
 37  The Install phase completed successfully, and the Commit phase is beginning.
 38  ......
 39  The Commit phase completed successfully.
 40  The transacted install has completed.
 41
 42If you do not see this output, please look for the 
 43CSWindowsService.InstallLog file in the ouput folder, and investigate the 
 44cause of failure.
 45
 46Step3. Open Service Management Console (services.msc). You should be able to 
 47find "CSWindowsService Sample Service" in the service list. 
 48
 49Step4. Right-click the CSWindowsService service in Service Management Console 
 50and select Start to start the service. Open Event Viewer, and navigate to 
 51Windows Logs / Application. You should be able to see two events from 
 52CSWindowsService with event messages: "CSWindowsService in OnStart." and 
 53"Service started successfully.". 
 54
 55Right-click the service in Service Management Console and select Stop to stop 
 56the service. You will see two new events from CSWindowsService in Event 
 57Viewer / Windows Logs / Application with messages: "CSWindowsService in 
 58OnStop" and "Service stopped successfully.".
 59
 60Step5. To uninstall the service, enter the following command in Visual Studio 
 612008 Command Prompt running as administrator.
 62
 63  InstallUtil /u CSWindowsService.exe
 64
 65If the service is successfully stopped and removed, you would see this output:
 66
 67  The uninstall is beginning.
 68  ......
 69  Removing EventLog source CSWindowsService.
 70  Service CSWindowsService is being removed from the system...
 71  Service CSWindowsService was successfully removed from the system.
 72  The uninstall has completed.
 73
 74
 75/////////////////////////////////////////////////////////////////////////////
 76Setup and Removal:
 77
 78--------------------------------------
 79In the Development Environment
 80
 81A. Setup
 82
 83Run the command "Installutil.exe CSWindowsService.exe" in an elevated Visual 
 84Studio 2008 Command Prompt. It installs CSWindowsService.exe as a service to 
 85the local service control manager database.
 86
 87B. Cleanup
 88
 89Run the command "Installutil.exe /u CSWindowsService.exe" in an elevated 
 90Visual Studio 2008 Command Prompt. It stops and removes the CSWindowsService
 91service from the local service control manager database.
 92
 93--------------------------------------
 94In the Deployment Environment
 95
 96A. Setup
 97
 98Install CSWindowsServiceSetup(x86).msi, the output of the 
 99CSWindowsServiceSetup(x86) setup project, on a x86 operating system. If the 
100target platform is x64, install CSWindowsServiceSetup(x64).msi outputted by 
101the CSWindowsServiceSetup(x64) setup project.
102
103B. Removal
104
105Uninstall CSWindowsServiceSetup(x86).msi, the output of the 
106CSWindowsServiceSetup(x86) setup project, on a x86 operating system. If the 
107target platform is x64, uninstall CSWindowsServiceSetup(x64).msi outputted by 
108the CSWindowsServiceSetup(x64) setup project.
109
110
111/////////////////////////////////////////////////////////////////////////////
112Implementation:
113
114A. Creating Windows Service
115http://msdn.microsoft.com/en-us/library/aa983583.aspx
116
117Step1. In Visual Studio 2008, add a new Visual C# / Windows / Windows Service 
118project named CSWindowsService. The project template automatically adds a 
119component class named Service1 that inherits from 
120System.ServiceProcess.ServiceBase.
121
122Step2. Rename the default Service1 to the name "SampleService". Open the 
123service in designer and set the ServiceName property to be CSWindowsService. 
124
125Step3. To add custom event log functionality to your service, drag and drop 
126an event log component from toolbox to the design view, and set its Log 
127property to be Application, and its Source to be CSWindowsService. The event 
128log component will be used to log some messages to the Application log.
129
130Step4. To define what occurs when the service starts and stops, in the Code 
131Editor, locate the OnStart and OnStop methods that were automatically 
132overridden when you created the project, and write code to determine what 
133occurs when the service starts running. In this example, we log the service 
134start and stop information to the Application log, and show how to run the 
135main function of the service in a thread pool worker thread.
136
137SampleService.OnStart, which is executed when the service starts, calls 
138EventLog.WriteEntry to log the service-start information. And it calls 
139ThreadPool.QueueUserWorkItem to queue the main service function 
140(SampleService.ServiceWorkerThread) for execution in a worker thread.
141
142NOTE: A service application is designed to be long running. Therefore, it 
143usually polls or monitors something in the system. The monitoring is set up 
144in the OnStart method. However, OnStart does not actually do the monitoring. 
145The OnStart method must return to the operating system after the service's 
146operation has begun. It must not loop forever or block. To set up a simple 
147monitoring mechanism, one general solution is to create a timer in OnStart. 
148The timer would then raise events in your code periodically, at which time 
149your service could do its monitoring. The other solution is to spawn a new 
150thread to perform the main service functions, which is demonstrated in this 
151code sample.
152
153    protected override void OnStart(string[] args)
154    {
155        // Log a service start message to the Application log.
156        this.eventLog1.WriteEntry("CSWindowsService in OnStart.");
157
158        // Queue the main service function for execution in a worker thread.
159        ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerThread));
160    }
161
162SampleService.OnStop, which is executed when the service stops, calls 
163EventLog.WriteEntry to log the service-stop information. Next, it sets the 
164member varaible 'stopping' as true to indicate that the service is stopping 
165and waits for the finish of the main service function that is signaled by the 
166'stoppedEvent' event object.
167
168    protected override void OnStop()
169    {
170        // Log a service stop message to the Application log.
171        this.eventLog1.WriteEntry("CSWindowsService in OnStop.");
172
173        // Indicate that the service is stopping and wait for the finish 
174        // of the main service function (ServiceWorkerThread).
175        this.stopping = true;
176        this.stoppedEvent.WaitOne();
177    }
178
179SampleService.ServiceWorkerThread runs in a thread pool worker thread. It 
180performs the main function of the service such as the communication with 
181client applications through a named pipe. In order that the main function 
182finishes gracefully when the service is about to stop, it should periodically 
183check the 'stopping' varaible. When the function detects that the service is 
184stopping, it cleans up the work and signal the 'stoppedEvent' event object.
185
186    private void ServiceWorkerThread(object state)
187    {
188        // Periodically check if the service is stopping.
189        while (!this.stopping)
190        {
191            // Perform main service function here...
192
193            Thread.Sleep(2000);  // Simulate some lengthy operations.
194        }
195
196        // Signal the stopped event.
197        this.stoppedEvent.Set();
198    }
199
200B. Adding Installer to the service
201http://msdn.microsoft.com/en-us/library/aa984263.aspx
202
203Step1. Open SampleService.cs in Designer, and click the background of the 
204designer to select the service itself, instead of any of its contents. With 
205the designer in focus, right-click, and then click Add Installer. By default, 
206a component class that contains two installers is added to your project. The 
207component is named ProjectInstaller, and the installers it contains are the 
208installer for your service and the installer for the service's associated 
209process. 
210
211Step2. In Design view for ProjectInstaller, click serviceInstaller1. In the 
212Properties window, set the ServiceName property to CSWindowsService. Set the 
213DisplayName property to CSWindowsService Sample Service. In the designer, 
214click serviceProcessInstaller1. Set the Account property to LocalService. 
215This will cause the service to be installed and to run on a local service 
216account. 
217
218Security Note: In this code sample, the service is configured to run as 
219LocalService, instead of LocalSystem. The LocalSystem account has broad 
220permissions. Use the LocalSystem account with caution, because it might 
221increase your risk of attacks from malicious software. For tasks that do 
222not need broad permissions, consider using the LocalService account, which 
223acts as a non-privileged user on the local computer and presents anonymous 
224credentials to any remote server.
225
226C. Creating a setup project for the service to facilitate the deployment
227
228Step1. Add a new Other Project Types / Setup and Deployment Projects / Setup 
229Project named CSWindowsServiceSetup.
230
231Step2. To add CSWindowsService.exe to the setup project, right-click 
232CSWindowsServiceSetup, point to Add, and then click Project Output. Select 
233CSWindowsService in the Project box and choose Primary Output from the list. 
234A project item for the primary output of CSWindowsService is added to the 
235setup project. 
236
237Step3. By default, the target platform of the setup project is x86. If you 
238want to build a setup that targets the x64 platform, click the setup project, 
239and choose "x64" as the TargetPlatform in the Properties dialog. 
240
241Step4. Now add a custom action to install the CSWindowsService.exe file. 
242Right-click the setup project in Solution Explorer, point to View, and then 
243click Custom Actions. In the Custom Actions editor, right-click the Custom 
244Actions node and click Add Custom Action. Double-click the Application Folder 
245in the list to open it, select Primary Output from CSWindowsService (Active), 
246and click OK. The primary output is added to all four nodes of the custom 
247actions — Install, Commit, Rollback, and Uninstall. In Solution Explorer, 
248right-click the CSWindowsServiceSetup project and click Build.
249
250
251/////////////////////////////////////////////////////////////////////////////
252References:
253
254MSDN: Windows Service Applications
255http://msdn.microsoft.com/en-us/library/y817hyb6.aspx
256
257
258/////////////////////////////////////////////////////////////////////////////