powered by simpleCommunicator - 2.0.55     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Управление WinService NT: Delete, DisplayName, Description, StartMode
20 сообщений из 20, страница 1 из 1
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38835876
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Проверка существования сервиса, как запустить, остановить, статус (запущен, остановлен, запускается) -это я разобрался.
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
  Public Function IsServiceExists(ByVal ServiceName As String) As Boolean
    For Each scTemp In ServiceController.GetServices()
      If scTemp.ServiceName = ServiceName Then Return True
    Next
    Return False
  End Function

  Public Function GetServiceStatus(ByVal ServiceName As String) As ServiceControllerStatus
    Return New ServiceController(ServiceName).Status
  End Function

  Public Function StartNTService(ByVal ServiceName As String) As Boolean
    Dim sc As New ServiceController(ServiceName)
    Try
      sc.Start()
      Return True
    Catch
      Return False
    End Try
  End Function

  Public Function StopNTService(ByVal ServiceName As String) As Boolean
    Dim sc As New ServiceController(ServiceName)
    Try
      sc.Stop()
      Return True
    Catch
      Return False
    End Try
  End Function



Нерешенные вопросы:
1) Задать DisplayName
2) Задать Description
3) Задать StartUp Mode (start= auto; start= demand...)
4) Узнать текущий StartUp Mode (start= auto; start= demand...)
5) Удалить сервис
P.S. Задача установки сервиса не стоит - т.к. у меня оболочка чужая, то устанавливаю сторонней утилитой через Shell
Интересуют вспомогательные указанные задачи.

Известные мне методы:
1) командная утилита sc через Shell
Например:
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
 Public Sub SetServiceDisplayName(ByVal ServiceName As String, ByVal DisplayName As String)
    Shell("sc config " & ServiceName & " displayname= " & Chr(34) & DisplayName & Chr(34), AppWinStyle.Hide) 'vbNormalFocus
  End Sub

  Public Sub SetServiceDescription(ByVal ServiceName As String, ByVal Description As String)
    Shell("sc description " & ServiceName & " " & Chr(34) & Description & Chr(34), AppWinStyle.Hide) 'vbNormalFocus
  End Sub


2) Win32 API Service Functions
Громоздко, но что уже написано можно и перекатать если лучше вариантов не найдется.

Меня интересуют ответы на мои 5 вопросов (вроде ничего не упустил) как это делается на .Net.
Подозреваю что ServiceInstaller - класс , но что-то пока не врубился, как менять-запрашивать указанные свойства и как удалить сервис (имя сервиса задано и известно). Задача установки сервиса с нуля не стоит.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38835969
carrotik
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77,

... так а в реестре Windows прочитать/записать?
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38835989
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
carrotik,

Я спрашиваю про чисто .Net методы (типа тех 4-х ф-ций что я привел вначале).
Методами sc.exe и Win32-API я владею. Они уже однозначно гораздо лучше чем копание в реестре.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836050
carrotik
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77carrotik,

Я спрашиваю про чисто .Net методы (типа тех 4-х ф-ций что я привел вначале).
Методами sc.exe и Win32-API я владею. Они уже однозначно гораздо лучше чем копание в реестре.

..вероятно, их нет ... это вообще скриптовая задача, зачем ее помещать во фреймворк?
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836081
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
carrotikвероятно, их нет ...
Да ладно.
4-е ф-ции я написал, с чего топик и начал

Вот это что тогда?
ServiceInstaller.Uninstall - метод
Удаляет службу, удаляя сведения о ней из реестра.
Только я пока не понимаю как сюда например подцепиться, зная имя службы.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836237
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
carrotikскриптовая задача
Не такая уж скриптовая.
Дмитрий774) Узнать текущий StartUp Mode (start= auto; start= demand...)
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
  Private Const ERROR_INSUFFICIENT_BUFFER = 122&

  'Access Rights for the Service Control Manager
  Public Const SC_MANAGER_CONNECT = &H1&

  'Access Rights for a Service
  Public Const SERVICE_QUERY_CONFIG = &H1&

  'Service Structures
  <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
  Public Structure QUERY_SERVICE_CONFIG
    Dim dwServiceType As Integer
    Dim dwStartType As Integer
    Dim dwErrorControl As Integer
    Dim lpBinaryPathName As IntPtr
    Dim lpLoadOrderGroup As IntPtr
    Dim dwTagId As Integer
    Dim lpDependencies As IntPtr
    Dim lpServiceStartName As IntPtr
    Dim lpDisplayName As IntPtr
  End Structure

  'Service Functions
  Private Declare Function CloseServiceHandle _
   Lib "advapi32" (ByVal hSCObject As IntPtr) As Boolean
  Public Declare Unicode Function OpenSCManager _
   Lib "advapi32" Alias "OpenSCManagerW" _
   (ByVal lpMachineName As String, ByVal lpDatabaseName As String, _
   ByVal dwDesiredAccess As Integer) As IntPtr
  Public Declare Unicode Function OpenService _
   Lib "advapi32" Alias "OpenServiceW" _
   (ByVal hSCManager As IntPtr, ByVal lpServiceName As String, _
   ByVal dwDesiredAccess As Integer) As IntPtr
  Public Declare Unicode Function QueryServiceConfig Lib "advapi32" _
   Alias "QueryServiceConfigW" (ByVal hService As IntPtr, _
   ByRef lpServiceConfig As QUERY_SERVICE_CONFIG, _
   ByVal cbBufSize As Integer, ByRef pcbBytesNeeded As Integer) As Boolean


  Public Function GetServiceStartType(ByVal ServiceName As String) As Integer
    ' It returns zero value on error
    'возвращает тип автозапуска: 2-SERVICE_AUTO_START;3-SERVICE_DEMAND_START;4-SERVICE_DISABLED
    Dim hService As Long
    Dim r As Integer, SCfg() As QUERY_SERVICE_CONFIG, r1 As Integer

    Dim hSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_CONNECT)
    If hSCManager <> IntPtr.Zero Then
      hService = OpenService(hSCManager, ServiceName, SERVICE_QUERY_CONFIG)
      If hService <> IntPtr.Zero Then
        ReDim SCfg(0 To 0)
        If QueryServiceConfig(hService, SCfg(0), 0, r) = False Then
          If Err.LastDllError = ERROR_INSUFFICIENT_BUFFER Then
            r1 = r \ Marshal.SizeOf(GetType(QUERY_SERVICE_CONFIG)) + 1
            ReDim SCfg(0 To r1 - 1)
            If QueryServiceConfig(hService, SCfg(0), r1 * Marshal.SizeOf(GetType(QUERY_SERVICE_CONFIG)), r) Then
              GetServiceStartType = SCfg(0).dwStartType
            Else
              GetServiceStartType = 0
            End If
          Else
            GetServiceStartType = 0
          End If
        End If
        CloseServiceHandle(hService)
      Else
        GetServiceStartType = 0
      End If
      CloseServiceHandle(hSCManager)
    Else
      GetServiceStartType = 0
    End If
  End Function
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836272
carrotik
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77,

.. это проще, чем обратиться к реестру? (тем более, что эти обертки все равно это же и делают).. ну ... не знаю ...
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836319
petalvik
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77как это делается на .Net
Каждый раз, как я заглядываю в темы Дмитрия, я вижу хэндлы, функции винапи, инвок и тому подобное. Я с изумлением проверяю форум - всё верно: .NET Framework, после чего оху... охладеваю и закрываю тему.

Ведь неоднократно уже говорилось Диме, что стоит поглубже освоить дотнет, не тянуть в него старые привычки из VB и WinAPI. Большинство вопросов решаются управляемыми средствами дотнета (но не все, да).

Дмитрий77Нерешенные вопросы:
1) Задать DisplayName
2) Задать Description
3) Задать StartUp Mode (start= auto; start= demand...)
4) Узнать текущий StartUp Mode (start= auto; start= demand...)
5) Удалить сервис
Вот ты же нашёл в msdn класс ServiceInstaller, так почему бы не просмотреть всё пространство имён System.ServiceProcess : все классы, структуры, перечисления.
Там есть класс ServiceController , у которого есть свойства DisplayName и Status.
А у класса ServiceInstaller есть свойство Description и StartType.

И не надо никаких шеллов и прочего. Лишь уделить чуточку больше времени на освоение дотнета.


ЗЫ: А ещё с сервисами можно работать с помощью WMI. Это для любителей советских консулов.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836412
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
petalvik- вижу хэндлы, функции винапи, инвок и тому подобное...после чего оху... охладеваю и закрываю
типа слабо?
знаешь, мне тоже простоты хочется.

petalvik- всё верно: .NET Framework.
Верно-верно.

petalvikДмитрий77Нерешенные вопросы:
1) Задать DisplayName
2) Задать Description
3) Задать StartUp Mode (start= auto; start= demand...)
4) Узнать текущий StartUp Mode (start= auto; start= demand...)
5) Удалить сервис
Вот ты же нашёл в msdn класс ServiceInstaller, так почему бы не просмотреть всё пространство имён System.ServiceProcess : все классы, структуры, перечисления.
Там есть класс ServiceController , у которого есть свойства DisplayName и Status.
А у класса ServiceInstaller есть свойство Description и StartType.
Отлично, ты тоже уже заметил что я именно об этом и спрашиваю.
Хорошо, я дурак и тупой, если так удобнее и быстрее будет ответ.
Коды дай. Пожалуйста. Если конечно знаешь.
Вот только живых примеров (ответы на мои пункты) я что-то не нашел. Ни в MSDN ни в гугле. Вот и ткни меня.

Кстати DisplayName через ServiceController поменять у меня не получилось (под админом естественно).
А что касается ServiceInstaller, то мне во первых не ясно как к нему подвязаться зная имя службы.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836439
Фотография Изопропил
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77знаешь, мне тоже простоты хочется.
я уже предлагал писать касающееся WinAPI на С
без траха стоя на голове с лыжами в гамаке
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836475
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Изопропил,

под простотой я здесь имел ввиду как раз чисто Net коды, а не API.
Через ServiceInstaller и System.ServiceProcess и ServiceController. (то что я хочу от вас услышать)
Только где они? Или одни рассуждения, как всегда.
Т.е. я привел через API - некоторым тут х.*е.*во становится (не Вам) -потому как они ето извините не умеют.
А прошу привести свои чудесные нетовские -сразу тишина.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836521
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
petalvikВот ты же нашёл в msdn класс ServiceInstaller,
А у класса ServiceInstaller есть свойство Description и StartType.
И не надо никаких шеллов и прочего. Лишь уделить чуточку больше времени на освоение дотнета.
Уделил. А это вообще не то, зачем пыль в глаза пускать.
ServiceInstaller -это когда надо чтоб сам exe себя умел устанавливать/удалять/конфигурировать в качестве сервиса.
А я спрашиваю про уже установленный сервис.
Про произвольный (скажем так чтоб яснее), который отображается в "Службы" и определяется его именем.
Который надо/можно немножко подконфигурировать и что-то про него узнать (автозапуск да/нет).
ServiceController -да, но возможности ограничены. Только управление (старт/стоп/статус/существует ли), но не конфигурирование. Разницу чувствуете?
carrotik..вероятно, их нет ...
Вероятно это правильный ответ. Увы.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836558
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Под спойлером. Если вдруг кому понадобится. Не жалко.

Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
Imports System.ServiceProcess
Imports System.Runtime.InteropServices

Module Module1
  Public Const PROCESS_QUERY_INFORMATION = &H400
  Public Const STILL_ACTIVE = &H103

  Public Declare Function OpenProcess Lib "kernel32" _
   (ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Boolean, _
   ByVal dwProcessID As Integer) As IntPtr
  Public Declare Function GetExitCodeProcess Lib "kernel32" _
   (ByVal hProcess As IntPtr, ByRef lpExitCode As Integer) As Boolean

  Private Const ERROR_INSUFFICIENT_BUFFER = 122&

  Private Const STANDARD_RIGHTS_REQUIRED = &HF0000

  'Access Rights for the Service Control Manager
  Public Const SC_MANAGER_CONNECT = &H1
  Public Const SC_MANAGER_CREATE_SERVICE = &H2
  Public Const SC_MANAGER_ENUMERATE_SERVICE = &H4
  Public Const SC_MANAGER_LOCK = &H8
  Public Const SC_MANAGER_QUERY_LOCK_STATUS = &H10
  Public Const SC_MANAGER_MODIFY_BOOT_CONFIG = &H20
  Public Const SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _
                                        SC_MANAGER_CONNECT Or _
                                        SC_MANAGER_CREATE_SERVICE Or _
                                        SC_MANAGER_ENUMERATE_SERVICE _
                                        Or SC_MANAGER_LOCK _
                                        Or SC_MANAGER_QUERY_LOCK_STATUS _
                                        Or SC_MANAGER_MODIFY_BOOT_CONFIG)

  'Access Rights for a Service
  Public Const SERVICE_QUERY_CONFIG = &H1&
  Public Const SERVICE_CHANGE_CONFIG = &H2&
  Public Const SERVICE_QUERY_STATUS = &H4&
  Public Const SERVICE_ENUMERATE_DEPENDENTS = &H8&
  Public Const SERVICE_START = &H10&
  Public Const SERVICE_STOP = &H20&
  Public Const SERVICE_PAUSE_CONTINUE = &H40&
  Public Const SERVICE_INTERROGATE = &H80&
  Public Const SERVICE_USER_DEFINED_CONTROL = &H100&
  Public Const SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _
                                         SERVICE_QUERY_CONFIG Or _
                                         SERVICE_CHANGE_CONFIG Or _
                                         SERVICE_QUERY_STATUS Or _
                                         SERVICE_ENUMERATE_DEPENDENTS Or _
                                         SERVICE_START Or _
                                         SERVICE_STOP Or _
                                         SERVICE_PAUSE_CONTINUE Or _
                                         SERVICE_INTERROGATE Or _
                                         SERVICE_USER_DEFINED_CONTROL)

  <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
  Public Structure SERVICE_DESCRIPTION
    Dim lpDescription As String
  End Structure

  <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
  Public Structure QUERY_SERVICE_CONFIG
    Dim dwServiceType As Integer
    Dim dwStartType As Integer
    Dim dwErrorControl As Integer
    Dim lpBinaryPathName As String '<MarshalAs(UnmanagedType.LPWStr)> 
    Dim lpLoadOrderGroup As String
    Dim dwTagId As Integer
    Dim lpDependencies As String
    Dim lpServiceStartName As String
    Dim lpDisplayName As String
  End Structure

  <StructLayout(LayoutKind.Sequential)>
  Public Structure SERVICE_STATUS
    Dim dwServiceType As Integer
    Dim dwCurrentState As Integer
    Dim dwControlsAccepted As Integer
    Dim dwWin32ExitCode As Integer
    Dim dwServiceSpecificExitCode As Integer
    Dim dwCheckPoint As Integer
    Dim dwWaitHint As Integer
  End Structure

  'Service Functions
  Public Declare Function CloseServiceHandle _
   Lib "advapi32" (ByVal hSCObject As IntPtr) As Boolean

  Public Const SERVICE_NO_CHANGE As Integer = -1

  'The service start options.
  Public Const SERVICE_AUTO_START = 2
  Public Const SERVICE_DEMAND_START = 3

  Public Declare Unicode Function ChangeServiceConfig Lib "advapi32" Alias "ChangeServiceConfigW" _
   (ByVal hService As IntPtr, ByVal dwServiceType As Integer, ByVal dwStartType As Integer, _
   ByVal dwErrorControl As Integer, Optional ByVal lpBinaryPathName As String = vbNullString, _
   Optional ByVal lpLoadOrderGroup As String = vbNullString,
   Optional ByVal lpdwTagId As Integer = 0,
   Optional ByVal lpDependencies As String = vbNullString,
   Optional ByVal lpServiceStartName As String = vbNullString,
   Optional ByVal lpPassword As String = vbNullString,
   Optional ByVal lpDisplayName As String = vbNullString) As Boolean

  'dwInfoLevel - The configuration information to be changed.
  Public Const SERVICE_CONFIG_DESCRIPTION = 1

  Public Declare Unicode Function ChangeServiceConfig2_DESCRIPTION Lib "advapi32" Alias "ChangeServiceConfig2W" _
   (ByVal hService As IntPtr, ByVal dwInfoLevel As Integer, ByRef lpInfo As SERVICE_DESCRIPTION) As Boolean

  'dwControl - one of the following control codes
  Public Const SERVICE_CONTROL_STOP = 1&
  Public Const SERVICE_CONTROL_PAUSE = 2&
  Public Const SERVICE_CONTROL_CONTINUE = 3&
  Public Const SERVICE_CONTROL_INTERROGATE = 4&
  Public Const SERVICE_CONTROL_SHUTDOWN = 5&

  Public Declare Function ControlService Lib "advapi32" _
   (ByVal hService As IntPtr, ByVal dwControl As Integer, _
   ByRef lpServiceStatus As SERVICE_STATUS) As Boolean
  Public Declare Function DeleteService _
   Lib "advapi32" (ByVal hService As IntPtr) As Boolean
  Public Declare Unicode Function OpenSCManager _
   Lib "advapi32" Alias "OpenSCManagerW" _
   (ByVal lpMachineName As String, ByVal lpDatabaseName As String, _
   ByVal dwDesiredAccess As Integer) As IntPtr
  Public Declare Unicode Function OpenService _
   Lib "advapi32" Alias "OpenServiceW" _
   (ByVal hSCManager As IntPtr, ByVal lpServiceName As String, _
   ByVal dwDesiredAccess As Integer) As IntPtr
  Public Declare Unicode Function QueryServiceConfig Lib "advapi32" _
   Alias "QueryServiceConfigW" (ByVal hService As IntPtr, _
   ByVal lpServiceConfig As IntPtr, _
   ByVal cbBufSize As Integer, ByRef pcbBytesNeeded As Integer) As Boolean 'ByRef lpServiceConfig As QUERY_SERVICE_CONFIG

  Public Function IsServiceExists(ByVal ServiceName As String) As Boolean
    'Net
    For Each scTemp In ServiceController.GetServices()
      If scTemp.ServiceName = ServiceName Then Return True
    Next
    Return False
  End Function

  Public Function GetServiceStatus(ByVal ServiceName As String) As ServiceControllerStatus
    'Net
    Return New ServiceController(ServiceName).Status
  End Function

  Public Function StartNTService(ByVal ServiceName As String) As Boolean
    'Net
    Dim sc As New ServiceController(ServiceName)
    Try
      sc.Start()
      Return True
    Catch
      Return False
    End Try
  End Function

  Public Function StopNTService(ByVal ServiceName As String) As Boolean
    'Net
    Dim sc As New ServiceController(ServiceName)
    Try
      sc.Stop()
      Return True
    Catch
      Return False
    End Try
  End Function

  Public Sub SetServiceDisplayName_SC(ByVal ServiceName As String, ByVal DisplayName As String)
    'admin
    ShellAndContinueNet("sc config " & ServiceName & " displayname= " & Chr(34) & DisplayName & Chr(34), AppWinStyle.Hide) 'vbNormalFocus
  End Sub

  Public Sub SetServiceDescription_SC(ByVal ServiceName As String, ByVal Description As String)
    'admin
    ShellAndContinueNet("sc description " & ServiceName & " " & Chr(34) & Description & Chr(34), AppWinStyle.Hide) 'vbNormalFocus
  End Sub

  Public Sub SetServiceServiceAutoStart_SC(ByVal ServiceName As String, ByVal bAutoStart As Boolean)
    'admin
    If bAutoStart Then
      ShellAndContinueNet("sc config " & ServiceName & " start= auto", AppWinStyle.Hide) 'vbNormalFocus
    Else
      ShellAndContinueNet("sc config " & ServiceName & " start= demand", AppWinStyle.Hide) 'vbNormalFocus
    End If
  End Sub

  Public Function GetServiceStartType(ByVal ServiceName As String) As Integer
    ' It returns zero value on error
    'возвращает тип автозапуска: 2-SERVICE_AUTO_START;3-SERVICE_DEMAND_START;4-SERVICE_DISABLED
    Dim hService As IntPtr
    Dim r As Integer, SCfg As QUERY_SERVICE_CONFIG
    Dim pBuffer As IntPtr

    GetServiceStartType = 0
    Dim hSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_CONNECT)
    If hSCManager <> IntPtr.Zero Then
      hService = OpenService(hSCManager, ServiceName, SERVICE_QUERY_CONFIG)
      If hService <> IntPtr.Zero Then
        If QueryServiceConfig(hService, pBuffer, r, r) = False Then
          If Err.LastDllError = ERROR_INSUFFICIENT_BUFFER Then
            pBuffer = Marshal.AllocHGlobal(r)
            If QueryServiceConfig(hService, pBuffer, r, r) Then
              SCfg = Marshal.PtrToStructure(pBuffer, GetType(QUERY_SERVICE_CONFIG))
              GetServiceStartType = SCfg.dwStartType
            End If
          End If
        End If
        CloseServiceHandle(hService)
      End If
      CloseServiceHandle(hSCManager)
    End If
    If Not pBuffer.Equals(0) Then
      Marshal.FreeHGlobal(pBuffer)
    End If
  End Function

  Public Function DeleteNTService(ByVal ServiceName As String) As Integer
    'admin
    ' This function uninstalls service
    ' It returns nonzero value on error
    Dim Status As SERVICE_STATUS

    DeleteNTService = 0
    Dim hSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_CONNECT)
    If hSCManager <> IntPtr.Zero Then
      Dim hService As IntPtr = OpenService(hSCManager, ServiceName, SERVICE_ALL_ACCESS)
      If hService Then
        ' Stop service if it is running
        ControlService(hService, SERVICE_CONTROL_STOP, Status)
        If DeleteService(hService) = 0 Then
          DeleteNTService = Err.LastDllError
        End If
        CloseServiceHandle(hService)
      Else
        DeleteNTService = Err.LastDllError
      End If
      CloseServiceHandle(hSCManager)
    Else
      DeleteNTService = Err.LastDllError
    End If
  End Function

  Public Function SetServiceDisplayName(ByVal ServiceName As String, ByVal DisplayName As String) As Boolean
    'admin
    SetServiceDisplayName = False
    ' Get a handle to the SCM database. 
    Dim schSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
    If schSCManager = IntPtr.Zero Then
      'Debug.Print("OpenSCManager failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      Exit Function
    End If

    ' Get a handle to the service.
    Dim schService As IntPtr = OpenService(schSCManager, ServiceName, SERVICE_CHANGE_CONFIG)
    If schService = IntPtr.Zero Then
      'Debug.Print("OpenService failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      CloseServiceHandle(schSCManager)
      Exit Function
    End If
    ' Change the service Display Name
    If ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, _
     , , , , , , DisplayName) = False Then
      'Debug.Print("ChangeServiceConfig failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
    Else
      'Debug.Print("Service Display Name changed successfully.")
      SetServiceDisplayName = True
    End If

    CloseServiceHandle(schService)
    CloseServiceHandle(schSCManager)
  End Function

  Public Function SetServiceServiceAutoStart(ByVal ServiceName As String, ByVal bAutoStart As Boolean) As Boolean
    'admin
    SetServiceServiceAutoStart = False
    ' Get a handle to the SCM database. 
    Dim schSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
    If schSCManager = IntPtr.Zero Then
      'Debug.Print("OpenSCManager failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      Exit Function
    End If

    ' Get a handle to the service.
    Dim schService As IntPtr = OpenService(schSCManager, ServiceName, SERVICE_CHANGE_CONFIG)
    If schService = IntPtr.Zero Then
      'Debug.Print("OpenService failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      CloseServiceHandle(schSCManager)
      Exit Function
    End If
    ' Change the service AutoStart
    If ChangeServiceConfig(schService, SERVICE_NO_CHANGE, _
     IIf(bAutoStart, SERVICE_AUTO_START, SERVICE_DEMAND_START), SERVICE_NO_CHANGE) = False Then
      'Debug.Print("ChangeServiceConfig failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
    Else
      'Debug.Print("Service AutoStart successfully changed to " & bAutoStart.ToString)
      SetServiceServiceAutoStart = True
    End If

    CloseServiceHandle(schService)
    CloseServiceHandle(schSCManager)
  End Function

  Public Function SetServiceDescription(ByVal ServiceName As String, ByVal Description As String) As Boolean
    'admin
    SetServiceDescription = False
    ' Get a handle to the SCM database. 
    Dim schSCManager As IntPtr = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
    If schSCManager = IntPtr.Zero Then
      'Debug.Print("OpenSCManager failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      Exit Function
    End If

    ' Get a handle to the service.
    Dim schService As IntPtr = OpenService(schSCManager, ServiceName, SERVICE_CHANGE_CONFIG)
    If schService = IntPtr.Zero Then
      'Debug.Print("OpenService failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
      CloseServiceHandle(schSCManager)
      Exit Function
    End If
    ' Change the service Description
    Dim sd As SERVICE_DESCRIPTION
    sd.lpDescription = Description
    If ChangeServiceConfig2_DESCRIPTION(schService, SERVICE_CONFIG_DESCRIPTION, sd) = False Then
      'Debug.Print("ChangeServiceConfig failed: " & RaiseAPIErrorByNumber(Err.LastDllError))
    Else
      'Debug.Print("Service Description changed successfully.")
      SetServiceDescription = True
    End If

    CloseServiceHandle(schService)
    CloseServiceHandle(schSCManager)
  End Function

  Public Function RaiseAPIErrorByNumber(ByVal ErrNum As Integer) As String
    Return ErrNum.ToString & " (" & (New System.ComponentModel.Win32Exception(ErrNum)).Message & ")"
  End Function

  Public Sub ShellAndContinue(ByVal AppToRun As String, ByVal mode As AppWinStyle)

    Dim RetVal As Integer

    'The next line launches AppToRun,
    'captures process ID
    Dim hProcess As IntPtr = OpenProcess(PROCESS_QUERY_INFORMATION, True, Shell(AppToRun, mode))
    Do
      'Get the status of the process
      GetExitCodeProcess(hProcess, RetVal)
      Application.DoEvents()
      'Loop while the process is active
    Loop While RetVal = STILL_ACTIVE

  End Sub

  Public Sub ShellAndContinueNet(ByVal AppToRun As String, ByVal mode As AppWinStyle)
    Dim MyProcess As Process = Process.GetProcessById(Shell(AppToRun, mode))
    Do While Not MyProcess.HasExited
      Application.DoEvents()
    Loop
  End Sub
End Module


Ну предложите лучше, чего трепаться.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836571
JeStone
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дмитрий77Я спрашиваю про чисто .Net методы (типа тех 4-х ф-ций что я привел вначале).

Дмитрий77Ну предложите лучше, чего трепаться.

Дмитрий771) Задать DisplayName
2) Задать Description
3) Задать StartUp Mode (start= auto; start= demand...)
4) Узнать текущий StartUp Mode (start= auto; start= demand...)
5) Удалить сервис

2-й пункт не знаю как через .Net решить, а гуглить лень.
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
    class Program
    {
        static void Main(string[] args)
        {
            Service service = new Service("wuauserv");  // Этот WMI класс генерится автоматом (просто как пример, все можно и без автогенерации этого класса сделать через wmi-запрос)
            string State = service.State;  // Текущее состояние сервиса
            string StartMode = service.StartMode; // StartUpMode
            
            //Модификация параметров сервиса
            SetServiceProperies("wuauserv", "МОЙ!!! Центр обновления Windows", "Automatic");
            service.Delete();   // Удалить сервис
        }

        public static void SetServiceProperies(string serviceName, string displayName, string startMode) 
        { 
            ConnectionOptions oConn = new ConnectionOptions(); 
            oConn.Impersonation = ImpersonationLevel.Impersonate; 
        	 
            ManagementScope oMs = new ManagementScope(@"root\cimv2", oConn); 
            ObjectQuery oQuery = new ObjectQuery("select * from win32_service where name='" + serviceName + "'"); 
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); 
            ManagementObjectCollection oReturnCollection = oSearcher.Get(); 
            foreach (ManagementObject oReturn in oReturnCollection) 
            {
                ManagementBaseObject inParam = oReturn.GetMethodParameters("Change"); 
                inParam["StartMode"] = startMode;
                inParam["DisplayName"] = displayName;
                oReturn.InvokeMethod("Change", inParam, null); 
            } 
        } 
    }


Из минусов такого решения - по-моему WMI не поддерживается на XP, хотя могу ошибаться.
Ну и конечно класс Service я сгенерил просто для примера. Чтобы получить значения параметров достаточно было бы из oReturn запроса их выдрать. Удалить сервис также можно не генеря лишнего кода.
Автосгенереный WMI
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.
467.
468.
469.
470.
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
491.
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508.
509.
510.
511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
522.
523.
524.
525.
526.
527.
528.
529.
530.
531.
532.
533.
534.
535.
536.
537.
538.
539.
540.
541.
542.
543.
544.
545.
546.
547.
548.
549.
550.
551.
552.
553.
554.
555.
556.
557.
558.
559.
560.
561.
562.
563.
564.
565.
566.
567.
568.
569.
570.
571.
572.
573.
574.
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
589.
590.
591.
592.
593.
594.
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
607.
608.
609.
610.
611.
612.
613.
614.
615.
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
634.
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
649.
650.
651.
652.
653.
654.
655.
656.
657.
658.
659.
660.
661.
662.
663.
664.
665.
666.
667.
668.
669.
670.
671.
672.
673.
674.
675.
676.
677.
678.
679.
680.
681.
682.
683.
684.
685.
686.
687.
688.
689.
690.
691.
692.
693.
694.
695.
696.
697.
698.
699.
700.
701.
702.
703.
704.
705.
706.
707.
708.
709.
710.
711.
712.
713.
714.
715.
716.
717.
718.
719.
720.
721.
722.
723.
724.
725.
726.
727.
728.
729.
730.
731.
732.
733.
734.
735.
736.
737.
738.
739.
740.
741.
742.
743.
744.
745.
746.
747.
748.
749.
750.
751.
752.
753.
754.
755.
756.
757.
758.
759.
760.
761.
762.
763.
764.
765.
766.
767.
768.
769.
770.
771.
772.
773.
774.
775.
776.
777.
778.
779.
780.
781.
782.
783.
784.
785.
786.
787.
788.
789.
790.
791.
792.
793.
794.
795.
796.
797.
798.
799.
800.
801.
802.
803.
804.
805.
806.
807.
808.
809.
810.
811.
812.
813.
814.
815.
816.
817.
818.
819.
820.
821.
822.
823.
824.
825.
826.
827.
828.
829.
830.
831.
832.
833.
834.
835.
836.
837.
838.
839.
840.
841.
842.
843.
844.
845.
846.
847.
848.
849.
850.
851.
852.
853.
854.
855.
856.
857.
858.
859.
860.
861.
862.
863.
864.
865.
866.
867.
868.
869.
870.
871.
872.
873.
874.
875.
876.
877.
878.
879.
880.
881.
882.
883.
884.
885.
886.
887.
888.
889.
890.
891.
892.
893.
894.
895.
896.
897.
898.
899.
900.
901.
902.
903.
904.
905.
906.
907.
908.
909.
910.
911.
912.
913.
914.
915.
916.
917.
918.
919.
920.
921.
922.
923.
924.
925.
926.
927.
928.
929.
930.
931.
932.
933.
934.
935.
936.
937.
938.
939.
940.
941.
942.
943.
944.
945.
946.
947.
948.
949.
950.
951.
952.
953.
954.
955.
956.
957.
958.
959.
960.
961.
962.
963.
964.
965.
966.
967.
968.
969.
970.
971.
972.
973.
974.
975.
976.
977.
978.
979.
980.
981.
982.
983.
984.
985.
986.
987.
988.
989.
990.
991.
992.
993.
994.
995.
996.
997.
998.
999.
1000.
1001.
1002.
1003.
1004.
1005.
1006.
1007.
1008.
1009.
1010.
1011.
1012.
1013.
1014.
1015.
1016.
1017.
1018.
1019.
1020.
1021.
1022.
1023.
1024.
1025.
1026.
1027.
1028.
1029.
1030.
1031.
1032.
1033.
1034.
1035.
1036.
1037.
1038.
1039.
1040.
1041.
1042.
1043.
1044.
1045.
1046.
1047.
1048.
1049.
1050.
1051.
1052.
1053.
1054.
1055.
1056.
1057.
1058.
1059.
1060.
1061.
1062.
1063.
1064.
1065.
1066.
1067.
1068.
1069.
1070.
1071.
1072.
1073.
1074.
1075.
1076.
1077.
1078.
1079.
1080.
1081.
1082.
1083.
1084.
1085.
1086.
1087.
1088.
1089.
1090.
1091.
1092.
1093.
1094.
1095.
1096.
1097.
1098.
1099.
1100.
1101.
1102.
1103.
1104.
1105.
1106.
1107.
1108.
1109.
1110.
1111.
1112.
1113.
1114.
1115.
1116.
1117.
1118.
1119.
1120.
1121.
1122.
1123.
1124.
1125.
1126.
1127.
1128.
1129.
1130.
1131.
1132.
1133.
1134.
1135.
1136.
1137.
1138.
1139.
1140.
1141.
1142.
1143.
1144.
1145.
1146.
1147.
1148.
1149.
1150.
1151.
1152.
1153.
1154.
1155.
1156.
1157.
1158.
1159.
1160.
1161.
1162.
1163.
1164.
1165.
1166.
1167.
1168.
1169.
1170.
1171.
1172.
1173.
1174.
1175.
1176.
1177.
1178.
1179.
1180.
1181.
1182.
1183.
1184.
1185.
1186.
1187.
1188.
1189.
1190.
1191.
1192.
1193.
1194.
1195.
1196.
1197.
1198.
1199.
1200.
1201.
1202.
1203.
1204.
1205.
1206.
1207.
1208.
1209.
1210.
1211.
1212.
1213.
1214.
1215.
1216.
1217.
1218.
1219.
1220.
1221.
1222.
1223.
1224.
1225.
1226.
1227.
1228.
1229.
1230.
1231.
1232.
1233.
1234.
1235.
1236.
1237.
1238.
1239.
1240.
1241.
1242.
1243.
1244.
1245.
1246.
1247.
1248.
1249.
1250.
1251.
1252.
1253.
1254.
1255.
1256.
1257.
1258.
1259.
1260.
1261.
1262.
1263.
1264.
1265.
1266.
1267.
1268.
1269.
1270.
1271.
1272.
1273.
1274.
1275.
1276.
1277.
1278.
1279.
1280.
1281.
1282.
1283.
1284.
1285.
1286.
1287.
1288.
1289.
1290.
1291.
1292.
1293.
1294.
1295.
1296.
1297.
1298.
1299.
1300.
1301.
1302.
1303.
1304.
1305.
1306.
1307.
1308.
1309.
1310.
1311.
1312.
1313.
1314.
1315.
1316.
1317.
1318.
1319.
1320.
1321.
1322.
1323.
1324.
1325.
1326.
1327.
1328.
1329.
1330.
1331.
1332.
1333.
1334.
1335.
1336.
1337.
1338.
1339.
1340.
1341.
1342.
1343.
1344.
1345.
1346.
1347.
1348.
1349.
1350.
1351.
1352.
1353.
1354.
1355.
1356.
1357.
1358.
1359.
1360.
1361.
1362.
1363.
1364.
1365.
1366.
1367.
1368.
1369.
1370.
1371.
1372.
1373.
1374.
1375.
1376.
1377.
1378.
1379.
1380.
1381.
1382.
1383.
1384.
1385.
1386.
1387.
1388.
1389.
1390.
1391.
1392.
1393.
1394.
1395.
1396.
1397.
1398.
1399.
1400.
1401.
1402.
1403.
1404.
1405.
1406.
1407.
1408.
1409.
1410.
1411.
1412.
1413.
1414.
1415.
1416.
1417.
1418.
1419.
1420.
1421.
1422.
namespace ConsoleApplication1.ROOT.CIMV2 {
    using System;
    using System.ComponentModel;
    using System.Management;
    using System.Collections;
    using System.Globalization;
    using System.ComponentModel.Design.Serialization;
    using System.Reflection;
    
    
    // Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
    // Functions Is<PropertyName>Null() are used to check if a property is NULL.
    // Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
    // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
    // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa.
    // An Early Bound class generated for the WMI class.Win32_Service
    public class Service : System.ComponentModel.Component {
        
        // Private property to hold the WMI namespace in which the class resides.
        private static string CreatedWmiNamespace = "ROOT\\CIMV2";
        
        // Private property to hold the name of WMI class which created this class.
        private static string CreatedClassName = "Win32_Service";
        
        // Private member variable to hold the ManagementScope which is used by the various methods.
        private static System.Management.ManagementScope statMgmtScope = null;
        
        private ManagementSystemProperties PrivateSystemProperties;
        
        // Underlying lateBound WMI object.
        private System.Management.ManagementObject PrivateLateBoundObject;
        
        // Member variable to store the 'automatic commit' behavior for the class.
        private bool AutoCommitProp;
        
        // Private variable to hold the embedded property representing the instance.
        private System.Management.ManagementBaseObject embeddedObj;
        
        // The current WMI object used
        private System.Management.ManagementBaseObject curObj;
        
        // Flag to indicate if the instance is an embedded object.
        private bool isEmbedded;
        
        // Below are different overloads of constructors to initialize an instance of the class with a WMI object.
        public Service() {
            this.InitializeObject(null, null, null);
        }
        
        public Service(string keyName) {
            this.InitializeObject(null, new System.Management.ManagementPath(Service.ConstructPath(keyName)), null);
        }
        
        public Service(System.Management.ManagementScope mgmtScope, string keyName) {
            this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(Service.ConstructPath(keyName)), null);
        }
        
        public Service(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
            this.InitializeObject(null, path, getOptions);
        }
        
        public Service(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
            this.InitializeObject(mgmtScope, path, null);
        }
        
        public Service(System.Management.ManagementPath path) {
            this.InitializeObject(null, path, null);
        }
        
        public Service(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
            this.InitializeObject(mgmtScope, path, getOptions);
        }
        
        public Service(System.Management.ManagementObject theObject) {
            Initialize();
            if ((CheckIfProperClass(theObject) == true)) {
                PrivateLateBoundObject = theObject;
                PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
                curObj = PrivateLateBoundObject;
            }
            else {
                throw new System.ArgumentException("Class name does not match.");
            }
        }
        
        public Service(System.Management.ManagementBaseObject theObject) {
            Initialize();
            if ((CheckIfProperClass(theObject) == true)) {
                embeddedObj = theObject;
                PrivateSystemProperties = new ManagementSystemProperties(theObject);
                curObj = embeddedObj;
                isEmbedded = true;
            }
            else {
                throw new System.ArgumentException("Class name does not match.");
            }
        }
        
        // Property returns the namespace of the WMI class.
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string OriginatingNamespace {
            get {
                return "ROOT\\CIMV2";
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string ManagementClassName {
            get {
                string strRet = CreatedClassName;
                if ((curObj != null)) {
                    if ((curObj.ClassPath != null)) {
                        strRet = ((string)(curObj["__CLASS"]));
                        if (((strRet == null) 
                                    || (strRet == string.Empty))) {
                            strRet = CreatedClassName;
                        }
                    }
                }
                return strRet;
            }
        }
        
        // Property pointing to an embedded object to get System properties of the WMI object.
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ManagementSystemProperties SystemProperties {
            get {
                return PrivateSystemProperties;
            }
        }
        
        // Property returning the underlying lateBound object.
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public System.Management.ManagementBaseObject LateBoundObject {
            get {
                return curObj;
            }
        }
        
        // ManagementScope of the object.
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public System.Management.ManagementScope Scope {
            get {
                if ((isEmbedded == false)) {
                    return PrivateLateBoundObject.Scope;
                }
                else {
                    return null;
                }
            }
            set {
                if ((isEmbedded == false)) {
                    PrivateLateBoundObject.Scope = value;
                }
            }
        }
        
        // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool AutoCommit {
            get {
                return AutoCommitProp;
            }
            set {
                AutoCommitProp = value;
            }
        }
        
        // The ManagementPath of the underlying WMI object.
        [Browsable(true)]
        public System.Management.ManagementPath Path {
            get {
                if ((isEmbedded == false)) {
                    return PrivateLateBoundObject.Path;
                }
                else {
                    return null;
                }
            }
            set {
                if ((isEmbedded == false)) {
                    if ((CheckIfProperClass(null, value, null) != true)) {
                        throw new System.ArgumentException("Class name does not match.");
                    }
                    PrivateLateBoundObject.Path = value;
                }
            }
        }
        
        // Public static scope property which is used by the various methods.
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static System.Management.ManagementScope StaticScope {
            get {
                return statMgmtScope;
            }
            set {
                statMgmtScope = value;
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsAcceptPauseNull {
            get {
                if ((curObj["AcceptPause"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The AcceptPause property indicates whether the service can be paused.\nValues: TRU" +
            "E or FALSE. A value of TRUE indicates the service can be paused.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public bool AcceptPause {
            get {
                if ((curObj["AcceptPause"] == null)) {
                    return System.Convert.ToBoolean(0);
                }
                return ((bool)(curObj["AcceptPause"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsAcceptStopNull {
            get {
                if ((curObj["AcceptStop"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The AcceptStop property indicates whether the service can be stopped.\nValues: TRU" +
            "E or FALSE. A value of TRUE indicates the service can be stopped.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public bool AcceptStop {
            get {
                if ((curObj["AcceptStop"] == null)) {
                    return System.Convert.ToBoolean(0);
                }
                return ((bool)(curObj["AcceptStop"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The Caption property is a short textual description (one-line string) of the obje" +
            "ct.")]
        public string Caption {
            get {
                return ((string)(curObj["Caption"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsCheckPointNull {
            get {
                if ((curObj["CheckPoint"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The CheckPoint property specifies a value that the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up. The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint CheckPoint {
            get {
                if ((curObj["CheckPoint"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["CheckPoint"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("CreationClassName indicates the name of the class or the subclass used in the cre" +
            "ation of an instance. When used with the other key properties of this class, thi" +
            "s property allows all instances of this class and its subclasses to be uniquely " +
            "identified.")]
        public string CreationClassName {
            get {
                return ((string)(curObj["CreationClassName"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The Description property provides a textual description of the object. ")]
        public string Description {
            get {
                return ((string)(curObj["Description"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsDesktopInteractNull {
            get {
                if ((curObj["DesktopInteract"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The DesktopInteract property indicates whether the service can create or communic" +
            "ate with windows on the desktop.\nValues: TRUE or FALSE. A value of TRUE indicate" +
            "s the service can create or communicate with windows on the desktop.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public bool DesktopInteract {
            get {
                if ((curObj["DesktopInteract"] == null)) {
                    return System.Convert.ToBoolean(0);
                }
                return ((bool)(curObj["DesktopInteract"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The DisplayName property indicates the display name of the service. This string has a maximum length of 256 characters. The name is case-preserved in the Service Control Manager. DisplayName comparisons are always case-insensitive. 
Constraints: Accepts the same value as the Name property.
Example: Atdisk.")]
        public string DisplayName {
            get {
                return ((string)(curObj["DisplayName"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"If this service fails to start during startup, the ErrorControl property specifies the severity of the error. The value indicates the action taken by the startup program if failure occurs. All errors are logged by the computer system. The computer system does not notify the user of ""Ignore"" errors. With ""Normal"" errors the user is notified. With ""Severe"" errors, the system is restarted with the last-known-good configuration. Finally, on""Critical"" errors the system attempts to restart with a good configuration.")]
        public string ErrorControl {
            get {
                return ((string)(curObj["ErrorControl"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsExitCodeNull {
            get {
                if ((curObj["ExitCode"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The ExitCode property specifies a Win32 error code defining any problems encountered in starting or stopping the service. This property is set to ERROR_SERVICE_SPECIFIC_ERROR (1066) when the error is unique to the service represented by this class, and information about the error is available in the ServiceSpecificExitCode member. The service sets this value to NO_ERROR when running, and again upon normal termination.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint ExitCode {
            get {
                if ((curObj["ExitCode"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["ExitCode"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsInstallDateNull {
            get {
                if ((curObj["InstallDate"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The InstallDate property is datetime value indicating when the object was install" +
            "ed. A lack of a value does not indicate that the object is not installed.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public System.DateTime InstallDate {
            get {
                if ((curObj["InstallDate"] != null)) {
                    return ToDateTime(((string)(curObj["InstallDate"])));
                }
                else {
                    return System.DateTime.MinValue;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The Name property uniquely identifies the service and provides an indication of t" +
            "he functionality that is managed. This functionality is described in more detail" +
            " in the object\'s Description property. ")]
        public string Name {
            get {
                return ((string)(curObj["Name"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The PathName property contains the fully qualified path to the service binary fil" +
            "e that implements the service.\nExample: \\SystemRoot\\System32\\drivers\\afd.sys")]
        public string PathName {
            get {
                return ((string)(curObj["PathName"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsProcessIdNull {
            get {
                if ((curObj["ProcessId"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The ProcessId property specifies the process identifier of the service.\nExample: " +
            "324")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint ProcessId {
            get {
                if ((curObj["ProcessId"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["ProcessId"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsServiceSpecificExitCodeNull {
            get {
                if ((curObj["ServiceSpecificExitCode"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The ServiceSpecificExitCode property specifies a service-specific error code for errors that occur while the service is either starting or stopping. The exit codes are defined by the service represented by this class. This value is only set when the ExitCodeproperty value is ERROR_SERVICE_SPECIFIC_ERROR, 1066.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint ServiceSpecificExitCode {
            get {
                if ((curObj["ServiceSpecificExitCode"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["ServiceSpecificExitCode"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The ServiceType property supplies the type of service provided to calling process" +
            "es.")]
        public string ServiceType {
            get {
                return ((string)(curObj["ServiceType"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsStartedNull {
            get {
                if ((curObj["Started"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("Started is a boolean indicating whether the service has been started (TRUE), or s" +
            "topped (FALSE).")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public bool Started {
            get {
                if ((curObj["Started"] == null)) {
                    return System.Convert.ToBoolean(0);
                }
                return ((bool)(curObj["Started"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The StartMode property indicates the start mode of the Win32 base service. ""Boot"" specifies a device driver started by the operating system loader. This value is valid only for driver services. ""System"" specifies a device driver started by the IoInitSystem function. This value is valid only for driver services. ""Automatic"" specifies a service to be started automatically by the service control manager during system startup. ""Manual"" specifies a service to be started by the service control manager when a process calls the StartService function. ""Disabled"" specifies a service that can no longer be started.")]
        public string StartMode {
            get {
                return ((string)(curObj["StartMode"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The StartName property indicates the account name under which the service runs. Depending on the service type, the account name may be in the form of ""DomainName\Username"".  The service process will be logged using one of these two forms when it runs. If the account belongs to the built-in domain, "".\Username"" can be specified. If NULL is specified, the service will be logged on as the LocalSystem account. For kernel or system level drivers, StartName contains the driver object name (that is, \FileSystem\Rdr or \Driver\Xns) which the input and output (I/O) system uses to load the device driver. Additionally, if NULL is specified, the driver runs with a default object name created by the I/O system based on the service name.
Example: DWDOM\Admin.")]
        public string StartName {
            get {
                return ((string)(curObj["StartName"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The State property indicates the current state of the base service.")]
        public string State {
            get {
                return ((string)(curObj["State"]));
            }
            set {
                curObj["State"] = value;
                if (((isEmbedded == false) 
                            && (AutoCommitProp == true))) {
                    PrivateLateBoundObject.Put();
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are ""OK"", ""Degraded"" and ""Pred Fail"". ""Pred Fail"" indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are ""Error"", ""Starting"", ""Stopping"" and ""Service"". The latter, ""Service"", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither ""OK"" nor in one of the other states.")]
        public string Status {
            get {
                return ((string)(curObj["Status"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The scoping System\'s CreationClassName. ")]
        public string SystemCreationClassName {
            get {
                return ((string)(curObj["SystemCreationClassName"]));
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description("The name of the system that hosts this service")]
        public string SystemName {
            get {
                return ((string)(curObj["SystemName"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsTagIdNull {
            get {
                if ((curObj["TagId"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The TagId property specifies a unique tag value for this service in the group. A value of 0 indicates that the service has not been assigned a tag. A tag can be used for ordering service startup within a load order group by specifying a tag order vector in the registry located at: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\GroupOrderList. Tags are only evaluated for Kernel Driver and File System Driver start type services that have ""Boot"" or ""System"" start modes.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint TagId {
            get {
                if ((curObj["TagId"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["TagId"]));
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool IsWaitHintNull {
            get {
                if ((curObj["WaitHint"] == null)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Description(@"The WaitHint property specifies the estimated time required (in milliseconds) for a pending start, stop, pause, or continue operation. After the specified amount of time has elapsed, the service makes its next call to the SetServiceStatus function with either an incremented CheckPoint value or a change in Current State. If the amount of time specified by WaitHint passes, and CheckPoint has not been incremented, or the Current State has not changed, the service control manager or service control program assumes that an error has occurred.")]
        [TypeConverter(typeof(WMIValueTypeConverter))]
        public uint WaitHint {
            get {
                if ((curObj["WaitHint"] == null)) {
                    return System.Convert.ToUInt32(0);
                }
                return ((uint)(curObj["WaitHint"]));
            }
        }
        
        private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
            if (((path != null) 
                        && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
                return true;
            }
            else {
                return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
            }
        }
        
        private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
            if (((theObj != null) 
                        && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
                return true;
            }
            else {
                System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
                if ((parentClasses != null)) {
                    int count = 0;
                    for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
                        if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        
        private bool ShouldSerializeAcceptPause() {
            if ((this.IsAcceptPauseNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeAcceptStop() {
            if ((this.IsAcceptStopNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeCheckPoint() {
            if ((this.IsCheckPointNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeDesktopInteract() {
            if ((this.IsDesktopInteractNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeExitCode() {
            if ((this.IsExitCodeNull == false)) {
                return true;
            }
            return false;
        }
        
        // Converts a given datetime in DMTF format to System.DateTime object.
        static System.DateTime ToDateTime(string dmtfDate) {
            System.DateTime initializer = System.DateTime.MinValue;
            int year = initializer.Year;
            int month = initializer.Month;
            int day = initializer.Day;
            int hour = initializer.Hour;
            int minute = initializer.Minute;
            int second = initializer.Second;
            long ticks = 0;
            string dmtf = dmtfDate;
            System.DateTime datetime = System.DateTime.MinValue;
            string tempString = string.Empty;
            if ((dmtf == null)) {
                throw new System.ArgumentOutOfRangeException();
            }
            if ((dmtf.Length == 0)) {
                throw new System.ArgumentOutOfRangeException();
            }
            if ((dmtf.Length != 25)) {
                throw new System.ArgumentOutOfRangeException();
            }
            try {
                tempString = dmtf.Substring(0, 4);
                if (("****" != tempString)) {
                    year = int.Parse(tempString);
                }
                tempString = dmtf.Substring(4, 2);
                if (("**" != tempString)) {
                    month = int.Parse(tempString);
                }
                tempString = dmtf.Substring(6, 2);
                if (("**" != tempString)) {
                    day = int.Parse(tempString);
                }
                tempString = dmtf.Substring(8, 2);
                if (("**" != tempString)) {
                    hour = int.Parse(tempString);
                }
                tempString = dmtf.Substring(10, 2);
                if (("**" != tempString)) {
                    minute = int.Parse(tempString);
                }
                tempString = dmtf.Substring(12, 2);
                if (("**" != tempString)) {
                    second = int.Parse(tempString);
                }
                tempString = dmtf.Substring(15, 6);
                if (("******" != tempString)) {
                    ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000))));
                }
                if (((((((((year < 0) 
                            || (month < 0)) 
                            || (day < 0)) 
                            || (hour < 0)) 
                            || (minute < 0)) 
                            || (minute < 0)) 
                            || (second < 0)) 
                            || (ticks < 0))) {
                    throw new System.ArgumentOutOfRangeException();
                }
            }
            catch (System.Exception e) {
                throw new System.ArgumentOutOfRangeException(null, e.Message);
            }
            datetime = new System.DateTime(year, month, day, hour, minute, second, 0);
            datetime = datetime.AddTicks(ticks);
            System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
            int UTCOffset = 0;
            int OffsetToBeAdjusted = 0;
            long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
            tempString = dmtf.Substring(22, 3);
            if ((tempString != "******")) {
                tempString = dmtf.Substring(21, 4);
                try {
                    UTCOffset = int.Parse(tempString);
                }
                catch (System.Exception e) {
                    throw new System.ArgumentOutOfRangeException(null, e.Message);
                }
                OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset)));
                datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted)));
            }
            return datetime;
        }
        
        // Converts a given System.DateTime object to DMTF datetime format.
        static string ToDmtfDateTime(System.DateTime date) {
            string utcString = string.Empty;
            System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date);
            long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
            if ((System.Math.Abs(OffsetMins) > 999)) {
                date = date.ToUniversalTime();
                utcString = "+000";
            }
            else {
                if ((tickOffset.Ticks >= 0)) {
                    utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0'));
                }
                else {
                    string strTemp = ((long)(OffsetMins)).ToString();
                    utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0'));
                }
            }
            string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0');
            dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, ".");
            System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0);
            long microsec = ((long)((((date.Ticks - dtTemp.Ticks) 
                        * 1000) 
                        / System.TimeSpan.TicksPerMillisecond)));
            string strMicrosec = ((long)(microsec)).ToString();
            if ((strMicrosec.Length > 6)) {
                strMicrosec = strMicrosec.Substring(0, 6);
            }
            dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0'));
            dmtfDateTime = string.Concat(dmtfDateTime, utcString);
            return dmtfDateTime;
        }
        
        private bool ShouldSerializeInstallDate() {
            if ((this.IsInstallDateNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeProcessId() {
            if ((this.IsProcessIdNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeServiceSpecificExitCode() {
            if ((this.IsServiceSpecificExitCodeNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeStarted() {
            if ((this.IsStartedNull == false)) {
                return true;
            }
            return false;
        }
        
        private void ResetState() {
            curObj["State"] = null;
            if (((isEmbedded == false) 
                        && (AutoCommitProp == true))) {
                PrivateLateBoundObject.Put();
            }
        }
        
        private bool ShouldSerializeTagId() {
            if ((this.IsTagIdNull == false)) {
                return true;
            }
            return false;
        }
        
        private bool ShouldSerializeWaitHint() {
            if ((this.IsWaitHintNull == false)) {
                return true;
            }
            return false;
        }
        
        [Browsable(true)]
        public void CommitObject() {
            if ((isEmbedded == false)) {
                PrivateLateBoundObject.Put();
            }
        }
        
        [Browsable(true)]
        public void CommitObject(System.Management.PutOptions putOptions) {
            if ((isEmbedded == false)) {
                PrivateLateBoundObject.Put(putOptions);
            }
        }
        
        private void Initialize() {
            AutoCommitProp = true;
            isEmbedded = false;
        }
        
        private static string ConstructPath(string keyName) {
            string strPath = "ROOT\\CIMV2:Win32_Service";
            strPath = string.Concat(strPath, string.Concat(".Name=", string.Concat("\"", string.Concat(keyName, "\""))));
            return strPath;
        }
        
        private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
            Initialize();
            if ((path != null)) {
                if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
                    throw new System.ArgumentException("Class name does not match.");
                }
            }
            PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
            PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
            curObj = PrivateLateBoundObject;
        }
        
        // Different overloads of GetInstances() help in enumerating instances of the WMI class.
        public static ServiceCollection GetInstances() {
            return GetInstances(null, null, null);
        }
        
        public static ServiceCollection GetInstances(string condition) {
            return GetInstances(null, condition, null);
        }
        
        public static ServiceCollection GetInstances(string[] selectedProperties) {
            return GetInstances(null, null, selectedProperties);
        }
        
        public static ServiceCollection GetInstances(string condition, string[] selectedProperties) {
            return GetInstances(null, condition, selectedProperties);
        }
        
        public static ServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
            if ((mgmtScope == null)) {
                if ((statMgmtScope == null)) {
                    mgmtScope = new System.Management.ManagementScope();
                    mgmtScope.Path.NamespacePath = "root\\CIMV2";
                }
                else {
                    mgmtScope = statMgmtScope;
                }
            }
            System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
            pathObj.ClassName = "Win32_Service";
            pathObj.NamespacePath = "root\\CIMV2";
            System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
            if ((enumOptions == null)) {
                enumOptions = new System.Management.EnumerationOptions();
                enumOptions.EnsureLocatable = true;
            }
            return new ServiceCollection(clsObject.GetInstances(enumOptions));
        }
        
        public static ServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
            return GetInstances(mgmtScope, condition, null);
        }
        
        public static ServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
            return GetInstances(mgmtScope, null, selectedProperties);
        }
        
        public static ServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
            if ((mgmtScope == null)) {
                if ((statMgmtScope == null)) {
                    mgmtScope = new System.Management.ManagementScope();
                    mgmtScope.Path.NamespacePath = "root\\CIMV2";
                }
                else {
                    mgmtScope = statMgmtScope;
                }
            }
            System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_Service", condition, selectedProperties));
            System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
            enumOptions.EnsureLocatable = true;
            ObjectSearcher.Options = enumOptions;
            return new ServiceCollection(ObjectSearcher.Get());
        }
        
        [Browsable(true)]
        public static Service CreateInstance() {
            System.Management.ManagementScope mgmtScope = null;
            if ((statMgmtScope == null)) {
                mgmtScope = new System.Management.ManagementScope();
                mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
            }
            else {
                mgmtScope = statMgmtScope;
            }
            System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
            System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
            return new Service(tmpMgmtClass.CreateInstance());
        }
        
        [Browsable(true)]
        public void Delete() {
            PrivateLateBoundObject.Delete();
        }
        
        public uint Change(bool DesktopInteract, string DisplayName, byte ErrorControl, string LoadOrderGroup, string[] LoadOrderGroupDependencies, string PathName, string[] ServiceDependencies, byte ServiceType, string StartMode, string StartName, string StartPassword) {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                inParams = PrivateLateBoundObject.GetMethodParameters("Change");
                inParams["DesktopInteract"] = ((bool)(DesktopInteract));
                inParams["DisplayName"] = ((string)(DisplayName));
                inParams["ErrorControl"] = ((byte)(ErrorControl));
                inParams["LoadOrderGroup"] = ((string)(LoadOrderGroup));
                inParams["LoadOrderGroupDependencies"] = ((string[])(LoadOrderGroupDependencies));
                inParams["PathName"] = ((string)(PathName));
                inParams["ServiceDependencies"] = ((string[])(ServiceDependencies));
                inParams["ServiceType"] = ((byte)(ServiceType));
                inParams["StartMode"] = ((string)(StartMode));
                inParams["StartName"] = ((string)(StartName));
                inParams["StartPassword"] = ((string)(StartPassword));
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Change", inParams, null);
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint ChangeStartMode(string StartMode) {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                inParams = PrivateLateBoundObject.GetMethodParameters("ChangeStartMode");
                inParams["StartMode"] = ((string)(StartMode));
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ChangeStartMode", inParams, null);
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public static uint Create(bool DesktopInteract, string DisplayName, byte ErrorControl, string LoadOrderGroup, string[] LoadOrderGroupDependencies, string Name, string PathName, string[] ServiceDependencies, byte ServiceType, string StartMode, string StartName, string StartPassword) {
            bool IsMethodStatic = true;
            if ((IsMethodStatic == true)) {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams = classObj.GetMethodParameters("Create");
                inParams["DesktopInteract"] = ((bool)(DesktopInteract));
                inParams["DisplayName"] = ((string)(DisplayName));
                inParams["ErrorControl"] = ((byte)(ErrorControl));
                inParams["LoadOrderGroup"] = ((string)(LoadOrderGroup));
                inParams["LoadOrderGroupDependencies"] = ((string[])(LoadOrderGroupDependencies));
                inParams["Name"] = ((string)(Name));
                inParams["PathName"] = ((string)(PathName));
                inParams["ServiceDependencies"] = ((string[])(ServiceDependencies));
                inParams["ServiceType"] = ((byte)(ServiceType));
                inParams["StartMode"] = ((string)(StartMode));
                inParams["StartName"] = ((string)(StartName));
                inParams["StartPassword"] = ((string)(StartPassword));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint Delete0() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Delete", inParams, null);
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint GetSecurityDescriptor(out System.Management.ManagementBaseObject Descriptor) {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSecurityDescriptor", inParams, null);
                Descriptor = ((System.Management.ManagementBaseObject)(outParams.Properties["Descriptor"].Value));
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                Descriptor = null;
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint InterrogateService() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("InterrogateService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint PauseService() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("PauseService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint ResumeService() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ResumeService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint SetSecurityDescriptor(System.Management.ManagementBaseObject Descriptor) {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                inParams = PrivateLateBoundObject.GetMethodParameters("SetSecurityDescriptor");
                inParams["Descriptor"] = ((System.Management.ManagementBaseObject )(Descriptor));
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetSecurityDescriptor", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint StartService() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint StopService() {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        public uint UserControlService(byte ControlCode) {
            if ((isEmbedded == false)) {
                System.Management.ManagementBaseObject inParams = null;
                bool EnablePrivileges = PrivateLateBoundObject.Scope.Options.EnablePrivileges;
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = true;
                inParams = PrivateLateBoundObject.GetMethodParameters("UserControlService");
                inParams["ControlCode"] = ((byte)(ControlCode));
                System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("UserControlService", inParams, null);
                PrivateLateBoundObject.Scope.Options.EnablePrivileges = EnablePrivileges;
                return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
            }
            else {
                return System.Convert.ToUInt32(0);
            }
        }
        
        // Enumerator implementation for enumerating instances of the class.
        public class ServiceCollection : object, ICollection {
            
            private ManagementObjectCollection privColObj;
            
            public ServiceCollection(ManagementObjectCollection objCollection) {
                privColObj = objCollection;
            }
            
            public virtual int Count {
                get {
                    return privColObj.Count;
                }
            }
            
            public virtual bool IsSynchronized {
                get {
                    return privColObj.IsSynchronized;
                }
            }
            
            public virtual object SyncRoot {
                get {
                    return this;
                }
            }
            
            public virtual void CopyTo(System.Array array, int index) {
                privColObj.CopyTo(array, index);
                int nCtr;
                for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
                    array.SetValue(new Service(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
                }
            }
            
            public virtual System.Collections.IEnumerator GetEnumerator() {
                return new ServiceEnumerator(privColObj.GetEnumerator());
            }
            
            public class ServiceEnumerator : object, System.Collections.IEnumerator {
                
                private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
                
                public ServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
                    privObjEnum = objEnum;
                }
                
                public virtual object Current {
                    get {
                        return new Service(((System.Management.ManagementObject)(privObjEnum.Current)));
                    }
                }
                
                public virtual bool MoveNext() {
                    return privObjEnum.MoveNext();
                }
                
                public virtual void Reset() {
                    privObjEnum.Reset();
                }
            }
        }
        
        // TypeConverter to handle null values for ValueType properties
        public class WMIValueTypeConverter : TypeConverter {
            
            private TypeConverter baseConverter;
            
            private System.Type baseType;
            
            public WMIValueTypeConverter(System.Type inBaseType) {
                baseConverter = TypeDescriptor.GetConverter(inBaseType);
                baseType = inBaseType;
            }
            
            public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
                return baseConverter.CanConvertFrom(context, srcType);
            }
            
            public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
                return baseConverter.CanConvertTo(context, destinationType);
            }
            
            public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
                return baseConverter.ConvertFrom(context, culture, value);
            }
            
            public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
                return baseConverter.CreateInstance(context, dictionary);
            }
            
            public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
                return baseConverter.GetCreateInstanceSupported(context);
            }
            
            public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
                return baseConverter.GetProperties(context, value, attributeVar);
            }
            
            public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
                return baseConverter.GetPropertiesSupported(context);
            }
            
            public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
                return baseConverter.GetStandardValues(context);
            }
            
            public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
                return baseConverter.GetStandardValuesExclusive(context);
            }
            
            public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
                return baseConverter.GetStandardValuesSupported(context);
            }
            
            public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
                if ((baseType.BaseType == typeof(System.Enum))) {
                    if ((value.GetType() == destinationType)) {
                        return value;
                    }
                    if ((((value == null) 
                                && (context != null)) 
                                && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
                        return  "NULL_ENUM_VALUE" ;
                    }
                    return baseConverter.ConvertTo(context, culture, value, destinationType);
                }
                if (((baseType == typeof(bool)) 
                            && (baseType.BaseType == typeof(System.ValueType)))) {
                    if ((((value == null) 
                                && (context != null)) 
                                && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
                        return "";
                    }
                    return baseConverter.ConvertTo(context, culture, value, destinationType);
                }
                if (((context != null) 
                            && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
                    return "";
                }
                return baseConverter.ConvertTo(context, culture, value, destinationType);
            }
        }
        
        // Embedded class to represent WMI system Properties.
        [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
        public class ManagementSystemProperties {
            
            private System.Management.ManagementBaseObject PrivateLateBoundObject;
            
            public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
                PrivateLateBoundObject = ManagedObject;
            }
            
            [Browsable(true)]
            public int GENUS {
                get {
                    return ((int)(PrivateLateBoundObject["__GENUS"]));
                }
            }
            
            [Browsable(true)]
            public string CLASS {
                get {
                    return ((string)(PrivateLateBoundObject["__CLASS"]));
                }
            }
            
            [Browsable(true)]
            public string SUPERCLASS {
                get {
                    return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
                }
            }
            
            [Browsable(true)]
            public string DYNASTY {
                get {
                    return ((string)(PrivateLateBoundObject["__DYNASTY"]));
                }
            }
            
            [Browsable(true)]
            public string RELPATH {
                get {
                    return ((string)(PrivateLateBoundObject["__RELPATH"]));
                }
            }
            
            [Browsable(true)]
            public int PROPERTY_COUNT {
                get {
                    return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
                }
            }
            
            [Browsable(true)]
            public string[] DERIVATION {
                get {
                    return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
                }
            }
            
            [Browsable(true)]
            public string SERVER {
                get {
                    return ((string)(PrivateLateBoundObject["__SERVER"]));
                }
            }
            
            [Browsable(true)]
            public string NAMESPACE {
                get {
                    return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
                }
            }
            
            [Browsable(true)]
            public string PATH {
                get {
                    return ((string)(PrivateLateBoundObject["__PATH"]));
                }
            }
        }
    }
}


...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836574
Сон Веры Павловны
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
JeStone
Код: c#
1.
// Этот WMI класс генерится автоматом


А называется этот автомат mgmtclassgen .
JeStoneИз минусов такого решения - по-моему WMI не поддерживается на XP
Вполне поддерживается.
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836599
Arm79
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
7182820 => 13871561 (без старт/стоп, оказалось, не нужно)

Все остальное - добавляете в сервис инсталляторы, и в свойствах прописываете
Дмитрий771) Задать DisplayName
2) Задать Description
3) Задать StartUp Mode (start= auto; start= demand...)
4) Узнать текущий StartUp Mode (start= auto; start= demand...)
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836748
carrotik
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
JeStone,

... WMI поддерживалось еще на 2000 ....
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836751
Фотография Изопропил
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
carrotik... WMI поддерживалось еще на 2000 ....
на 2000 и Win 98 - установлено было изначально

на NT 4 и Win95 - можно было установить отдельно
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38836884
JeStone
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
carrotikJeStone,

... WMI поддерживалось еще на 2000 ....
Это же замечательно. Мне не приходится работать с такими старыми ОС, поэтому я этого не знал
...
Рейтинг: 0 / 0
Управление WinService NT: Delete, DisplayName, Description, StartMode
    #38837054
Дмитрий77
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Ребят, но WMI в отличии от ServiceController (который есть "чисто .Net" класс для работы с сервисами) - это отдельная песня.
ServiceController -это как раз .Net обертка над Win32 API Service Functions , но как видим сильно неполная.

Про WMI -да оно есть везде начиная с XP. И я довольно долго его использовал для энумерации портов и модемов в системе. Но в итоге я от WMI отказался в пользу DiSetup.. API, т.к. с WMI были некоторые мелкие глюки (долго объяснять).

Поэтому если уж выбирать между API и WMI то однозначно API.
...
Рейтинг: 0 / 0
20 сообщений из 20, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Управление WinService NT: Delete, DisplayName, Description, StartMode
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]