MainApplicationContext.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2019 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerSystemTrayApp.Properties;
  16. using Microsoft.Win32;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.ComponentModel;
  20. using System.Diagnostics;
  21. using System.Drawing;
  22. using System.IO;
  23. using System.Management;
  24. using System.Net;
  25. using System.Net.NetworkInformation;
  26. using System.Net.Sockets;
  27. using System.Reflection;
  28. using System.ServiceProcess;
  29. using System.Text;
  30. using System.Windows.Forms;
  31. using TechnitiumLibrary.IO;
  32. namespace DnsServerSystemTrayApp
  33. {
  34. public class MainApplicationContext : ApplicationContext
  35. {
  36. #region variables
  37. const int SERVICE_WAIT_TIMEOUT_SECONDS = 30;
  38. private readonly ServiceController _service = new ServiceController("DnsService");
  39. readonly string _configFile;
  40. readonly List<DnsProvider> _dnsProviders = new List<DnsProvider>();
  41. private NotifyIcon TrayIcon;
  42. private ContextMenuStrip TrayIconContextMenu;
  43. private ToolStripMenuItem DashboardMenuItem;
  44. private ToolStripMenuItem NetworkDnsMenuItem;
  45. private ToolStripMenuItem DefaultNetworkDnsMenuItem;
  46. private ToolStripMenuItem ManageNetworkDnsMenuItem;
  47. private ToolStripMenuItem ServiceMenuItem;
  48. private ToolStripMenuItem StartServiceMenuItem;
  49. private ToolStripMenuItem RestartServiceMenuItem;
  50. private ToolStripMenuItem StopServiceMenuItem;
  51. private ToolStripMenuItem AboutMenuItem;
  52. private ToolStripMenuItem AutoStartMenuItem;
  53. private ToolStripMenuItem ExitMenuItem;
  54. #endregion
  55. #region constructor
  56. public MainApplicationContext(string configFile, string[] args)
  57. {
  58. _configFile = configFile;
  59. LoadConfig();
  60. InitializeComponent();
  61. if (args.Length > 0)
  62. {
  63. switch (args[0])
  64. {
  65. case "--network-dns-default":
  66. DefaultNetworkDnsMenuItem_Click(this, EventArgs.Empty);
  67. break;
  68. case "--network-dns-item":
  69. foreach (DnsProvider dnsProvider in _dnsProviders)
  70. {
  71. if (dnsProvider.Name.Equals(args[1]))
  72. {
  73. NetworkDnsMenuSubItem_Click(new ToolStripMenuItem(dnsProvider.Name) { Tag = dnsProvider }, EventArgs.Empty);
  74. break;
  75. }
  76. }
  77. break;
  78. case "--network-dns-manage":
  79. ManageNetworkDnsMenuItem_Click(this, EventArgs.Empty);
  80. break;
  81. case "--service-start":
  82. StartServiceMenuItem_Click(this, EventArgs.Empty);
  83. break;
  84. case "--service-restart":
  85. RestartServiceMenuItem_Click(this, EventArgs.Empty);
  86. break;
  87. case "--service-stop":
  88. StopServiceMenuItem_Click(this, EventArgs.Empty);
  89. break;
  90. }
  91. }
  92. }
  93. #endregion
  94. #region IDisposable
  95. protected override void Dispose(bool disposing)
  96. {
  97. if (disposing)
  98. {
  99. TrayIcon?.Dispose();
  100. }
  101. base.Dispose(disposing);
  102. }
  103. #endregion
  104. #region private
  105. private void InitializeComponent()
  106. {
  107. //
  108. // TrayIconContextMenu
  109. //
  110. TrayIconContextMenu = new ContextMenuStrip();
  111. TrayIconContextMenu.SuspendLayout();
  112. //
  113. // TrayIcon
  114. //
  115. var resources = new ComponentResourceManager(typeof(frmAbout));
  116. TrayIcon = new NotifyIcon();
  117. TrayIcon.Icon = (Icon)resources.GetObject("$this.Icon");
  118. TrayIcon.Visible = true;
  119. TrayIcon.MouseUp += TrayIcon_MouseUp;
  120. TrayIcon.ContextMenuStrip = TrayIconContextMenu;
  121. TrayIcon.Text = Resources.ServiceName;
  122. //
  123. // DashboardMenuItem
  124. //
  125. DashboardMenuItem = new ToolStripMenuItem();
  126. DashboardMenuItem.Name = "DashboardMenuItem";
  127. DashboardMenuItem.Text = Resources.DashboardMenuItem;
  128. DashboardMenuItem.Click += DashboardMenuItem_Click;
  129. //
  130. // NetworkDnsMenuItem
  131. //
  132. NetworkDnsMenuItem = new ToolStripMenuItem();
  133. NetworkDnsMenuItem.Name = "NetworkDnsMenuItem";
  134. NetworkDnsMenuItem.Text = Resources.NetworkDnsMenuItem;
  135. DefaultNetworkDnsMenuItem = new ToolStripMenuItem("Default");
  136. DefaultNetworkDnsMenuItem.Click += DefaultNetworkDnsMenuItem_Click;
  137. ManageNetworkDnsMenuItem = new ToolStripMenuItem("Manage");
  138. ManageNetworkDnsMenuItem.Click += ManageNetworkDnsMenuItem_Click;
  139. //
  140. // ServiceMenuItem
  141. //
  142. ServiceMenuItem = new ToolStripMenuItem();
  143. ServiceMenuItem.Name = "ServiceMenuItem";
  144. ServiceMenuItem.Text = Resources.ServiceMenuItem;
  145. StartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStartMenuItem);
  146. StartServiceMenuItem.Click += StartServiceMenuItem_Click;
  147. RestartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceRestartMenuItem);
  148. RestartServiceMenuItem.Click += RestartServiceMenuItem_Click;
  149. StopServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStopMenuItem);
  150. StopServiceMenuItem.Click += StopServiceMenuItem_Click;
  151. ServiceMenuItem.DropDownItems.AddRange(new ToolStripItem[]
  152. {
  153. StartServiceMenuItem,
  154. RestartServiceMenuItem,
  155. StopServiceMenuItem
  156. });
  157. //
  158. // AboutMenuItem
  159. //
  160. AboutMenuItem = new ToolStripMenuItem();
  161. AboutMenuItem.Name = "AboutMenuItem";
  162. AboutMenuItem.Text = Resources.AboutMenuItem;
  163. AboutMenuItem.Click += AboutMenuItem_Click;
  164. //
  165. // AutoStartMenuItem
  166. //
  167. AutoStartMenuItem = new ToolStripMenuItem();
  168. AutoStartMenuItem.Name = "AutoStartMenuItem";
  169. AutoStartMenuItem.Text = "&Auto Start Icon";
  170. AutoStartMenuItem.Click += AutoStartMenuItem_Click;
  171. //
  172. // ExitMenuItem
  173. //
  174. ExitMenuItem = new ToolStripMenuItem();
  175. ExitMenuItem.Name = "ExitMenuItem";
  176. ExitMenuItem.Text = Resources.ExitMenuItem;
  177. ExitMenuItem.Click += ExitMenuItem_Click;
  178. TrayIconContextMenu.Items.AddRange(new ToolStripItem[]
  179. {
  180. DashboardMenuItem,
  181. new ToolStripSeparator(),
  182. NetworkDnsMenuItem,
  183. ServiceMenuItem,
  184. AboutMenuItem,
  185. new ToolStripSeparator(),
  186. AutoStartMenuItem,
  187. ExitMenuItem
  188. });
  189. TrayIconContextMenu.ResumeLayout(false);
  190. }
  191. private void LoadConfig()
  192. {
  193. try
  194. {
  195. using (FileStream fS = new FileStream(_configFile, FileMode.Open, FileAccess.Read))
  196. {
  197. BinaryReader bR = new BinaryReader(fS);
  198. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DT")
  199. throw new InvalidDataException("Invalid DNS Server System Tray App config file format.");
  200. switch (bR.ReadByte())
  201. {
  202. case 1:
  203. int count = bR.ReadInt32();
  204. _dnsProviders.Clear();
  205. for (int i = 0; i < count; i++)
  206. _dnsProviders.Add(new DnsProvider(bR));
  207. _dnsProviders.Sort();
  208. break;
  209. default:
  210. throw new NotSupportedException("DNS Server System Tray App config file format is not supported.");
  211. }
  212. }
  213. }
  214. catch (FileNotFoundException)
  215. {
  216. _dnsProviders.Clear();
  217. _dnsProviders.AddRange(DnsProvider.GetDefaultProviders());
  218. SaveConfig();
  219. }
  220. catch (Exception ex)
  221. {
  222. MessageBox.Show("Error occured while loading config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  223. }
  224. }
  225. private void SaveConfig()
  226. {
  227. try
  228. {
  229. using (FileStream fS = new FileStream(_configFile, FileMode.Create, FileAccess.Write))
  230. {
  231. BinaryWriter bW = new BinaryWriter(fS);
  232. bW.Write(Encoding.ASCII.GetBytes("DT"));
  233. bW.Write((byte)1);
  234. bW.Write(_dnsProviders.Count);
  235. foreach (DnsProvider dnsProvider in _dnsProviders)
  236. dnsProvider.WriteTo(bW);
  237. }
  238. }
  239. catch (Exception ex)
  240. {
  241. MessageBox.Show("Error occured while saving config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  242. }
  243. }
  244. private static void SetNameServer(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  245. {
  246. SetNameServerIPv4(nic, dnsAddresses);
  247. SetNameServerIPv6(nic, dnsAddresses);
  248. }
  249. private static void SetNameServerIPv4(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  250. {
  251. ManagementClass networkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
  252. ManagementObjectCollection instances = networkAdapterConfig.GetInstances();
  253. foreach (ManagementObject obj in instances)
  254. {
  255. if ((bool)obj["IPEnabled"] && obj["SettingID"].Equals(nic.Id))
  256. {
  257. List<string> dnsServers = new List<string>();
  258. foreach (IPAddress dnsAddress in dnsAddresses)
  259. {
  260. if (dnsAddress.AddressFamily != AddressFamily.InterNetwork)
  261. continue;
  262. dnsServers.Add(dnsAddress.ToString());
  263. }
  264. ManagementBaseObject objParameter = obj.GetMethodParameters("SetDNSServerSearchOrder");
  265. objParameter["DNSServerSearchOrder"] = dnsServers.ToArray();
  266. ManagementBaseObject response = obj.InvokeMethod("SetDNSServerSearchOrder", objParameter, null);
  267. uint returnValue = (uint)response.GetPropertyValue("ReturnValue");
  268. switch (returnValue)
  269. {
  270. case 0: //success
  271. case 1: //reboot required
  272. break;
  273. case 64:
  274. throw new Exception("Method not supported on this platform. WMI error code: " + returnValue);
  275. case 65:
  276. throw new Exception("Unknown failure. WMI error code: " + returnValue);
  277. case 70:
  278. throw new Exception("Invalid IP address. WMI error code: " + returnValue);
  279. case 96:
  280. throw new Exception("Unable to notify DNS service. WMI error code: " + returnValue);
  281. case 97:
  282. throw new Exception("Interface not configurable. WMI error code: " + returnValue);
  283. default:
  284. throw new Exception("WMI error code: " + returnValue);
  285. }
  286. break;
  287. }
  288. }
  289. }
  290. private static void SetNameServerIPv6(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  291. {
  292. //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\{}
  293. string nameServer = null;
  294. foreach (IPAddress dnsAddress in dnsAddresses)
  295. {
  296. if (dnsAddress.AddressFamily != AddressFamily.InterNetworkV6)
  297. continue;
  298. if (nameServer == null)
  299. nameServer = dnsAddress.ToString();
  300. else
  301. nameServer += "," + dnsAddress.ToString();
  302. }
  303. if (nameServer == null)
  304. nameServer = "";
  305. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\" + nic.Id, true))
  306. {
  307. if (key != null)
  308. key.SetValue("NameServer", nameServer, RegistryValueKind.String);
  309. }
  310. }
  311. private static bool AddressExists(ICollection<IPAddress> checkAddresses, ICollection<IPAddress> addresses)
  312. {
  313. foreach (IPAddress checkAddress in checkAddresses)
  314. {
  315. foreach (IPAddress address in addresses)
  316. {
  317. if (checkAddress.Equals(address))
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. private void TrayIcon_MouseUp(object sender, MouseEventArgs e)
  324. {
  325. if (e.Button == MouseButtons.Right)
  326. {
  327. #region Network DNS
  328. List<IPAddress> networkDnsAddresses = new List<IPAddress>();
  329. try
  330. {
  331. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  332. {
  333. if (nic.OperationalStatus != OperationalStatus.Up)
  334. continue;
  335. networkDnsAddresses.AddRange(nic.GetIPProperties().DnsAddresses);
  336. }
  337. }
  338. catch
  339. { }
  340. NetworkDnsMenuItem.DropDownItems.Clear();
  341. NetworkDnsMenuItem.DropDownItems.Add(DefaultNetworkDnsMenuItem);
  342. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  343. bool noItemChecked = true;
  344. DefaultNetworkDnsMenuItem.Checked = false;
  345. foreach (DnsProvider dnsProvider in _dnsProviders)
  346. {
  347. ToolStripMenuItem item = new ToolStripMenuItem(dnsProvider.Name);
  348. item.Tag = dnsProvider;
  349. item.Click += NetworkDnsMenuSubItem_Click;
  350. if (AddressExists(networkDnsAddresses, dnsProvider.Addresses))
  351. {
  352. item.Checked = true;
  353. noItemChecked = false;
  354. }
  355. NetworkDnsMenuItem.DropDownItems.Add(item);
  356. }
  357. if (noItemChecked)
  358. {
  359. foreach (IPAddress dnsAddress in networkDnsAddresses)
  360. {
  361. if (!dnsAddress.IsIPv6SiteLocal)
  362. {
  363. DefaultNetworkDnsMenuItem.Checked = true;
  364. break;
  365. }
  366. }
  367. }
  368. if (_dnsProviders.Count > 0)
  369. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  370. NetworkDnsMenuItem.DropDownItems.Add(ManageNetworkDnsMenuItem);
  371. #endregion
  372. #region service
  373. try
  374. {
  375. switch (_service.Status)
  376. {
  377. case ServiceControllerStatus.Stopped:
  378. DashboardMenuItem.Enabled = false;
  379. StartServiceMenuItem.Enabled = true;
  380. RestartServiceMenuItem.Enabled = false;
  381. StopServiceMenuItem.Enabled = false;
  382. break;
  383. case ServiceControllerStatus.Running:
  384. DashboardMenuItem.Enabled = true;
  385. StartServiceMenuItem.Enabled = false;
  386. RestartServiceMenuItem.Enabled = true;
  387. StopServiceMenuItem.Enabled = true;
  388. break;
  389. default:
  390. DashboardMenuItem.Enabled = false;
  391. StartServiceMenuItem.Enabled = false;
  392. RestartServiceMenuItem.Enabled = false;
  393. StopServiceMenuItem.Enabled = false;
  394. break;
  395. }
  396. ServiceMenuItem.Enabled = true;
  397. }
  398. catch
  399. {
  400. DashboardMenuItem.Enabled = false;
  401. ServiceMenuItem.Enabled = false;
  402. }
  403. #endregion
  404. #region auto start
  405. try
  406. {
  407. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  408. {
  409. if (key != null)
  410. {
  411. string autoStartPath = key.GetValue("Technitium DNS System Tray") as string;
  412. AutoStartMenuItem.Checked = (autoStartPath != null) && autoStartPath.Equals("\"" + Assembly.GetEntryAssembly().Location + "\"");
  413. }
  414. }
  415. }
  416. catch
  417. { }
  418. #endregion
  419. TrayIcon.ShowContextMenu();
  420. }
  421. }
  422. private void DashboardMenuItem_Click(object sender, EventArgs e)
  423. {
  424. int port = 5380;
  425. try
  426. {
  427. //try finding port number from dns config file
  428. string dnsConfigFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "config", "dns.config");
  429. using (FileStream fS = new FileStream(dnsConfigFile, FileMode.Open, FileAccess.Read))
  430. {
  431. BinaryReader bR = new BinaryReader(fS);
  432. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  433. throw new InvalidDataException("DnsServer config file format is invalid.");
  434. int version = bR.ReadByte();
  435. if (version > 1)
  436. {
  437. string serverDomain = bR.ReadShortString();
  438. port = bR.ReadInt32();
  439. }
  440. }
  441. }
  442. catch
  443. { }
  444. Process.Start("http://localhost:" + port.ToString());
  445. }
  446. private void DefaultNetworkDnsMenuItem_Click(object sender, EventArgs e)
  447. {
  448. if (!Program.IsAdmin)
  449. {
  450. Program.RunAsAdmin("--network-dns-default");
  451. return;
  452. }
  453. try
  454. {
  455. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  456. {
  457. if (nic.OperationalStatus != OperationalStatus.Up)
  458. continue;
  459. SetNameServerIPv6(nic, new IPAddress[] { });
  460. try
  461. {
  462. IPInterfaceProperties properties = nic.GetIPProperties();
  463. if (properties.GetIPv4Properties().IsDhcpEnabled)
  464. {
  465. SetNameServerIPv4(nic, new IPAddress[] { });
  466. }
  467. else if (properties.GatewayAddresses.Count > 0)
  468. {
  469. SetNameServerIPv4(nic, new IPAddress[] { properties.GatewayAddresses[0].Address });
  470. }
  471. else
  472. {
  473. SetNameServerIPv4(nic, new IPAddress[] { });
  474. }
  475. }
  476. catch (NetworkInformationException)
  477. { }
  478. }
  479. MessageBox.Show("The network DNS servers were set to default successfully.", "Default DNS Set - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  480. }
  481. catch (Exception ex)
  482. {
  483. MessageBox.Show("Error occured while setting default network DNS servers. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  484. }
  485. }
  486. private void ManageNetworkDnsMenuItem_Click(object sender, EventArgs e)
  487. {
  488. if (!Program.IsAdmin)
  489. {
  490. Program.RunAsAdmin("--network-dns-manage");
  491. return;
  492. }
  493. using (frmManageDnsProviders frm = new frmManageDnsProviders(_dnsProviders))
  494. {
  495. if (frm.ShowDialog() == DialogResult.OK)
  496. {
  497. _dnsProviders.Clear();
  498. _dnsProviders.AddRange(frm.DnsProviders);
  499. _dnsProviders.Sort();
  500. SaveConfig();
  501. }
  502. }
  503. }
  504. private void NetworkDnsMenuSubItem_Click(object sender, EventArgs e)
  505. {
  506. ToolStripMenuItem item = sender as ToolStripMenuItem;
  507. DnsProvider dnsProvider = item.Tag as DnsProvider;
  508. if (!Program.IsAdmin)
  509. {
  510. Program.RunAsAdmin("--network-dns-item " + dnsProvider.Name);
  511. return;
  512. }
  513. try
  514. {
  515. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  516. {
  517. if (nic.OperationalStatus != OperationalStatus.Up)
  518. continue;
  519. IPInterfaceProperties properties = nic.GetIPProperties();
  520. if ((properties.DnsAddresses.Count > 0) && !properties.DnsAddresses[0].IsIPv6SiteLocal)
  521. SetNameServer(nic, dnsProvider.Addresses);
  522. }
  523. MessageBox.Show("The network DNS servers were set to " + dnsProvider.Name + " successfully.", dnsProvider.Name + " Configured - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  524. }
  525. catch (Exception ex)
  526. {
  527. MessageBox.Show("Error occured while setting " + dnsProvider.Name + " as network DNS server. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  528. }
  529. }
  530. private void StartServiceMenuItem_Click(object sender, EventArgs e)
  531. {
  532. if (!Program.IsAdmin)
  533. {
  534. Program.RunAsAdmin("--service-start");
  535. return;
  536. }
  537. try
  538. {
  539. _service.Start();
  540. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  541. MessageBox.Show("The service was started successfully.", "Service Started - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  542. }
  543. catch (System.ServiceProcess.TimeoutException ex)
  544. {
  545. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  546. }
  547. catch (Exception ex)
  548. {
  549. MessageBox.Show("Error occured while starting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  550. }
  551. }
  552. private void RestartServiceMenuItem_Click(object sender, EventArgs e)
  553. {
  554. if (!Program.IsAdmin)
  555. {
  556. Program.RunAsAdmin("--service-restart");
  557. return;
  558. }
  559. try
  560. {
  561. _service.Stop();
  562. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  563. _service.Start();
  564. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  565. MessageBox.Show("The service was restarted successfully.", "Service Restarted - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  566. }
  567. catch (System.ServiceProcess.TimeoutException ex)
  568. {
  569. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  570. }
  571. catch (Exception ex)
  572. {
  573. MessageBox.Show("Error occured while restarting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  574. }
  575. }
  576. private void StopServiceMenuItem_Click(object sender, EventArgs e)
  577. {
  578. if (!Program.IsAdmin)
  579. {
  580. Program.RunAsAdmin("--service-stop");
  581. return;
  582. }
  583. try
  584. {
  585. _service.Stop();
  586. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  587. MessageBox.Show("The service was stopped successfully.", "Service Stopped - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  588. }
  589. catch (System.ServiceProcess.TimeoutException ex)
  590. {
  591. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  592. }
  593. catch (Exception ex)
  594. {
  595. MessageBox.Show("Error occured while stopping service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  596. }
  597. }
  598. private void AboutMenuItem_Click(object sender, EventArgs e)
  599. {
  600. using (frmAbout frm = new frmAbout())
  601. {
  602. frm.ShowDialog();
  603. }
  604. }
  605. private void AutoStartMenuItem_Click(object sender, EventArgs e)
  606. {
  607. if (AutoStartMenuItem.Checked)
  608. {
  609. //remove
  610. try
  611. {
  612. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  613. {
  614. if (key != null)
  615. key.DeleteValue("Technitium DNS System Tray", false);
  616. }
  617. }
  618. catch (Exception ex)
  619. {
  620. MessageBox.Show("Error occured while removing auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  621. }
  622. }
  623. else
  624. {
  625. //add
  626. try
  627. {
  628. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  629. {
  630. if (key != null)
  631. key.SetValue("Technitium DNS System Tray", "\"" + Assembly.GetEntryAssembly().Location + "\"", RegistryValueKind.String);
  632. }
  633. }
  634. catch (Exception ex)
  635. {
  636. MessageBox.Show("Error occured while adding auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  637. }
  638. }
  639. }
  640. private void ExitMenuItem_Click(object sender, EventArgs e)
  641. {
  642. if (MessageBox.Show(Resources.AreYouSureYouWantToQuit, Resources.Quit + " - " + Resources.ServiceName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
  643. Application.Exit();
  644. }
  645. #endregion
  646. }
  647. }