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