MainApplicationContext.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2021 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.Diagnostics;
  20. using System.IO;
  21. using System.Management;
  22. using System.Net;
  23. using System.Net.NetworkInformation;
  24. using System.Net.Sockets;
  25. using System.ServiceProcess;
  26. using System.Text;
  27. using System.Windows.Forms;
  28. using TechnitiumLibrary.IO;
  29. namespace DnsServerSystemTrayApp
  30. {
  31. public class MainApplicationContext : ApplicationContext
  32. {
  33. #region variables
  34. const int SERVICE_WAIT_TIMEOUT_SECONDS = 30;
  35. private readonly ServiceController _service = new ServiceController("DnsService");
  36. readonly string _configFile;
  37. readonly List<DnsProvider> _dnsProviders = new List<DnsProvider>();
  38. private NotifyIcon TrayIcon;
  39. private ContextMenuStrip TrayIconContextMenu;
  40. private ToolStripMenuItem DashboardMenuItem;
  41. private ToolStripMenuItem NetworkDnsMenuItem;
  42. private ToolStripMenuItem DefaultNetworkDnsMenuItem;
  43. private ToolStripMenuItem ManageNetworkDnsMenuItem;
  44. private ToolStripMenuItem ServiceMenuItem;
  45. private ToolStripMenuItem StartServiceMenuItem;
  46. private ToolStripMenuItem RestartServiceMenuItem;
  47. private ToolStripMenuItem StopServiceMenuItem;
  48. private ToolStripMenuItem AboutMenuItem;
  49. private ToolStripMenuItem AutoStartMenuItem;
  50. private ToolStripMenuItem ExitMenuItem;
  51. #endregion
  52. #region constructor
  53. public MainApplicationContext(string configFile, string[] args)
  54. {
  55. _configFile = configFile;
  56. LoadConfig();
  57. InitializeComponent();
  58. if (args.Length > 0)
  59. {
  60. switch (args[0])
  61. {
  62. case "--network-dns-default":
  63. DefaultNetworkDnsMenuItem_Click(this, EventArgs.Empty);
  64. break;
  65. case "--network-dns-item":
  66. foreach (DnsProvider dnsProvider in _dnsProviders)
  67. {
  68. if (dnsProvider.Name.Equals(args[1]))
  69. {
  70. NetworkDnsMenuSubItem_Click(new ToolStripMenuItem(dnsProvider.Name) { Tag = dnsProvider }, EventArgs.Empty);
  71. break;
  72. }
  73. }
  74. break;
  75. case "--network-dns-manage":
  76. ManageNetworkDnsMenuItem_Click(this, EventArgs.Empty);
  77. break;
  78. case "--service-start":
  79. StartServiceMenuItem_Click(this, EventArgs.Empty);
  80. break;
  81. case "--service-restart":
  82. RestartServiceMenuItem_Click(this, EventArgs.Empty);
  83. break;
  84. case "--service-stop":
  85. StopServiceMenuItem_Click(this, EventArgs.Empty);
  86. break;
  87. }
  88. }
  89. }
  90. #endregion
  91. #region IDisposable
  92. protected override void Dispose(bool disposing)
  93. {
  94. if (disposing)
  95. {
  96. TrayIcon?.Dispose();
  97. }
  98. base.Dispose(disposing);
  99. }
  100. #endregion
  101. #region private
  102. private void InitializeComponent()
  103. {
  104. //
  105. // TrayIconContextMenu
  106. //
  107. TrayIconContextMenu = new ContextMenuStrip();
  108. TrayIconContextMenu.SuspendLayout();
  109. //
  110. // TrayIcon
  111. //
  112. TrayIcon = new NotifyIcon();
  113. TrayIcon.Icon = Resources.logo2;
  114. TrayIcon.Visible = true;
  115. TrayIcon.MouseUp += TrayIcon_MouseUp;
  116. TrayIcon.ContextMenuStrip = TrayIconContextMenu;
  117. TrayIcon.Text = Resources.ServiceName;
  118. //
  119. // DashboardMenuItem
  120. //
  121. DashboardMenuItem = new ToolStripMenuItem();
  122. DashboardMenuItem.Name = "DashboardMenuItem";
  123. DashboardMenuItem.Text = Resources.DashboardMenuItem;
  124. DashboardMenuItem.Click += DashboardMenuItem_Click;
  125. //
  126. // NetworkDnsMenuItem
  127. //
  128. NetworkDnsMenuItem = new ToolStripMenuItem();
  129. NetworkDnsMenuItem.Name = "NetworkDnsMenuItem";
  130. NetworkDnsMenuItem.Text = Resources.NetworkDnsMenuItem;
  131. DefaultNetworkDnsMenuItem = new ToolStripMenuItem("Default");
  132. DefaultNetworkDnsMenuItem.Click += DefaultNetworkDnsMenuItem_Click;
  133. ManageNetworkDnsMenuItem = new ToolStripMenuItem("Manage");
  134. ManageNetworkDnsMenuItem.Click += ManageNetworkDnsMenuItem_Click;
  135. //
  136. // ServiceMenuItem
  137. //
  138. ServiceMenuItem = new ToolStripMenuItem();
  139. ServiceMenuItem.Name = "ServiceMenuItem";
  140. ServiceMenuItem.Text = Resources.ServiceMenuItem;
  141. StartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStartMenuItem);
  142. StartServiceMenuItem.Click += StartServiceMenuItem_Click;
  143. RestartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceRestartMenuItem);
  144. RestartServiceMenuItem.Click += RestartServiceMenuItem_Click;
  145. StopServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStopMenuItem);
  146. StopServiceMenuItem.Click += StopServiceMenuItem_Click;
  147. ServiceMenuItem.DropDownItems.AddRange(new ToolStripItem[]
  148. {
  149. StartServiceMenuItem,
  150. RestartServiceMenuItem,
  151. StopServiceMenuItem
  152. });
  153. //
  154. // AboutMenuItem
  155. //
  156. AboutMenuItem = new ToolStripMenuItem();
  157. AboutMenuItem.Name = "AboutMenuItem";
  158. AboutMenuItem.Text = Resources.AboutMenuItem;
  159. AboutMenuItem.Click += AboutMenuItem_Click;
  160. //
  161. // AutoStartMenuItem
  162. //
  163. AutoStartMenuItem = new ToolStripMenuItem();
  164. AutoStartMenuItem.Name = "AutoStartMenuItem";
  165. AutoStartMenuItem.Text = "&Auto Start Icon";
  166. AutoStartMenuItem.Click += AutoStartMenuItem_Click;
  167. //
  168. // ExitMenuItem
  169. //
  170. ExitMenuItem = new ToolStripMenuItem();
  171. ExitMenuItem.Name = "ExitMenuItem";
  172. ExitMenuItem.Text = Resources.ExitMenuItem;
  173. ExitMenuItem.Click += ExitMenuItem_Click;
  174. TrayIconContextMenu.Items.AddRange(new ToolStripItem[]
  175. {
  176. DashboardMenuItem,
  177. new ToolStripSeparator(),
  178. NetworkDnsMenuItem,
  179. ServiceMenuItem,
  180. AboutMenuItem,
  181. new ToolStripSeparator(),
  182. AutoStartMenuItem,
  183. ExitMenuItem
  184. });
  185. TrayIconContextMenu.ResumeLayout(false);
  186. }
  187. private void LoadConfig()
  188. {
  189. try
  190. {
  191. using (FileStream fS = new FileStream(_configFile, FileMode.Open, FileAccess.Read))
  192. {
  193. BinaryReader bR = new BinaryReader(fS);
  194. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DT")
  195. throw new InvalidDataException("Invalid DNS Server System Tray App config file format.");
  196. switch (bR.ReadByte())
  197. {
  198. case 1:
  199. int count = bR.ReadInt32();
  200. _dnsProviders.Clear();
  201. for (int i = 0; i < count; i++)
  202. _dnsProviders.Add(new DnsProvider(bR));
  203. _dnsProviders.Sort();
  204. break;
  205. default:
  206. throw new NotSupportedException("DNS Server System Tray App config file format is not supported.");
  207. }
  208. }
  209. }
  210. catch (FileNotFoundException)
  211. {
  212. _dnsProviders.Clear();
  213. _dnsProviders.AddRange(DnsProvider.GetDefaultProviders());
  214. _dnsProviders.Sort();
  215. }
  216. catch (Exception ex)
  217. {
  218. MessageBox.Show("Error occured while loading config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  219. }
  220. }
  221. private void SaveConfig()
  222. {
  223. try
  224. {
  225. using (FileStream fS = new FileStream(_configFile, FileMode.Create, FileAccess.Write))
  226. {
  227. BinaryWriter bW = new BinaryWriter(fS);
  228. bW.Write(Encoding.ASCII.GetBytes("DT"));
  229. bW.Write((byte)1);
  230. bW.Write(_dnsProviders.Count);
  231. foreach (DnsProvider dnsProvider in _dnsProviders)
  232. dnsProvider.WriteTo(bW);
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. MessageBox.Show("Error occured while saving config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  238. }
  239. }
  240. private static void SetNameServer(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  241. {
  242. SetNameServerIPv4(nic, dnsAddresses);
  243. SetNameServerIPv6(nic, dnsAddresses);
  244. }
  245. private static void SetNameServerIPv4(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  246. {
  247. ManagementClass networkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
  248. ManagementObjectCollection instances = networkAdapterConfig.GetInstances();
  249. foreach (ManagementObject obj in instances)
  250. {
  251. if ((bool)obj["IPEnabled"] && obj["SettingID"].Equals(nic.Id))
  252. {
  253. List<string> dnsServers = new List<string>();
  254. foreach (IPAddress dnsAddress in dnsAddresses)
  255. {
  256. if (dnsAddress.AddressFamily != AddressFamily.InterNetwork)
  257. continue;
  258. dnsServers.Add(dnsAddress.ToString());
  259. }
  260. ManagementBaseObject objParameter = obj.GetMethodParameters("SetDNSServerSearchOrder");
  261. objParameter["DNSServerSearchOrder"] = dnsServers.ToArray();
  262. ManagementBaseObject response = obj.InvokeMethod("SetDNSServerSearchOrder", objParameter, null);
  263. uint returnValue = (uint)response.GetPropertyValue("ReturnValue");
  264. switch (returnValue)
  265. {
  266. case 0: //success
  267. case 1: //reboot required
  268. break;
  269. case 64:
  270. throw new Exception("Method not supported on this platform. WMI error code: " + returnValue);
  271. case 65:
  272. throw new Exception("Unknown failure. WMI error code: " + returnValue);
  273. case 70:
  274. throw new Exception("Invalid IP address. WMI error code: " + returnValue);
  275. case 96:
  276. throw new Exception("Unable to notify DNS service. WMI error code: " + returnValue);
  277. case 97:
  278. throw new Exception("Interface not configurable. WMI error code: " + returnValue);
  279. default:
  280. throw new Exception("WMI error code: " + returnValue);
  281. }
  282. break;
  283. }
  284. }
  285. }
  286. private static void SetNameServerIPv6(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  287. {
  288. //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\{}
  289. string nameServer = null;
  290. foreach (IPAddress dnsAddress in dnsAddresses)
  291. {
  292. if (dnsAddress.AddressFamily != AddressFamily.InterNetworkV6)
  293. continue;
  294. if (nameServer == null)
  295. nameServer = dnsAddress.ToString();
  296. else
  297. nameServer += "," + dnsAddress.ToString();
  298. }
  299. if (nameServer == null)
  300. nameServer = "";
  301. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\" + nic.Id, true))
  302. {
  303. if (key != null)
  304. key.SetValue("NameServer", nameServer, RegistryValueKind.String);
  305. }
  306. }
  307. private static bool AddressExists(ICollection<IPAddress> checkAddresses, ICollection<IPAddress> addresses)
  308. {
  309. foreach (IPAddress checkAddress in checkAddresses)
  310. {
  311. foreach (IPAddress address in addresses)
  312. {
  313. if (checkAddress.Equals(address))
  314. return true;
  315. }
  316. }
  317. return false;
  318. }
  319. private void TrayIcon_MouseUp(object sender, MouseEventArgs e)
  320. {
  321. if (e.Button == MouseButtons.Right)
  322. {
  323. #region Network DNS
  324. List<IPAddress> networkDnsAddresses = new List<IPAddress>();
  325. try
  326. {
  327. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  328. {
  329. if (nic.OperationalStatus != OperationalStatus.Up)
  330. continue;
  331. networkDnsAddresses.AddRange(nic.GetIPProperties().DnsAddresses);
  332. }
  333. }
  334. catch
  335. { }
  336. NetworkDnsMenuItem.DropDownItems.Clear();
  337. NetworkDnsMenuItem.DropDownItems.Add(DefaultNetworkDnsMenuItem);
  338. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  339. bool noItemChecked = true;
  340. DefaultNetworkDnsMenuItem.Checked = false;
  341. foreach (DnsProvider dnsProvider in _dnsProviders)
  342. {
  343. ToolStripMenuItem item = new ToolStripMenuItem(dnsProvider.Name);
  344. item.Tag = dnsProvider;
  345. item.Click += NetworkDnsMenuSubItem_Click;
  346. if (AddressExists(networkDnsAddresses, dnsProvider.Addresses))
  347. {
  348. item.Checked = true;
  349. noItemChecked = false;
  350. }
  351. NetworkDnsMenuItem.DropDownItems.Add(item);
  352. }
  353. if (noItemChecked)
  354. {
  355. foreach (IPAddress dnsAddress in networkDnsAddresses)
  356. {
  357. if (!dnsAddress.IsIPv6SiteLocal)
  358. {
  359. DefaultNetworkDnsMenuItem.Checked = true;
  360. break;
  361. }
  362. }
  363. }
  364. if (_dnsProviders.Count > 0)
  365. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  366. NetworkDnsMenuItem.DropDownItems.Add(ManageNetworkDnsMenuItem);
  367. #endregion
  368. #region service
  369. try
  370. {
  371. _service.Refresh();
  372. switch (_service.Status)
  373. {
  374. case ServiceControllerStatus.Stopped:
  375. DashboardMenuItem.Enabled = false;
  376. StartServiceMenuItem.Enabled = true;
  377. RestartServiceMenuItem.Enabled = false;
  378. StopServiceMenuItem.Enabled = false;
  379. break;
  380. case ServiceControllerStatus.Running:
  381. DashboardMenuItem.Enabled = true;
  382. StartServiceMenuItem.Enabled = false;
  383. RestartServiceMenuItem.Enabled = true;
  384. StopServiceMenuItem.Enabled = true;
  385. break;
  386. default:
  387. DashboardMenuItem.Enabled = false;
  388. StartServiceMenuItem.Enabled = false;
  389. RestartServiceMenuItem.Enabled = false;
  390. StopServiceMenuItem.Enabled = false;
  391. break;
  392. }
  393. ServiceMenuItem.Enabled = true;
  394. }
  395. catch
  396. {
  397. DashboardMenuItem.Enabled = false;
  398. ServiceMenuItem.Enabled = false;
  399. }
  400. #endregion
  401. #region auto start
  402. try
  403. {
  404. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  405. {
  406. if (key != null)
  407. {
  408. string autoStartPath = key.GetValue("Technitium DNS System Tray") as string;
  409. AutoStartMenuItem.Checked = (autoStartPath != null) && autoStartPath.Equals("\"" + Program.APP_PATH + "\"");
  410. }
  411. }
  412. }
  413. catch
  414. { }
  415. #endregion
  416. TrayIcon.ShowContextMenu();
  417. }
  418. }
  419. private void DashboardMenuItem_Click(object sender, EventArgs e)
  420. {
  421. int port = 5380;
  422. try
  423. {
  424. //try finding port number from dns config file
  425. string dnsConfigFile = Path.Combine(Path.GetDirectoryName(Program.APP_PATH), "config", "dns.config");
  426. using (FileStream fS = new FileStream(dnsConfigFile, FileMode.Open, FileAccess.Read))
  427. {
  428. BinaryReader bR = new BinaryReader(fS);
  429. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  430. throw new InvalidDataException("DnsServer config file format is invalid.");
  431. int version = bR.ReadByte();
  432. if (version > 1)
  433. {
  434. string serverDomain = bR.ReadShortString();
  435. port = bR.ReadInt32();
  436. }
  437. }
  438. }
  439. catch
  440. { }
  441. ProcessStartInfo processInfo = new ProcessStartInfo("http://localhost:" + port.ToString());
  442. processInfo.UseShellExecute = true;
  443. processInfo.Verb = "open";
  444. Process.Start(processInfo);
  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, Array.Empty<IPAddress>());
  460. try
  461. {
  462. IPInterfaceProperties properties = nic.GetIPProperties();
  463. if (properties.GetIPv4Properties().IsDhcpEnabled)
  464. {
  465. SetNameServerIPv4(nic, Array.Empty<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, Array.Empty<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", "\"" + Program.APP_PATH + "\"", 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. }