Main.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.IO;
  10. using WMI;
  11. using System.Xml;
  12. using System.Threading;
  13. using Microsoft.Win32;
  14. namespace winsw
  15. {
  16. public struct SERVICE_STATUS
  17. {
  18. public int serviceType;
  19. public int currentState;
  20. public int controlsAccepted;
  21. public int win32ExitCode;
  22. public int serviceSpecificExitCode;
  23. public int checkPoint;
  24. public int waitHint;
  25. }
  26. public enum State
  27. {
  28. SERVICE_STOPPED = 0x00000001,
  29. SERVICE_START_PENDING = 0x00000002,
  30. SERVICE_STOP_PENDING = 0x00000003,
  31. SERVICE_RUNNING = 0x00000004,
  32. SERVICE_CONTINUE_PENDING = 0x00000005,
  33. SERVICE_PAUSE_PENDING = 0x00000006,
  34. SERVICE_PAUSED = 0x00000007,
  35. }
  36. /// <summary>
  37. /// In-memory representation of the configuration file.
  38. /// </summary>
  39. public class ServiceDescriptor
  40. {
  41. private readonly XmlDocument dom = new XmlDocument();
  42. /// <summary>
  43. /// Where did we find the configuration file?
  44. ///
  45. /// This string is "c:\abc\def\ghi" when the configuration XML is "c:\abc\def\ghi.xml"
  46. /// </summary>
  47. public readonly string BasePath;
  48. /// <summary>
  49. /// The file name portion of the configuration file.
  50. ///
  51. /// In the above example, this would be "ghi".
  52. /// </summary>
  53. public readonly string BaseName;
  54. public static string ExecutablePath
  55. {
  56. get
  57. {
  58. // this returns the executable name as given by the calling process, so
  59. // it needs to be absolutized.
  60. string p = Environment.GetCommandLineArgs()[0];
  61. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  62. }
  63. }
  64. public ServiceDescriptor()
  65. {
  66. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  67. // as well as trimming off ".vshost" suffix (which is used during debugging)
  68. string p = ExecutablePath;
  69. string baseName = Path.GetFileNameWithoutExtension(p);
  70. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  71. while (true)
  72. {
  73. p = Path.GetDirectoryName(p);
  74. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  75. break;
  76. }
  77. // register the base directory as environment variable so that future expansions can refer to this.
  78. Environment.SetEnvironmentVariable("BASE", p);
  79. BaseName = baseName;
  80. BasePath = Path.Combine(p, BaseName);
  81. dom.Load(BasePath+".xml");
  82. }
  83. private string SingleElement(string tagName)
  84. {
  85. var n = dom.SelectSingleNode("//" + tagName);
  86. if (n == null) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  87. return Environment.ExpandEnvironmentVariables(n.InnerText);
  88. }
  89. /// <summary>
  90. /// Path to the executable.
  91. /// </summary>
  92. public string Executable
  93. {
  94. get
  95. {
  96. return SingleElement("executable");
  97. }
  98. }
  99. /// <summary>
  100. /// Optionally specify a different Path to an executable to shutdown the service.
  101. /// </summary>
  102. public string StopExecutable
  103. {
  104. get
  105. {
  106. return AppendTags("stopexecutable");
  107. }
  108. }
  109. /// <summary>
  110. /// Arguments or multiple optional argument elements which overrule the arguments element.
  111. /// </summary>
  112. public string Arguments
  113. {
  114. get
  115. {
  116. string arguments = AppendTags("argument");
  117. if (arguments == null)
  118. {
  119. var tagName = "arguments";
  120. var argumentsNode = dom.SelectSingleNode("//" + tagName);
  121. if (argumentsNode == null)
  122. {
  123. if (AppendTags("startargument") == null)
  124. {
  125. throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  126. }
  127. else
  128. {
  129. return "";
  130. }
  131. }
  132. return Environment.ExpandEnvironmentVariables(argumentsNode.InnerText);
  133. }
  134. else
  135. {
  136. return arguments;
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Multiple optional startargument elements.
  142. /// </summary>
  143. public string Startarguments
  144. {
  145. get
  146. {
  147. return AppendTags("startargument");
  148. }
  149. }
  150. /// <summary>
  151. /// Multiple optional stopargument elements.
  152. /// </summary>
  153. public string Stoparguments
  154. {
  155. get
  156. {
  157. return AppendTags("stopargument");
  158. }
  159. }
  160. /// <summary>
  161. /// Combines the contents of all the elements of the given name,
  162. /// or return null if no element exists.
  163. /// </summary>
  164. private string AppendTags(string tagName)
  165. {
  166. XmlNode argumentNode = dom.SelectSingleNode("//" + tagName);
  167. if (argumentNode == null)
  168. {
  169. return null;
  170. }
  171. else
  172. {
  173. string arguments = "";
  174. foreach (XmlNode argument in dom.SelectNodes("//" + tagName))
  175. {
  176. arguments += " " + argument.InnerText;
  177. }
  178. return Environment.ExpandEnvironmentVariables(arguments);
  179. }
  180. }
  181. /// <summary>
  182. /// LogDirectory is the service wrapper executable directory or the optionally specified logpath element.
  183. /// </summary>
  184. public string LogDirectory
  185. {
  186. get
  187. {
  188. XmlNode loggingNode = dom.SelectSingleNode("//logpath");
  189. if (loggingNode != null)
  190. {
  191. return loggingNode.InnerText;
  192. }
  193. else
  194. {
  195. return Path.GetDirectoryName(ExecutablePath);
  196. }
  197. }
  198. }
  199. /// <summary>
  200. /// Logmode to 'reset', 'roll' once or 'append' [default] the out.log and err.log files.
  201. /// </summary>
  202. public string Logmode
  203. {
  204. get
  205. {
  206. XmlNode logmodeNode = dom.SelectSingleNode("//logmode");
  207. if (logmodeNode == null)
  208. {
  209. return "append";
  210. }
  211. else
  212. {
  213. return logmodeNode.InnerText;
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// Optionally specified depend services that must start before this service starts.
  219. /// </summary>
  220. public string[] ServiceDependencies
  221. {
  222. get
  223. {
  224. System.Collections.ArrayList serviceDependencies = new System.Collections.ArrayList();
  225. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  226. {
  227. serviceDependencies.Add(depend.InnerText);
  228. }
  229. return (string[])serviceDependencies.ToArray(typeof(string));
  230. }
  231. }
  232. public string Id
  233. {
  234. get
  235. {
  236. return SingleElement("id");
  237. }
  238. }
  239. public string Caption
  240. {
  241. get
  242. {
  243. return SingleElement("name");
  244. }
  245. }
  246. public string Description
  247. {
  248. get
  249. {
  250. return SingleElement("description");
  251. }
  252. }
  253. /// <summary>
  254. /// True if the service should when finished on shutdown.
  255. /// </summary>
  256. public bool BeepOnShutdown
  257. {
  258. get
  259. {
  260. return dom.SelectSingleNode("//beeponshutdown") != null;
  261. }
  262. }
  263. /// <summary>
  264. /// The estimated time required for a pending stop operation, in milliseconds (default 15 secs).
  265. /// Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function
  266. /// with either an incremented checkPoint value or a change in currentState. (see http://msdn.microsoft.com/en-us/library/ms685996.aspx)
  267. /// </summary>
  268. public int WaitHint
  269. {
  270. get
  271. {
  272. XmlNode waithintNode = dom.SelectSingleNode("//waithint");
  273. if (waithintNode == null)
  274. {
  275. return 15000;
  276. }
  277. else
  278. {
  279. return int.Parse(waithintNode.InnerText);
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// The time, in milliseconds (default 1 sec), before the service should make its next call to the SetServiceStatus function
  285. /// with an incremented checkPoint value.
  286. /// Do not wait longer than the wait hint. A good interval is one-tenth of the wait hint but not less than 1 second and not more than 10 seconds.
  287. /// </summary>
  288. public int SleepTime
  289. {
  290. get
  291. {
  292. XmlNode sleeptimeNode = dom.SelectSingleNode("//sleeptime");
  293. if (sleeptimeNode == null)
  294. {
  295. return 1000;
  296. }
  297. else
  298. {
  299. return int.Parse(sleeptimeNode.InnerText);
  300. }
  301. }
  302. }
  303. /// <summary>
  304. /// True if the service can interact with the desktop.
  305. /// </summary>
  306. public bool Interactive
  307. {
  308. get
  309. {
  310. return dom.SelectSingleNode("//interactive") != null;
  311. }
  312. }
  313. /// <summary>
  314. /// Environment variable overrides
  315. /// </summary>
  316. public Dictionary<string, string> EnvironmentVariables
  317. {
  318. get
  319. {
  320. Dictionary<string, string> map = new Dictionary<string, string>();
  321. foreach (XmlNode n in dom.SelectNodes("//env"))
  322. {
  323. string key = n.Attributes["name"].Value;
  324. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  325. map[key] = value;
  326. Environment.SetEnvironmentVariable(key, value);
  327. }
  328. return map;
  329. }
  330. }
  331. }
  332. public class WrapperService : ServiceBase
  333. {
  334. [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
  335. private static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
  336. private SERVICE_STATUS wrapperServiceStatus;
  337. private Process process = new Process();
  338. private ServiceDescriptor descriptor;
  339. private Dictionary<string, string> envs;
  340. /// <summary>
  341. /// Indicates to the watch dog thread that we are going to terminate the process,
  342. /// so don't try to kill us when the child exits.
  343. /// </summary>
  344. private bool orderlyShutdown;
  345. private bool systemShuttingdown;
  346. public WrapperService()
  347. {
  348. this.descriptor = new ServiceDescriptor();
  349. this.ServiceName = descriptor.Id;
  350. this.CanShutdown = true;
  351. this.CanStop = true;
  352. this.CanPauseAndContinue = false;
  353. this.AutoLog = true;
  354. this.systemShuttingdown = false;
  355. }
  356. /// <summary>
  357. /// Copy stuff from StreamReader to StreamWriter
  358. /// </summary>
  359. private void CopyStream(StreamReader i, StreamWriter o)
  360. {
  361. char[] buf = new char[1024];
  362. while (true)
  363. {
  364. int sz = i.Read(buf, 0, buf.Length);
  365. if (sz == 0) break;
  366. o.Write(buf, 0, sz);
  367. o.Flush();
  368. }
  369. i.Close();
  370. o.Close();
  371. }
  372. /// <summary>
  373. /// Process the file copy instructions, so that we can replace files that are always in use while
  374. /// the service runs.
  375. /// </summary>
  376. private void HandleFileCopies()
  377. {
  378. var file = descriptor.BasePath + ".copies";
  379. if (!File.Exists(file))
  380. return; // nothing to handle
  381. try
  382. {
  383. using (var tr = new StreamReader(file,Encoding.UTF8))
  384. {
  385. string line;
  386. while ((line = tr.ReadLine()) != null)
  387. {
  388. LogEvent("Handling copy: " + line);
  389. string[] tokens = line.Split('>');
  390. if (tokens.Length > 2)
  391. {
  392. LogEvent("Too many delimiters in " + line);
  393. continue;
  394. }
  395. CopyFile(tokens[0], tokens[1]);
  396. }
  397. }
  398. }
  399. finally
  400. {
  401. File.Delete(file);
  402. }
  403. }
  404. private void CopyFile(string sourceFileName, string destFileName)
  405. {
  406. try
  407. {
  408. File.Delete(destFileName);
  409. File.Move(sourceFileName, destFileName);
  410. }
  411. catch (IOException e)
  412. {
  413. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  414. }
  415. }
  416. /// <summary>
  417. /// Handle the creation of the logfiles based on the optional logmode setting.
  418. /// </summary>
  419. private void HandleLogfiles()
  420. {
  421. string logDirectory = descriptor.LogDirectory;
  422. if (!Directory.Exists(logDirectory))
  423. {
  424. Directory.CreateDirectory(logDirectory);
  425. }
  426. string baseName = descriptor.BaseName;
  427. string errorLogfilename = Path.Combine(logDirectory, baseName + ".err.log");
  428. string outputLogfilename = Path.Combine(logDirectory, baseName + ".out.log");
  429. System.IO.FileMode fileMode = FileMode.Append;
  430. if (descriptor.Logmode == "reset")
  431. {
  432. fileMode = FileMode.Create;
  433. }
  434. else if (descriptor.Logmode == "roll")
  435. {
  436. CopyFile(outputLogfilename, outputLogfilename + ".old");
  437. CopyFile(errorLogfilename, errorLogfilename + ".old");
  438. }
  439. new Thread(delegate() { CopyStream(process.StandardOutput, new StreamWriter(new FileStream(outputLogfilename, fileMode))); }).Start();
  440. new Thread(delegate() { CopyStream(process.StandardError, new StreamWriter(new FileStream(errorLogfilename, fileMode))); }).Start();
  441. }
  442. private void LogEvent(String message)
  443. {
  444. if (systemShuttingdown)
  445. {
  446. /* NOP - cannot call EventLog because of shutdown. */
  447. }
  448. else
  449. {
  450. EventLog.WriteEntry(message);
  451. }
  452. }
  453. private void LogEvent(String message, EventLogEntryType type)
  454. {
  455. if (systemShuttingdown)
  456. {
  457. /* NOP - cannot call EventLog because of shutdown. */
  458. }
  459. else
  460. {
  461. EventLog.WriteEntry(message, type);
  462. }
  463. }
  464. private void WriteEvent(String message, Exception exception)
  465. {
  466. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  467. }
  468. private void WriteEvent(String message)
  469. {
  470. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  471. StreamWriter log = new StreamWriter(logfilename, true);
  472. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  473. log.Flush();
  474. log.Close();
  475. }
  476. protected override void OnStart(string[] args)
  477. {
  478. envs = descriptor.EnvironmentVariables;
  479. foreach (string key in envs.Keys)
  480. {
  481. LogEvent("envar " + key + '=' + envs[key]);
  482. }
  483. HandleFileCopies();
  484. string startarguments = descriptor.Startarguments;
  485. if (startarguments == null)
  486. {
  487. startarguments = descriptor.Arguments;
  488. }
  489. else
  490. {
  491. startarguments += " " + descriptor.Arguments;
  492. }
  493. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  494. WriteEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  495. StartProcess(process, startarguments, descriptor.Executable);
  496. // send stdout and stderr to its respective output file.
  497. HandleLogfiles();
  498. process.StandardInput.Close(); // nothing for you to read!
  499. }
  500. protected override void OnShutdown()
  501. {
  502. // WriteEvent("OnShutdown");
  503. try
  504. {
  505. this.systemShuttingdown = true;
  506. StopIt();
  507. }
  508. catch (Exception ex)
  509. {
  510. WriteEvent("Shutdown exception", ex);
  511. }
  512. }
  513. protected override void OnStop()
  514. {
  515. // WriteEvent("OnStop");
  516. try
  517. {
  518. StopIt();
  519. }
  520. catch (Exception ex)
  521. {
  522. WriteEvent("Stop exception", ex);
  523. }
  524. }
  525. private void StopIt()
  526. {
  527. string stoparguments = descriptor.Stoparguments;
  528. LogEvent("Stopping " + descriptor.Id);
  529. WriteEvent("Stopping " + descriptor.Id);
  530. orderlyShutdown = true;
  531. if (stoparguments == null)
  532. {
  533. try
  534. {
  535. WriteEvent("ProcessKill " + process.Id);
  536. process.Kill();
  537. }
  538. catch (InvalidOperationException)
  539. {
  540. // already terminated
  541. }
  542. }
  543. else
  544. {
  545. SignalShutdownPending();
  546. stoparguments += " " + descriptor.Arguments;
  547. Process stopProcess = new Process();
  548. String executable = descriptor.StopExecutable;
  549. if (executable == null)
  550. {
  551. executable = descriptor.Executable;
  552. }
  553. StartProcess(stopProcess, stoparguments, executable);
  554. WriteEvent("WaitForProcessToExit "+process.Id+"+"+stopProcess.Id);
  555. WaitForProcessToExit(process);
  556. WaitForProcessToExit(stopProcess);
  557. SignalShutdownComplete();
  558. }
  559. if (systemShuttingdown && descriptor.BeepOnShutdown)
  560. {
  561. Console.Beep();
  562. }
  563. WriteEvent("Finished " + descriptor.Id);
  564. }
  565. private void WaitForProcessToExit(Process process)
  566. {
  567. SignalShutdownPending();
  568. try
  569. {
  570. // WriteEvent("WaitForProcessToExit [start]");
  571. while (!process.WaitForExit(descriptor.SleepTime))
  572. {
  573. SignalShutdownPending();
  574. // WriteEvent("WaitForProcessToExit [repeat]");
  575. }
  576. }
  577. catch (InvalidOperationException)
  578. {
  579. // already terminated
  580. }
  581. // WriteEvent("WaitForProcessToExit [finished]");
  582. }
  583. private void SignalShutdownPending()
  584. {
  585. IntPtr handle = this.ServiceHandle;
  586. wrapperServiceStatus.checkPoint++;
  587. wrapperServiceStatus.waitHint = descriptor.WaitHint;
  588. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  589. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  590. SetServiceStatus(handle, ref wrapperServiceStatus);
  591. }
  592. private void SignalShutdownComplete()
  593. {
  594. IntPtr handle = this.ServiceHandle;
  595. wrapperServiceStatus.checkPoint++;
  596. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  597. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  598. SetServiceStatus(handle, ref wrapperServiceStatus);
  599. }
  600. private void StartProcess(Process process, string arguments, String executable)
  601. {
  602. var ps = process.StartInfo;
  603. ps.FileName = executable;
  604. ps.Arguments = arguments;
  605. ps.CreateNoWindow = false;
  606. ps.UseShellExecute = false;
  607. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  608. ps.RedirectStandardOutput = true;
  609. ps.RedirectStandardError = true;
  610. foreach (string key in envs.Keys)
  611. System.Environment.SetEnvironmentVariable(key, envs[key]);
  612. // ps.EnvironmentVariables[key] = envs[key]; // bugged (lower cases all variable names due to StringDictionary being used, see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=326163)
  613. process.Start();
  614. WriteEvent("Started " + process.Id);
  615. // monitor the completion of the process
  616. new Thread(delegate()
  617. {
  618. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  619. process.WaitForExit();
  620. try
  621. {
  622. if (orderlyShutdown)
  623. {
  624. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  625. }
  626. else
  627. {
  628. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  629. Environment.Exit(process.ExitCode);
  630. }
  631. }
  632. catch (InvalidOperationException ioe)
  633. {
  634. LogEvent("WaitForExit " + ioe.Message);
  635. }
  636. try
  637. {
  638. process.Dispose();
  639. }
  640. catch (InvalidOperationException ioe)
  641. {
  642. LogEvent("Dispose " + ioe.Message);
  643. }
  644. }).Start();
  645. }
  646. public static int Main(string[] args)
  647. {
  648. try
  649. {
  650. Run(args);
  651. return 0;
  652. }
  653. catch (WmiException e)
  654. {
  655. Console.Error.WriteLine(e);
  656. return (int)e.ErrorCode;
  657. }
  658. catch (Exception e)
  659. {
  660. Console.Error.WriteLine(e);
  661. return -1;
  662. }
  663. }
  664. private static void ThrowNoSuchService()
  665. {
  666. throw new WmiException(ReturnValue.NoSuchService);
  667. }
  668. public static void Run(string[] args)
  669. {
  670. if (args.Length > 0)
  671. {
  672. var d = new ServiceDescriptor();
  673. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  674. Win32Service s = svc.Select(d.Id);
  675. args[0] = args[0].ToLower();
  676. if (args[0] == "install")
  677. {
  678. svc.Create(
  679. d.Id,
  680. d.Caption,
  681. ServiceDescriptor.ExecutablePath,
  682. WMI.ServiceType.OwnProcess,
  683. ErrorControl.UserNotified,
  684. StartMode.Automatic,
  685. d.Interactive,
  686. d.ServiceDependencies);
  687. // update the description
  688. /* Somehow this doesn't work, even though it doesn't report an error
  689. Win32Service s = svc.Select(d.Id);
  690. s.Description = d.Description;
  691. s.Commit();
  692. */
  693. // so using a classic method to set the description. Ugly.
  694. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  695. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  696. }
  697. if (args[0] == "uninstall")
  698. {
  699. if (s == null)
  700. return; // there's no such service, so consider it already uninstalled
  701. try
  702. {
  703. s.Delete();
  704. }
  705. catch (WmiException e)
  706. {
  707. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  708. return; // it's already uninstalled, so consider it a success
  709. throw e;
  710. }
  711. }
  712. if (args[0] == "start")
  713. {
  714. if (s == null) ThrowNoSuchService();
  715. s.StartService();
  716. }
  717. if (args[0] == "stop")
  718. {
  719. if (s == null) ThrowNoSuchService();
  720. s.StopService();
  721. }
  722. if (args[0] == "restart")
  723. {
  724. if (s == null)
  725. ThrowNoSuchService();
  726. if(s.Started)
  727. s.StopService();
  728. while (s.Started)
  729. {
  730. Thread.Sleep(1000);
  731. s = svc.Select(d.Id);
  732. }
  733. s.StartService();
  734. }
  735. if (args[0] == "status")
  736. {
  737. if (s == null)
  738. Console.WriteLine("NonExistent");
  739. else if (s.Started)
  740. Console.WriteLine("Started");
  741. else
  742. Console.WriteLine("Stopped");
  743. }
  744. if (args[0] == "test")
  745. {
  746. WrapperService wsvc = new WrapperService();
  747. wsvc.OnStart(args);
  748. Thread.Sleep(1000);
  749. wsvc.OnStop();
  750. }
  751. return;
  752. }
  753. ServiceBase.Run(new WrapperService());
  754. }
  755. }
  756. }