private void ConnectClientInternalMenuItem_Click(object sender, EventArgs e) { ToolStripItem s = sender as ToolStripItem; RemoteMachine node = Ping.RemoteMachines[s.Tag.ToString()]; Process.Start("mstsc", "/v:" + node.lanip); }
private void ConnectClientMenuItem_Click(object sender, EventArgs e) { ToolStripItem s = sender as ToolStripItem; string host = s.Tag.ToString(); setHostBlueDot(host); RemoteMachine node = Ping.RemoteMachines[host]; Process.Start("mstsc", "/v:" + node.wanip + ":" + node.port); }
private async void RandomizePortMenuItem_Click(object sender, EventArgs e) { ToolStripItem s = sender as ToolStripItem; string host = s.Tag.ToString(); setHostBlueDot(host); RemoteMachine node = Ping.RemoteMachines[host]; await PingRequest.SendCommandToTargetAsync(node.host, "randomize"); timerTickAsync(null, null); }
public async System.Threading.Tasks.Task <dynamic> SendAsync(INatDevice Router, string ApiKey, string Key) { try { this.ExternalIP = Router.GetExternalIP().ToString(); } catch (Exception exc) { Debug.WriteLine(exc.Message); this.ExternalIP = ""; } string Hostname = Dns.GetHostName(); this.IsPortMapped = StaticHelpers.isPortMappedOnRouter(Router); ManagementObject os = new ManagementObject("Win32_OperatingSystem=@"); string serial = (string)os["SerialNumber"]; var values = new Dictionary <string, string> { { "status", IsPortMapped ? "open" : "closed" }, { "rdpopen", StaticHelpers.isRDPAvailable() ? "1" : "0" }, { "wanip", this.ExternalIP != null ? this.ExternalIP : "" }, { "lanip", StaticHelpers.GetInternalIP() }, { "port", Registry.Get("Port") }, { "host", Hostname }, { "interval", Registry.Get("Interval") }, { "lifetime", Registry.Get("PortLifetime") }, { "version", StaticHelpers.GetVersion() }, { "guid", serial }, { "serviceinstalled", StaticHelpers.IsServiceInstalled().ToString() }, { "servicerunning", StaticHelpers.IsServiceRunning().ToString() } }; var serializer = new JavaScriptSerializer(); var content = new FormUrlEncodedContent(new Dictionary <string, string> { { "hostid", StaticHelpers.GetHostHash(Hostname) }, { "apikey", ApiKey }, { "payload", Harpocrates.Engine.Encrypt(serializer.Serialize(values), Key) } }); // HttpWebRequest request = WebRequest.Create(Endpoint) as HttpWebRequest; // request.Proxy = new WebProxy(MyProxyHostString, MyProxyPort); // Send the API call HttpClient client = new HttpClient(); dynamic response = await client.PostAsync(Endpoint, content); // Parse out the account TTL header IEnumerable <string> ttls; if (response.Headers.TryGetValues("ttl", out ttls)) { foreach (string ttl in ttls) { this.LifeTime = Int32.Parse(ttl); } } // Parse out version header IEnumerable <string> versions; if (response.Headers.TryGetValues("version", out versions)) { foreach (string version in versions) { this.Version = version; } } this.CommandWasProcessed = ProcessCommandHeader(Router, response, Key); // Create the machines List string responseString = await response.Content.ReadAsStringAsync(); List <Dictionary <string, string> > RemoteMachinesRaw = new JavaScriptSerializer().Deserialize <List <Dictionary <string, string> > >(responseString); // If there was some error parsing the json, just quit here... if (RemoteMachinesRaw == null) { return(response); } foreach (var a in RemoteMachinesRaw) { RemoteMachineImportJson parsed; // First try to decrypt one return parameter for this machine // If decryption fails then other machine probably has different key try { string payloadDecrypted = Harpocrates.Engine.Decrypt(a["payload"], Key); parsed = serializer.Deserialize <RemoteMachineImportJson>(payloadDecrypted); } catch { continue; } RemoteMachine x = new RemoteMachine(); x.wanip = parsed.wanip; x.lanip = parsed.lanip; x.host = parsed.host; x.port = Int32.Parse(parsed.port); x.pending = Convert.ToBoolean(Convert.ToInt32(a["pending"])); x.rdpopen = Convert.ToBoolean(Convert.ToInt32(parsed.rdpopen)); x.status = parsed.status; x.version = parsed.version; x.interval = Int32.Parse(parsed.interval); x.lifetime = Int32.Parse(parsed.lifetime); x.guid = parsed.guid; x.servicerunning = Boolean.Parse(parsed.servicerunning); x.serviceinstalled = Boolean.Parse(parsed.serviceinstalled); RemoteMachines.Add(x.host, x); } return(response); }
private ToolStripMenuItem CreateHostMenuItem(string Name, RemoteMachine x) { ToolStripMenuItem HostMenuItem = new ToolStripMenuItem(); HostMenuItem.Text = x.host; HostMenuItem.Name = Name; if (x.pending) { HostMenuItem.Image = Properties.Resources.bullet_blue; } else if (x.wanip == "") { HostMenuItem.Image = Properties.Resources.bullet_red; HostMenuItem.ToolTipText = "Host error: could not configure router"; } else if (x.rdpopen == false) { HostMenuItem.Image = Properties.Resources.bullet_yellow; HostMenuItem.ToolTipText = "Host error: RDP service not listening on this host"; } else if (x.status == "open") { HostMenuItem.Image = Properties.Resources.bullet_green; } else { HostMenuItem.Image = Properties.Resources.bullet_grey; } HostMenuItem.Tag = x.host; if (x.status == "closed") { ToolStripMenuItem OpenPortMenuItem = new ToolStripMenuItem(); OpenPortMenuItem.Text = "Open Port"; OpenPortMenuItem.Tag = x.host; OpenPortMenuItem.Click += new EventHandler(OpenPortMenuItem_Click); HostMenuItem.DropDownItems.Add(OpenPortMenuItem); } if (x.status == "open" && x.rdpopen == true) { ToolStripMenuItem ConnectClientMenuItem = new ToolStripMenuItem(); ConnectClientMenuItem.Text = "Launch RDP"; ConnectClientMenuItem.Tag = x.host; ConnectClientMenuItem.Click += new EventHandler(ConnectClientMenuItem_Click); if (x.host == Dns.GetHostName() || x.wanip == this.ExternalIp) { ConnectClientMenuItem.ToolTipText = "Computer can not connect to itself."; ConnectClientMenuItem.Enabled = false; } if (x.wanip == "") { ConnectClientMenuItem.ToolTipText = "Remote computer could not determine WAN IP address."; ConnectClientMenuItem.Enabled = false; } HostMenuItem.DropDownItems.Add(ConnectClientMenuItem); } if (x.rdpopen == true) { ToolStripMenuItem LaunchRDPInternalMenuItem = new ToolStripMenuItem(); LaunchRDPInternalMenuItem.Text = "Launch RDP [internal]"; // If this machine is the one the user is on disable it... if (x.host == Dns.GetHostName() || x.wanip != this.ExternalIp) { LaunchRDPInternalMenuItem.ToolTipText = "Computer can not connect to itself."; LaunchRDPInternalMenuItem.Enabled = false; } LaunchRDPInternalMenuItem.Tag = x.host; LaunchRDPInternalMenuItem.Click += new EventHandler(ConnectClientInternalMenuItem_Click); HostMenuItem.DropDownItems.Add(LaunchRDPInternalMenuItem); } if (x.status == "open") { ToolStripMenuItem ClosePortMenuItem = new ToolStripMenuItem(); ClosePortMenuItem.Text = "Close Port"; ClosePortMenuItem.Tag = x.host; ClosePortMenuItem.Click += new EventHandler(ClosePortMenuItem_Click); HostMenuItem.DropDownItems.Add(ClosePortMenuItem); } ToolStripMenuItem HostPortSettingsMenuItem = new ToolStripMenuItem(); HostPortSettingsMenuItem.Text = "Port Settings"; HostMenuItem.DropDownItems.Add(HostPortSettingsMenuItem); ToolStripMenuItem RandomizePortMenuItem = new ToolStripMenuItem(); RandomizePortMenuItem.Text = "Randomize Port"; RandomizePortMenuItem.Tag = x.host; RandomizePortMenuItem.Click += new EventHandler(RandomizePortMenuItem_Click); HostPortSettingsMenuItem.DropDownItems.Add(RandomizePortMenuItem); ToolStripMenuItem PortSetManualMenuItem = new ToolStripMenuItem(); PortSetManualMenuItem.Text = "Choose Port"; PortSetManualMenuItem.Tag = x.host; PortSetManualMenuItem.Click += delegate(Object sender1, EventArgs ee) { PortSelect ps = new PortSelect(); ps.numPort.Value = x.port; ps.ShowDialog(); PingRequest.SendCommandToTargetAsync(x.host, "port", ps.numPort.Value.ToString()); timerTickAsync(null, null); }; HostPortSettingsMenuItem.DropDownItems.Add(PortSetManualMenuItem); ToolStripMenuItem HostPortLifetimeSelectMenuItem = new ToolStripMenuItem(); HostPortLifetimeSelectMenuItem.Text = "Lifetime"; HostPortLifetimeSelectMenuItem.Tag = x.host; HostPortSettingsMenuItem.DropDownItems.Add(HostPortLifetimeSelectMenuItem); foreach (KeyValuePair <int, string> Life in this.Lifetimes) { ToolStripMenuItem i = new ToolStripMenuItem(); i.Text = Life.Value; if (Life.Key == x.lifetime) { i.Checked = true; } i.Click += delegate(Object sender1, EventArgs ee) { ToolStripMenuItem s = sender1 as ToolStripMenuItem; PingRequest.SendCommandToTargetAsync(x.host, "lifetime", Life.Key.ToString()); timerTickAsync(null, null); }; HostPortLifetimeSelectMenuItem.DropDownItems.Add(i); } ToolStripMenuItem MachineIntervalMenuItem = new ToolStripMenuItem(); MachineIntervalMenuItem.Text = "Ping Interval"; HostMenuItem.DropDownItems.Add(MachineIntervalMenuItem); foreach (KeyValuePair <int, string> Ping in this.PingsIntervals) { ToolStripMenuItem i = new ToolStripMenuItem(); i.Text = Ping.Value; i.Tag = Ping.Key; if (Ping.Key == x.interval) { i.Checked = true; } i.Click += delegate(Object sender1, EventArgs ee) { ToolStripMenuItem s = sender1 as ToolStripMenuItem; PingRequest.SendCommandToTargetAsync(x.host, "interval", Ping.Key.ToString()); timerTickAsync(null, null); }; MachineIntervalMenuItem.DropDownItems.Add(i); } ToolStripMenuItem TestCommandMenuItem = new ToolStripMenuItem(); TestCommandMenuItem.Text = "Test Command Bus"; TestCommandMenuItem.Tag = x.host; TestCommandMenuItem.Click += new EventHandler(SendTestCommand); HostMenuItem.DropDownItems.Add(TestCommandMenuItem); HostMenuItem.DropDownItems.Add("-"); ToolStripMenuItem MachineStatusMenuItem = new ToolStripMenuItem(); MachineStatusMenuItem.Text = "Machine Information"; MachineStatusMenuItem.Tag = x.host; MachineStatusMenuItem.Width = 400; HostMenuItem.DropDownItems.Add(MachineStatusMenuItem); int width = 300; Font f = new Font("Consolas", 9); MachineStatusMenuItem.DropDownItems.AddRange(new ToolStripItem[] { new ToolStripLabel { Text = "Host Name : " + x.host, Width = width, Font = f }, new ToolStripLabel { Text = "Machine GUID : " + x.guid, Width = width, Font = f }, new ToolStripLabel { Text = "External IP : " + x.wanip, Width = width, Font = f }, new ToolStripLabel { Text = "Internal IP : " + x.lanip, Width = width, Font = f }, new ToolStripLabel { Text = "Mapped Port : " + x.port, Width = width, Font = f }, new ToolStripLabel { Text = "Interval : " + x.interval + " Seconds", Width = width, Font = f }, new ToolStripLabel { Text = "Version : " + x.version, Width = width, Font = f }, new ToolStripLabel { Text = "Port Lifetime : " + x.lifetime + " Minutes", Width = width, Font = f }, new ToolStripLabel { Text = "Port Status : " + x.status, Width = width, Font = f }, new ToolStripLabel { Text = "Service Installed : " + x.serviceinstalled, Width = width, Font = f }, new ToolStripLabel { Text = "Service Running : " + x.servicerunning, Width = width, Font = f } }); return(HostMenuItem); }
public async void timerTickAsync(object sender, EventArgs e) { Console.WriteLine("The timer ticked at {0:HH:mm:ss.fff}", DateTime.UtcNow); // Get some basic settings items out of the registry // which are required to make an API ping call string Key = Registry.Get("Key"); string ApiKey = Registry.Get("ApiKey"); string Interval = Registry.Get("Interval"); // Protect application from crashing when important // settings values can not be found. if (ApiKey == "" || Interval == "" || Key == "") { return; } string host = Dns.GetHostName(); // Reset timer interval incase it was changed in the settings this.loopTimer.Interval = Int32.Parse(Interval) * 1000; // If the router object is still being found, skip this ping if (Router == null) { this.TitleMenuItem.Image = Properties.Resources.bullet_yellow; this.TitleMenuItem.ToolTipText = "Your router does not seem to support all required features."; } else { this.TitleMenuItem.ToolTipText = ""; } // Do something if the failed number of ping attempts is to high if (this.FailedPings > 3) { this.TitleMenuItem.Image = Properties.Resources.bullet_red; } else { this.TitleMenuItem.Image = Properties.Resources.bullet_green; } dynamic response; Ping = new PingRequest(); try { response = await Ping.SendAsync(Router, ApiKey, Key); } catch (Exception exc) { Console.WriteLine(exc.Message); this.FailedPings++; return; } // Check with router to see if port is open // This allows the system to detect if port is still forwarded from a previous try { Mapping RoutedPort = this.Router.GetSpecificMapping(Protocol.Tcp, Int32.Parse(Registry.Get("Port"))); } catch (Exception exc) { } this.isPortOpen = Ping.IsPortMapped; // If account is good, make menu header icon green if (Ping.LifeTime > 0) { this.TitleMenuItem.Image = Properties.Resources.bullet_green; this.TitleMenuItem.ToolTipText = String.Format("Your API key is valid for {0} more days", Ping.LifeTime / (60 * 60 * 24)); } // Display the update available menu item if update is available try { this.UpdateAvailableMenuItem.Visible = Ping.Version != null && Ping.Version != StaticHelpers.GetVersion(); } catch (Exception exc) { Console.WriteLine(exc.Message); } // Keep running list of discovered machines, so that expired ones can be removed after List <string> machineList = new List <string>(); if (Ping.RemoteMachines != null) { foreach (KeyValuePair <string, RemoteMachine> b in Ping.RemoteMachines) { RemoteMachine x = b.Value; string menukey = "menu___" + x.host; machineList.Add(menukey); // Remove any existing machine from the tray icon in a thread-safe way if (TrayIconContextMenu.InvokeRequired) { TrayIconContextMenu.Invoke(new MethodInvoker(delegate { TrayIconContextMenu.Items.RemoveByKey(menukey); })); } else { TrayIconContextMenu.Items.RemoveByKey(menukey); } ToolStripMenuItem HostMenuItem = this.CreateHostMenuItem(menukey, x); // Add the menu item thread-safely if (TrayIconContextMenu.InvokeRequired) { TrayIconContextMenu.Invoke(new MethodInvoker(delegate { this.TrayIconContextMenu.Items.Insert(2, HostMenuItem); })); } else { this.TrayIconContextMenu.Items.Insert(2, HostMenuItem); } } } List <string> removedMenuNames = new List <string>(); // Remove expired entries foreach (var b in this.TrayIconContextMenu.Items) { ToolStripMenuItem test = b as ToolStripMenuItem; if (test != null && test.Name.Contains("menu___") && !machineList.Contains(test.Name)) { removedMenuNames.Add(test.Name); } } foreach (string removedMenuName in removedMenuNames) { this.TrayIconContextMenu.Items.RemoveByKey(removedMenuName); } // If this ping request resulted in commands which were processed, then a // new thread should run another ping request to send any updated status // back to the central server if (Ping.CommandWasProcessed == true) { new Thread(() => { Thread.CurrentThread.IsBackground = true; timerTickAsync(null, null); }).Start(); } // Refresh the interval value just incase it was changed this.SelectIntervalSetting(Int32.Parse(Registry.Get("Interval"))); // Once a ping sequence has been fully completed, reset the fails counter this.FailedPings = 0; }