MainApplicationContext.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2022 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. case "--first-run":
  88. bool usingLoopbackAsDns = false;
  89. try
  90. {
  91. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  92. {
  93. if (nic.OperationalStatus != OperationalStatus.Up)
  94. continue;
  95. foreach (IPAddress dnsAddress in nic.GetIPProperties().DnsAddresses)
  96. {
  97. if (IPAddress.IsLoopback(dnsAddress))
  98. {
  99. usingLoopbackAsDns = true;
  100. break;
  101. }
  102. }
  103. if (usingLoopbackAsDns)
  104. break;
  105. }
  106. }
  107. catch
  108. { }
  109. if (!usingLoopbackAsDns && MessageBox.Show("Do you want to update this computer's network connections to use the locally running Technitium DNS Server?\r\n\r\nNote! It is recommended that you use the locally running Technitium DNS Server unless you explicitly want to keep using your existing network DNS configuration.", "Switch Network DNS? - Technitium DNS Server", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  110. SetNetworkDns(new DnsProvider("Technitium", new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }));
  111. break;
  112. }
  113. }
  114. }
  115. #endregion
  116. #region IDisposable
  117. protected override void Dispose(bool disposing)
  118. {
  119. if (disposing)
  120. {
  121. TrayIcon?.Dispose();
  122. }
  123. base.Dispose(disposing);
  124. }
  125. #endregion
  126. #region private
  127. private void InitializeComponent()
  128. {
  129. //
  130. // TrayIconContextMenu
  131. //
  132. TrayIconContextMenu = new ContextMenuStrip();
  133. TrayIconContextMenu.SuspendLayout();
  134. //
  135. // TrayIcon
  136. //
  137. TrayIcon = new NotifyIcon();
  138. TrayIcon.Icon = Resources.logo2;
  139. TrayIcon.Visible = true;
  140. TrayIcon.MouseUp += TrayIcon_MouseUp;
  141. TrayIcon.ContextMenuStrip = TrayIconContextMenu;
  142. TrayIcon.Text = Resources.ServiceName;
  143. //
  144. // DashboardMenuItem
  145. //
  146. DashboardMenuItem = new ToolStripMenuItem();
  147. DashboardMenuItem.Name = "DashboardMenuItem";
  148. DashboardMenuItem.Text = Resources.DashboardMenuItem;
  149. DashboardMenuItem.Click += DashboardMenuItem_Click;
  150. //
  151. // NetworkDnsMenuItem
  152. //
  153. NetworkDnsMenuItem = new ToolStripMenuItem();
  154. NetworkDnsMenuItem.Name = "NetworkDnsMenuItem";
  155. NetworkDnsMenuItem.Text = Resources.NetworkDnsMenuItem;
  156. DefaultNetworkDnsMenuItem = new ToolStripMenuItem("Default");
  157. DefaultNetworkDnsMenuItem.Click += DefaultNetworkDnsMenuItem_Click;
  158. ManageNetworkDnsMenuItem = new ToolStripMenuItem("Manage");
  159. ManageNetworkDnsMenuItem.Click += ManageNetworkDnsMenuItem_Click;
  160. //
  161. // ServiceMenuItem
  162. //
  163. ServiceMenuItem = new ToolStripMenuItem();
  164. ServiceMenuItem.Name = "ServiceMenuItem";
  165. ServiceMenuItem.Text = Resources.ServiceMenuItem;
  166. StartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStartMenuItem);
  167. StartServiceMenuItem.Click += StartServiceMenuItem_Click;
  168. RestartServiceMenuItem = new ToolStripMenuItem(Resources.ServiceRestartMenuItem);
  169. RestartServiceMenuItem.Click += RestartServiceMenuItem_Click;
  170. StopServiceMenuItem = new ToolStripMenuItem(Resources.ServiceStopMenuItem);
  171. StopServiceMenuItem.Click += StopServiceMenuItem_Click;
  172. ServiceMenuItem.DropDownItems.AddRange(new ToolStripItem[]
  173. {
  174. StartServiceMenuItem,
  175. RestartServiceMenuItem,
  176. StopServiceMenuItem
  177. });
  178. //
  179. // AboutMenuItem
  180. //
  181. AboutMenuItem = new ToolStripMenuItem();
  182. AboutMenuItem.Name = "AboutMenuItem";
  183. AboutMenuItem.Text = Resources.AboutMenuItem;
  184. AboutMenuItem.Click += AboutMenuItem_Click;
  185. //
  186. // AutoStartMenuItem
  187. //
  188. AutoStartMenuItem = new ToolStripMenuItem();
  189. AutoStartMenuItem.Name = "AutoStartMenuItem";
  190. AutoStartMenuItem.Text = "&Auto Start Icon";
  191. AutoStartMenuItem.Click += AutoStartMenuItem_Click;
  192. //
  193. // ExitMenuItem
  194. //
  195. ExitMenuItem = new ToolStripMenuItem();
  196. ExitMenuItem.Name = "ExitMenuItem";
  197. ExitMenuItem.Text = Resources.ExitMenuItem;
  198. ExitMenuItem.Click += ExitMenuItem_Click;
  199. TrayIconContextMenu.Items.AddRange(new ToolStripItem[]
  200. {
  201. DashboardMenuItem,
  202. new ToolStripSeparator(),
  203. NetworkDnsMenuItem,
  204. ServiceMenuItem,
  205. AboutMenuItem,
  206. new ToolStripSeparator(),
  207. AutoStartMenuItem,
  208. ExitMenuItem
  209. });
  210. TrayIconContextMenu.ResumeLayout(false);
  211. }
  212. private void LoadConfig()
  213. {
  214. try
  215. {
  216. using (FileStream fS = new FileStream(_configFile, FileMode.Open, FileAccess.Read))
  217. {
  218. BinaryReader bR = new BinaryReader(fS);
  219. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DT")
  220. throw new InvalidDataException("Invalid DNS Server System Tray App config file format.");
  221. switch (bR.ReadByte())
  222. {
  223. case 1:
  224. int count = bR.ReadInt32();
  225. _dnsProviders.Clear();
  226. for (int i = 0; i < count; i++)
  227. _dnsProviders.Add(new DnsProvider(bR));
  228. _dnsProviders.Sort();
  229. break;
  230. default:
  231. throw new NotSupportedException("DNS Server System Tray App config file format is not supported.");
  232. }
  233. }
  234. }
  235. catch (FileNotFoundException)
  236. {
  237. _dnsProviders.Clear();
  238. _dnsProviders.AddRange(DnsProvider.GetDefaultProviders());
  239. _dnsProviders.Sort();
  240. }
  241. catch (Exception ex)
  242. {
  243. MessageBox.Show("Error occured while loading config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  244. }
  245. }
  246. private void SaveConfig()
  247. {
  248. try
  249. {
  250. using (FileStream fS = new FileStream(_configFile, FileMode.Create, FileAccess.Write))
  251. {
  252. BinaryWriter bW = new BinaryWriter(fS);
  253. bW.Write(Encoding.ASCII.GetBytes("DT"));
  254. bW.Write((byte)1);
  255. bW.Write(_dnsProviders.Count);
  256. foreach (DnsProvider dnsProvider in _dnsProviders)
  257. dnsProvider.WriteTo(bW);
  258. }
  259. }
  260. catch (Exception ex)
  261. {
  262. MessageBox.Show("Error occured while saving config file. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  263. }
  264. }
  265. private static void SetNetworkDns(DnsProvider dnsProvider)
  266. {
  267. if (!Program.IsAdmin)
  268. {
  269. Program.RunAsAdmin("--network-dns-item " + dnsProvider.Name);
  270. return;
  271. }
  272. try
  273. {
  274. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  275. {
  276. if (nic.OperationalStatus != OperationalStatus.Up)
  277. continue;
  278. IPInterfaceProperties properties = nic.GetIPProperties();
  279. if ((properties.DnsAddresses.Count > 0) && !properties.DnsAddresses[0].IsIPv6SiteLocal)
  280. SetNameServer(nic, dnsProvider.Addresses);
  281. }
  282. MessageBox.Show("The network DNS servers were set to " + dnsProvider.Name + " successfully.", dnsProvider.Name + " Configured - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  283. }
  284. catch (Exception ex)
  285. {
  286. MessageBox.Show("Error occured while setting " + dnsProvider.Name + " as network DNS server. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  287. }
  288. }
  289. private static void SetNameServer(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  290. {
  291. SetNameServerIPv4(nic, dnsAddresses);
  292. SetNameServerIPv6(nic, dnsAddresses);
  293. }
  294. private static void SetNameServerIPv4(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  295. {
  296. ManagementClass networkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
  297. ManagementObjectCollection instances = networkAdapterConfig.GetInstances();
  298. foreach (ManagementObject obj in instances)
  299. {
  300. if ((bool)obj["IPEnabled"] && obj["SettingID"].Equals(nic.Id))
  301. {
  302. List<string> dnsServers = new List<string>();
  303. foreach (IPAddress dnsAddress in dnsAddresses)
  304. {
  305. if (dnsAddress.AddressFamily != AddressFamily.InterNetwork)
  306. continue;
  307. dnsServers.Add(dnsAddress.ToString());
  308. }
  309. ManagementBaseObject objParameter = obj.GetMethodParameters("SetDNSServerSearchOrder");
  310. objParameter["DNSServerSearchOrder"] = dnsServers.ToArray();
  311. ManagementBaseObject response = obj.InvokeMethod("SetDNSServerSearchOrder", objParameter, null);
  312. uint returnValue = (uint)response.GetPropertyValue("ReturnValue");
  313. switch (returnValue)
  314. {
  315. case 0: //success
  316. case 1: //reboot required
  317. break;
  318. case 64:
  319. throw new Exception("Method not supported on this platform. WMI error code: " + returnValue);
  320. case 65:
  321. throw new Exception("Unknown failure. WMI error code: " + returnValue);
  322. case 70:
  323. throw new Exception("Invalid IP address. WMI error code: " + returnValue);
  324. case 96:
  325. throw new Exception("Unable to notify DNS service. WMI error code: " + returnValue);
  326. case 97:
  327. throw new Exception("Interface not configurable. WMI error code: " + returnValue);
  328. default:
  329. throw new Exception("WMI error code: " + returnValue);
  330. }
  331. break;
  332. }
  333. }
  334. }
  335. private static void SetNameServerIPv6(NetworkInterface nic, ICollection<IPAddress> dnsAddresses)
  336. {
  337. //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\{}
  338. string nameServer = null;
  339. foreach (IPAddress dnsAddress in dnsAddresses)
  340. {
  341. if (dnsAddress.AddressFamily != AddressFamily.InterNetworkV6)
  342. continue;
  343. if (nameServer == null)
  344. nameServer = dnsAddress.ToString();
  345. else
  346. nameServer += "," + dnsAddress.ToString();
  347. }
  348. if (nameServer == null)
  349. nameServer = "";
  350. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\" + nic.Id, true))
  351. {
  352. if (key != null)
  353. key.SetValue("NameServer", nameServer, RegistryValueKind.String);
  354. }
  355. }
  356. private static bool AddressExists(ICollection<IPAddress> checkAddresses, ICollection<IPAddress> addresses)
  357. {
  358. foreach (IPAddress checkAddress in checkAddresses)
  359. {
  360. foreach (IPAddress address in addresses)
  361. {
  362. if (checkAddress.Equals(address))
  363. return true;
  364. }
  365. }
  366. return false;
  367. }
  368. private void TrayIcon_MouseUp(object sender, MouseEventArgs e)
  369. {
  370. if (e.Button == MouseButtons.Right)
  371. {
  372. #region Network DNS
  373. List<IPAddress> networkDnsAddresses = new List<IPAddress>();
  374. try
  375. {
  376. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  377. {
  378. if (nic.OperationalStatus != OperationalStatus.Up)
  379. continue;
  380. networkDnsAddresses.AddRange(nic.GetIPProperties().DnsAddresses);
  381. }
  382. }
  383. catch
  384. { }
  385. NetworkDnsMenuItem.DropDownItems.Clear();
  386. NetworkDnsMenuItem.DropDownItems.Add(DefaultNetworkDnsMenuItem);
  387. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  388. bool noItemChecked = true;
  389. DefaultNetworkDnsMenuItem.Checked = false;
  390. foreach (DnsProvider dnsProvider in _dnsProviders)
  391. {
  392. ToolStripMenuItem item = new ToolStripMenuItem(dnsProvider.Name);
  393. item.Tag = dnsProvider;
  394. item.Click += NetworkDnsMenuSubItem_Click;
  395. if (AddressExists(networkDnsAddresses, dnsProvider.Addresses))
  396. {
  397. item.Checked = true;
  398. noItemChecked = false;
  399. }
  400. NetworkDnsMenuItem.DropDownItems.Add(item);
  401. }
  402. if (noItemChecked)
  403. {
  404. foreach (IPAddress dnsAddress in networkDnsAddresses)
  405. {
  406. if (!dnsAddress.IsIPv6SiteLocal)
  407. {
  408. DefaultNetworkDnsMenuItem.Checked = true;
  409. break;
  410. }
  411. }
  412. }
  413. if (_dnsProviders.Count > 0)
  414. NetworkDnsMenuItem.DropDownItems.Add(new ToolStripSeparator());
  415. NetworkDnsMenuItem.DropDownItems.Add(ManageNetworkDnsMenuItem);
  416. #endregion
  417. #region service
  418. try
  419. {
  420. _service.Refresh();
  421. switch (_service.Status)
  422. {
  423. case ServiceControllerStatus.Stopped:
  424. DashboardMenuItem.Enabled = false;
  425. StartServiceMenuItem.Enabled = true;
  426. RestartServiceMenuItem.Enabled = false;
  427. StopServiceMenuItem.Enabled = false;
  428. break;
  429. case ServiceControllerStatus.Running:
  430. DashboardMenuItem.Enabled = true;
  431. StartServiceMenuItem.Enabled = false;
  432. RestartServiceMenuItem.Enabled = true;
  433. StopServiceMenuItem.Enabled = true;
  434. break;
  435. default:
  436. DashboardMenuItem.Enabled = false;
  437. StartServiceMenuItem.Enabled = false;
  438. RestartServiceMenuItem.Enabled = false;
  439. StopServiceMenuItem.Enabled = false;
  440. break;
  441. }
  442. ServiceMenuItem.Enabled = true;
  443. }
  444. catch
  445. {
  446. DashboardMenuItem.Enabled = false;
  447. ServiceMenuItem.Enabled = false;
  448. }
  449. #endregion
  450. #region auto start
  451. try
  452. {
  453. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  454. {
  455. if (key != null)
  456. {
  457. string autoStartPath = key.GetValue("Technitium DNS System Tray") as string;
  458. AutoStartMenuItem.Checked = (autoStartPath != null) && autoStartPath.Equals("\"" + Program.APP_PATH + "\"");
  459. }
  460. }
  461. }
  462. catch
  463. { }
  464. #endregion
  465. TrayIcon.ShowContextMenu();
  466. }
  467. }
  468. private void DashboardMenuItem_Click(object sender, EventArgs e)
  469. {
  470. int port = 5380;
  471. try
  472. {
  473. //try finding port number from dns config file
  474. string dnsConfigFile = Path.Combine(Path.GetDirectoryName(Program.APP_PATH), "config", "dns.config");
  475. using (FileStream fS = new FileStream(dnsConfigFile, FileMode.Open, FileAccess.Read))
  476. {
  477. BinaryReader bR = new BinaryReader(fS);
  478. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  479. throw new InvalidDataException("DnsServer config file format is invalid.");
  480. int version = bR.ReadByte();
  481. if (version > 1)
  482. {
  483. string serverDomain = bR.ReadShortString();
  484. port = bR.ReadInt32();
  485. }
  486. }
  487. }
  488. catch
  489. { }
  490. ProcessStartInfo processInfo = new ProcessStartInfo("http://localhost:" + port.ToString());
  491. processInfo.UseShellExecute = true;
  492. processInfo.Verb = "open";
  493. Process.Start(processInfo);
  494. }
  495. private void DefaultNetworkDnsMenuItem_Click(object sender, EventArgs e)
  496. {
  497. if (!Program.IsAdmin)
  498. {
  499. Program.RunAsAdmin("--network-dns-default");
  500. return;
  501. }
  502. try
  503. {
  504. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  505. {
  506. if (nic.OperationalStatus != OperationalStatus.Up)
  507. continue;
  508. SetNameServerIPv6(nic, Array.Empty<IPAddress>());
  509. try
  510. {
  511. IPInterfaceProperties properties = nic.GetIPProperties();
  512. if (properties.GetIPv4Properties().IsDhcpEnabled)
  513. {
  514. SetNameServerIPv4(nic, Array.Empty<IPAddress>());
  515. }
  516. else if (properties.GatewayAddresses.Count > 0)
  517. {
  518. SetNameServerIPv4(nic, new IPAddress[] { properties.GatewayAddresses[0].Address });
  519. }
  520. else
  521. {
  522. SetNameServerIPv4(nic, Array.Empty<IPAddress>());
  523. }
  524. }
  525. catch (NetworkInformationException)
  526. { }
  527. }
  528. MessageBox.Show("The network DNS servers were set to default successfully.", "Default DNS Set - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  529. }
  530. catch (Exception ex)
  531. {
  532. MessageBox.Show("Error occured while setting default network DNS servers. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  533. }
  534. }
  535. private void ManageNetworkDnsMenuItem_Click(object sender, EventArgs e)
  536. {
  537. if (!Program.IsAdmin)
  538. {
  539. Program.RunAsAdmin("--network-dns-manage");
  540. return;
  541. }
  542. using (frmManageDnsProviders frm = new frmManageDnsProviders(_dnsProviders))
  543. {
  544. if (frm.ShowDialog() == DialogResult.OK)
  545. {
  546. _dnsProviders.Clear();
  547. _dnsProviders.AddRange(frm.DnsProviders);
  548. _dnsProviders.Sort();
  549. SaveConfig();
  550. }
  551. }
  552. }
  553. private void NetworkDnsMenuSubItem_Click(object sender, EventArgs e)
  554. {
  555. ToolStripMenuItem item = sender as ToolStripMenuItem;
  556. DnsProvider dnsProvider = item.Tag as DnsProvider;
  557. SetNetworkDns(dnsProvider);
  558. }
  559. private void StartServiceMenuItem_Click(object sender, EventArgs e)
  560. {
  561. if (!Program.IsAdmin)
  562. {
  563. Program.RunAsAdmin("--service-start");
  564. return;
  565. }
  566. try
  567. {
  568. _service.Start();
  569. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  570. MessageBox.Show("The service was started successfully.", "Service Started - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  571. }
  572. catch (System.ServiceProcess.TimeoutException ex)
  573. {
  574. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  575. }
  576. catch (Exception ex)
  577. {
  578. MessageBox.Show("Error occured while starting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  579. }
  580. }
  581. private void RestartServiceMenuItem_Click(object sender, EventArgs e)
  582. {
  583. if (!Program.IsAdmin)
  584. {
  585. Program.RunAsAdmin("--service-restart");
  586. return;
  587. }
  588. try
  589. {
  590. _service.Stop();
  591. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  592. _service.Start();
  593. _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  594. MessageBox.Show("The service was restarted successfully.", "Service Restarted - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  595. }
  596. catch (System.ServiceProcess.TimeoutException ex)
  597. {
  598. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  599. }
  600. catch (Exception ex)
  601. {
  602. MessageBox.Show("Error occured while restarting service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  603. }
  604. }
  605. private void StopServiceMenuItem_Click(object sender, EventArgs e)
  606. {
  607. if (!Program.IsAdmin)
  608. {
  609. Program.RunAsAdmin("--service-stop");
  610. return;
  611. }
  612. try
  613. {
  614. _service.Stop();
  615. _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, SERVICE_WAIT_TIMEOUT_SECONDS));
  616. MessageBox.Show("The service was stopped successfully.", "Service Stopped - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  617. }
  618. catch (System.ServiceProcess.TimeoutException ex)
  619. {
  620. MessageBox.Show("The service did not respond in time." + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  621. }
  622. catch (Exception ex)
  623. {
  624. MessageBox.Show("Error occured while stopping service. " + ex.Message, "Service Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  625. }
  626. }
  627. private void AboutMenuItem_Click(object sender, EventArgs e)
  628. {
  629. using (frmAbout frm = new frmAbout())
  630. {
  631. frm.ShowDialog();
  632. }
  633. }
  634. private void AutoStartMenuItem_Click(object sender, EventArgs e)
  635. {
  636. if (AutoStartMenuItem.Checked)
  637. {
  638. //remove
  639. try
  640. {
  641. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  642. {
  643. if (key != null)
  644. key.DeleteValue("Technitium DNS System Tray", false);
  645. }
  646. }
  647. catch (Exception ex)
  648. {
  649. MessageBox.Show("Error occured while removing auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  650. }
  651. }
  652. else
  653. {
  654. //add
  655. try
  656. {
  657. using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
  658. {
  659. if (key != null)
  660. key.SetValue("Technitium DNS System Tray", "\"" + Program.APP_PATH + "\"", RegistryValueKind.String);
  661. }
  662. }
  663. catch (Exception ex)
  664. {
  665. MessageBox.Show("Error occured while adding auto start registry entry. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error);
  666. }
  667. }
  668. }
  669. private void ExitMenuItem_Click(object sender, EventArgs e)
  670. {
  671. if (MessageBox.Show(Resources.AreYouSureYouWantToQuit, Resources.Quit + " - " + Resources.ServiceName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
  672. Application.Exit();
  673. }
  674. #endregion
  675. }
  676. }