private void OnPingReply(PingReply reply, string ip) { if (reply != null && reply.Status == IPStatus.Success) { if (ResolveNames) { string name; try { IPHostEntry hostEntry = Dns.GetHostEntry(ip); name = hostEntry.HostName; Hosts.Add(name); } catch (SocketException ex) { Log.Logger.Error(ex, "SocketException"); name = "?"; } Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, reply.RoundtripTime); } else { Console.WriteLine("{0} is up: ({1} ms)", ip, reply.RoundtripTime); Hosts.Add(ip); } lock (lockObj) { upCount++; } } else if (reply == null) { Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip); } }
/// <summary> /// Scan only known Hosts. /// TODO: does currently not check the status /// </summary> public async void ScanARP() { IsAnalyzing = true; var l = GetAllDevicesOnLAN(); ScanProgress = 0; var his = l.Select(s => new HostInformation(s.Key.ToString()) { MAC = s.Value }); Hosts.Clear(); foreach (var h in his) { Hosts.Add(h); } UpdateClassCDummies(); if (Config.CheckInternet && CurrentNIC != null) { await CheckConnectivity(); } ScanProgress = 100; IsAnalyzing = false; OnPropertyChanged("HostsOnline"); OnPropertyChanged("ClassCDummies"); FireAllPropertiesChanged(); }
private void ReloadHosts() { // так делать не хорошо: var hosts = File.ReadAllLines(HostsPath, Encoding.UTF8).Select(str => str.Trim()).Where(str => str.Length > 0); foreach (var host in hosts) { try { var hostEntry = Dns.GetHostEntry(host); var ips = hostEntry.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork); if (ips.Any()) { var dnsvm = new DnsEntryViewModel { Hostname = host }; foreach (var ipAddress in ips) { dnsvm.IPAddresses.Add(ipAddress); } Hosts.Add(dnsvm); } } catch (SocketException) { } } }
/// <summary> /// Trata a operação de Adicionar Host /// </summary> private void adicionarToolStripMenuItem_Click(object sender, EventArgs e) { using (var hostAdd = new HostAddForm()) { var result = hostAdd.ShowDialog(this); switch (result) { case DialogResult.OK: // TODO: Validar se já existe Hosts.Add( new SNMPHost() { IP = hostAdd.IPAddr, Port = hostAdd.PortNum, Community = hostAdd.Community, Name = hostAdd.HostName } ); hostList_UpdateStatusBar(null, null); hostList.Focus(); break; case DialogResult.Cancel: // Faz nada não break; default: break; } } }
public static bool AddHost(string Name, string Address, string Port) { AddHostMux.WaitOne(); Host _Host = null; if (Hosts.Any(H => H.Name.Equals(Name)) == true) { _Host = Hosts.Where(H => H.Name == Name).Select(H => H).ToList()[0]; } try { if (_Host == null) { IPEndPointEx IPEndPoint = new IPEndPointEx(IPAddress.Parse(Address), int.Parse(Port)); IPEndPoint.LastSeen = DateTime.Now.ToString("HH:mm:ss tt"); _Host = new Host() { Name = Name }; App.Current.Dispatcher.Invoke((Action) delegate { if (Hosts.Any(H => H.Name.Equals(Name)) == false) { Hosts.Add(_Host); } if (_Host.Entries.Any(E => E.Equals(IPEndPoint)) == false) { _Host.Entries.Add(IPEndPoint); } }); } else { IPEndPointEx IPEndPoint = null; if (_Host.Entries.Any(E => E.Address.Equals(IPAddress.Parse(Address)) && E.Port.Equals(int.Parse(Port))) == true) { IPEndPoint = _Host.Entries.Where(E => E.Address.Equals(IPAddress.Parse(Address)) && E.Port.Equals(int.Parse(Port))).Select(H => H).ToList()[0]; IPEndPoint.LastSeen = DateTime.Now.ToString("HH:mm:ss tt"); } if (IPEndPoint == null) { IPEndPointEx NewIPEndPoint = new IPEndPointEx(IPAddress.Parse(Address), int.Parse(Port)); NewIPEndPoint.LastSeen = DateTime.Now.ToString("HH:mm:ss tt"); App.Current.Dispatcher.Invoke((Action) delegate { if (_Host.Entries.Any(E => E.Address == IPAddress.Parse(Address) && E.Port == int.Parse(Port) && E.LastSeen == NewIPEndPoint.LastSeen) == false) { _Host.Entries.Add(NewIPEndPoint); } }); } } } catch (Exception e) { System.Windows.MessageBox.Show(e.Message); } AddHostMux.ReleaseMutex(); return(true); }
/// <summary> /// Adds a host to <see cref="Hosts"/> if it doesn't already exist. /// </summary> /// <param name="host">The host to be added.</param> private void AddHost(string host) { if (!Hosts.Contains(host, StringComparer.InvariantCultureIgnoreCase)) { Hosts.Add(host); } }
public void AddTeacherToClass(Teacher teacher) { if (!Hosts.Contains(teacher)) { Hosts.Add(teacher); } }
private void UnknownDeviceFound(object sender, DeviceEventUnknownArgs e) { if (string.IsNullOrEmpty(e?.Data)) { return; } using TextReader textReader = new StringReader(e.Data); string line, location = null; while ((line = textReader.ReadLine()) != null) { if (!line.StartsWith("Location: ")) { continue; } location = line.Substring(10); break; } if (string.IsNullOrEmpty(location)) { return; } Uri uri = new Uri(location); HdHomeRunHost host = new HdHomeRunHost(); host.RestClient = new RestClient($"{uri.Scheme}://{uri.Host}:{uri.Port}"); host.RestClient.UseSystemTextJson(); RestRequest deviceRequest = new RestRequest(uri.AbsolutePath, DataFormat.Xml); IRestResponse deviceResponse = host.RestClient.Get(deviceRequest); if (!deviceResponse.IsSuccessful) { return; } const string regexPattern = "HDHomeRun/(\\d+).(\\d+)"; Regex regex = new Regex(regexPattern); if (!regex.IsMatch(deviceResponse.Server)) { return; } XmlDocument deviceDocument = new XmlDocument(); deviceDocument.LoadXml(deviceResponse.Content); XmlNamespaceManager nsmgr = new XmlNamespaceManager(deviceDocument.NameTable); nsmgr.AddNamespace("upnp", "urn:schemas-upnp-org:device-1-0"); XmlNode friendlyNameNode = deviceDocument.SelectSingleNode("//upnp:device//upnp:friendlyName", nsmgr); if (friendlyNameNode != null) { host.FriendlyName = friendlyNameNode.InnerText; } if (Hosts.Contains(host)) { return; } Hosts.Add(host); }
private void ReCalcHosts() { Hosts.Clear(); if (!IsBusy && Parsers != null && Urls != null) { var hostDistinct = Urls .Where(u => Helper.IsWellFormedUriString(u.Value, UriKind.Absolute)) .Select(u => new Uri(u.Value).Host) .Distinct() .ToArray(); //var hostToExclude = hostDistinct.Where(h1 => hostDistinct.Where(h2 => Helper.StringLikes(h1, Helper.GetDomainFromString(h2, true))).Count() > 1).ToArray(); //var hostToAdd = hostToExclude.Select(h => ("*"+Helper.GetDomainFromString(h, true)).Replace("**","*") ).Distinct().ToArray(); foreach (var sw in hostDistinct //.Except(hostToExclude) //.Concat(hostToAdd) //.Distinct() .OrderBy(i => i) .Select( host => new StringParserWrapper() { Value = host, IsItemEnabled = true, Parsers = this.Parsers, Parser = new Parser() { Url = host, Labels = Parsers.Labels }, Urls = new UrlCollection(Helper.GetSomeUrlsForHost(host, Urls, 10)) }) ) { Hosts.Add(sw); } //foreach (var sw in // Urls // .Select( // u => // Helper.GetDomainFromUrl(new Uri(u.Value), true) // //new Uri(u.Value).GetLeftPart(UriPartial.Authority) // ) // .Distinct() // .Select(host => new StringParserWrapper() // { // Value = host, // IsItemEnabled = true,//!Parsers.Parsers.Any(i2 => i2.Url == host), // Parser = new Parser() { Url = host, Labels = Parsers.Labels }, // Urls = new UrlCollection(Helper.GetSomeUrlsForHost(host, Urls, 10)) // })) // Hosts.Add(sw); } }
private void UpdateCans(IEnumerable <Common.Models.Can> cans) { Hosts.Clear(); cans.Run(can => Hosts.Add(can.HostName)); if (!String.IsNullOrEmpty(Settings.Default.LastHost)) { Hosts.Add(Settings.Default.LastHost); } }
private ConsulHostVm AddHost(string host) { var ret = new ConsulHostVm { Host = host, Services = new ObservableCollection <ConsulServiceVm>(), Title = host }; Hosts.Add(ret); return(ret); }
/// <summary> /// Remove hosts that have been on the demoted list for more /// than 120,000 milliseconds and add them to the available hosts list. /// </summary> internal static void ReleaseDemotedHosts(object state) { while (!DemotedHosts.IsEmpty) { if (DemotedHosts.TryPeek(out FailoverServer demotedServer) && demotedServer.DemotedTime.AddMilliseconds(DEMOTED_TIMEOUT) < DateTime.Now) { demotedServer.Attempted = false; Hosts?.Add(demotedServer); DemotedHosts.TryDequeue(out demotedServer); }
public void AddHost(HostConnection host) { _hostStates.TryAdd(host.Id, new HostState(host)); // This part of the code is not concurrent, but only ASP.NET uses concurrent calls, MVVM projects are not. // ASP.NET don't use ObservableCollections if (_useObservableCollections) { Hosts.Add(new ObservableHost(GetHostState(host.Id))); } }
public void AddHost(Host host) { if (host is null) { throw new ArgumentNullException(nameof(host)); } else { decimal maxhost = Math.Ceiling((decimal)Route.Distance / _perkmforhost); if (Hosts.Count < maxhost) { Hosts.Add(host); } } }
public void StartSearchHosts() { _lanClient.StartListeningBroadcast(); _hostsSearchSubscription = _lanClient.TcpClientEventSubject.AsObservable() .TakeUntil(_destroy) .Where(tcpEvent => tcpEvent.Type == TcpEventType.ReceiveData) .Where(tcpEvent => tcpEvent.Data != null) .Where(tcpEvent => ((Packet)tcpEvent.Data).MessageType == MunchkinMessageType.HostFound) .Finally(() => _gameLogger.Debug("Game host observable end.")) .Select(tcpEvent => { var packet = (Packet)tcpEvent.Data; var position = 3; var host = new MunchkinHost(); host.IpAddress = packet.SenderIpAdress; host.Id = Encoding.UTF8.GetString(packet.Buffer, position + 1, packet.Buffer[position]); position += packet.Buffer[position]; position++; host.Name = Encoding.UTF8.GetString(packet.Buffer, position + 1, packet.Buffer[position]); position += packet.Buffer[position]; position++; host.Capacity = packet.Buffer[position++]; host.Fullness = packet.Buffer[position++]; _gameLogger.Debug($"GameClient: got new packet with ip [{packet.SenderIpAdress}]"); return(host); }) .Subscribe(host => { if (!Hosts.Any(h => h.Id == host.Id)) { _gameLogger.Debug($"GameClient: added new host name[{host.Name}]"); Hosts.Add(host); } else { var hostToUpdate = Hosts.First(h => h.Id == host.Id); hostToUpdate.Name = host.Name; hostToUpdate.Capacity = host.Capacity; hostToUpdate.Fullness = host.Fullness; } }); }
private void AddHost(Host host = null) { for (int i = 0; i < Hosts.Count; i++) { if (Hosts[i].IsNew) { return; } } host = host ?? new Host(); Debug.WriteLine("adding host " + host); HostViewModel hvm = new HostViewModel(host, this); hvm.IsNew = hvm.IsInEditMode = true; Hosts.Add(hvm); RaiseAllPropertiesChanged(); }
private void ReadCFG() { //should normally read a config file for entries. Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.5"), 3005)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.17"), 3005)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.2"), 3005)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); Hosts.Add(new IPEndPoint(System.Net.IPAddress.Parse("192.168.1.7"), 3333)); ListenStart = 3333; ListenEnd = 3335; ListenAdd = System.Net.IPAddress.Parse("192.168.1.7"); }
public void AddHost(object sender, HostEventArgs eventArgs) { Host host = eventArgs.Host; for (int i = 0; i < Hosts.Count(); i++) { if (host.IpAddress.Equals(Hosts[i].IpAddress) || host.MacAddress.Equals(Hosts[i].MacAddress)) { Hosts[i] = host; return; } } Hosts.Add(host); HostAdded?.Invoke(this, new HostEventArgs() { Host = host }); }
internal void CopyFrom(CalendarEvent calEvt) { Start = calEvt.DtStart.AsUtc; End = calEvt.DtEnd?.AsUtc ?? DateTime.MinValue.ToUniversalTime(); var hosts = HostRegex.Match(calEvt.Description).Groups[1].Value; foreach (Match match in MentionRegex.Matches(hosts)) { Hosts.Add(match.Groups[1].Value); } var titleMatch = TitleRegex.Match(calEvt.Summary); EventID = Convert.ToInt32(UidRegex.Match(calEvt.Uid).Groups[1].Value); UID = calEvt.Uid; TagPrimary = titleMatch.Groups[1].Value; TagSecondary = titleMatch.Groups[2].Value; Title = calEvt.Summary; RawTitle = calEvt.Summary; Description = DetailsRegex.Match(calEvt.Description).Groups[1].Value.Replace("\n\n", "\n").Trim(); if (Description == string.Empty) { Description = calEvt.Description.Replace("\n\n", "\n").Trim(); } LastRefresh = DateTime.UtcNow; if (TagPrimary != null) { Title = Title.Replace("[" + TagPrimary + "]", "").Trim(); } if (TagSecondary != null) { Title = Title.Replace("[" + TagSecondary + "]", "").Trim(); } }
/// <summary> /// Prepopulates the SftpConnectionPool with servers defined in config file. /// </summary> /// <param name="section"></param> public static void Load(XmlNode section) { try { DefaultConnectionLimit = int.Parse(section.SelectSingleNode("SftpConnectionPool").Attributes["defaultConnectionLimit"].Value); Trace.WriteLine("[SftpConnectionPool] DefaultConnectionLimit set to " + DefaultConnectionLimit.ToString()); foreach (XmlNode node in section.SelectNodes("SftpConnectionPool/Host")) { string name = node.Attributes["hostName"].Value; int connLimit = int.Parse(node.Attributes["connectionLimit"].Value); Hosts.Add(new SftpHost(name, connLimit, true)); Trace.WriteLine("[SftpConnectionPool] A limited connections(" + connLimit.ToString() + ") given to " + name + "."); } Trace.WriteLine("[SftpConnectionPool] SftpConnectionPool was loaded with " + Hosts.Count.ToString() + " hosts."); } catch (Exception e) { throw ExceptionHandling.HandleComponentException(System.Reflection.MethodBase.GetCurrentMethod(), new Exception("SftpConnectionPool Load Configuration failed", e)); } }
public void Add(string host) { // check is a valid host name if (!CheckHost(host)) { Msg.Instance.Show(Res.msg_host_invalid, true); return; } // is host already in list if (Hosts.Find(x => x.Host == host) != null) { Msg.Instance.Show(Res.msg_host_exist, true); return; } if (AddHost(host)) { Hosts.Add(new HostList(host)); } Msg.Instance.Show(Res.msg_host_add); }
/// <summary> /// Constructor. /// </summary> /// <param name="controller">The setup controller.</param> internal SetupClusterStatus(ISetupController controller) { Covenant.Requires <ArgumentNullException>(controller != null, nameof(controller)); this.isClone = false; this.controller = controller; this.cluster = controller.Get <ClusterProxy>(KubeSetupProperty.ClusterProxy); this.GlobalStatus = controller.GlobalStatus; this.globalStatus = this.GlobalStatus; // Initialize the cluster node/host status instances. this.Nodes = new List <SetupNodeStatus>(); foreach (var node in cluster.Nodes) { Nodes.Add(new SetupNodeStatus(node, node.NodeDefinition)); } this.Hosts = new List <SetupNodeStatus>(); foreach (var host in cluster.Hosts) { Hosts.Add(new SetupNodeStatus(host, new object())); } // Initialize the setup steps. this.Steps = new List <SetupStepStatus>(); foreach (var step in controller.GetStepStatus().Where(step => !step.IsQuiet)) { Steps.Add(step); } this.CurrentStep = Steps.SingleOrDefault(step => step.Number == controller.CurrentStepNumber); }
/// <summary> /// Performs the IP scan /// </summary> public async void ScanICMP() { IsAnalyzing = true; //set Class C grid to the right page ChangeClassCNetwork(Config.IPRangeStart.ToIP().ToLongNetwork().ToIP()); //fills the list of the Hosts with actual HostInformations for all IPs that are scanned for (long i = Config.IPRangeStart; i <= Config.IPRangeEnd; i++) { var hi = Hosts.FirstOrDefault(f => f.IP == i); if (hi == null) { hi = new HostInformation(i); hi.Pending = true; Hosts.Add(hi); } else { hi.Pending = true; } } //update the underlaying Hosts of the dummies UpdateClassCDummies(); //check internet if needed if (Config.CheckInternet && CurrentNIC != null) { await CheckConnectivity(); } int hostcount = Hosts.Where(w => w.Pending).Count(); int current = 0; int check = 1; while (check != 0 && !Stop) //as long there are unchecked IPs... { //grab a bunch of pending IPs List <HostInformation> z = Hosts.Where(w => w.Pending).Take(Config.MaxParallelConnections).ToList(); z.ForEach(e => e.Status = HostStatus.Checking); List <Task <HostInformation> > tasks = new List <Task <HostInformation> >(); foreach (var t in z) { tasks.Add(CheckHost(t, Config.PingTimeout)); } //and execute the scan for them Task.WaitAll(tasks.ToArray()); //invoke view update OnPropertyChanged("HostsOnline"); check = z.Count(); current += check; ScanProgress = ((double)current / (double)hostcount) * 100; //scroll the the next page on the Class C grid if needed if (Config.AutoScroll && check > 0 && z.FirstOrDefault() != null) { ChangeClassCNetwork(z.First().IP.ToIP().ToLongNetwork().ToIP()); } } //now get the MACs of all newly found Hosts and store them. Update RecentHosts as well. var l = GetAllDevicesOnLAN(); foreach (var d in l) { var f = Hosts.FirstOrDefault(a => a.IP == d.Key.ToLong()); if (f != null) { f.MAC = d.Value; } else { f = new HostInformation(d.Key.ToLong()) { MAC = d.Value }; Hosts.Add(f); } if (!Config.RecentHosts.Any(a => a.MAC.ToString() == f.MAC.ToString())) { Config.RecentHosts.Add(f); } } //reset Pending status and do cleanup foreach (var h in Hosts) { h.Pending = false; } ScanProgress = Stop ? 0 : 100; Stop = false; IsAnalyzing = false; FireAllPropertiesChanged(); }
/// <summary> /// This function scans a single host /// </summary> /// <param name="h">A WOL2Host containing the information /// required to scan a host.</param> /// <returns>True, if the host was successfully scanned.</returns> private bool ScanHost(WOL2Host h) { bool bRet = false; IPAddress ip = IPAddress.Parse(h.GetIpAddress()); byte[] buffer = new byte[32]; Ping myPing = new Ping(); PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(ip, m_iPingTimeout, buffer, pingOptions); // send the ping if (reply.Status == IPStatus.Success) { // Found a host // WOL2Host h = new WOL2Host(); try { h.SetIpAddress(ip.ToString()); h.SetMacAddress(WOL2DNSHelper.GetMACAddress(h.GetIpAddress())); h.SetName(Dns.GetHostEntry(h.GetIpAddress()).HostName); // ipv6 lookup string lookup = h.GetName(); string ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); if (ipv6 == null) { lookup = h.GetIpAddress(); ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); } if (ipv6 != null) { h.SetIpV6Address(ipv6); } // check if the hostname was found bool bAdd = true; if (m_bAddIfHostnameResolved) { bAdd = (h.GetIpAddress() != h.GetName()); } if (m_bAddIfMacResolved) { bAdd = (h.GetMacAddress().Length != 0); } if (bAdd) { Monitor.Enter(Hosts); Hosts.Add(h); Monitor.Exit(Hosts); } MOE.Logger.DoLog("ScanHost(): Found host: " + h + ". " + (bAdd ? "Adding it." : "Not adding it."), MOE.Logger.LogLevel.lvlInfo); bRet = bAdd; } catch (System.Net.Sockets.SocketException se) { MOE.Logger.DoLog(se.ToString(), MOE.Logger.LogLevel.lvlWarning); } catch (Exception ex) { MOE.Logger.DoLog(ex.ToString(), MOE.Logger.LogLevel.lvlWarning); } } MOE.Logger.DoLog("ScanHost(): finished job " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug); return(bRet); }
public HomeViewModel(AddNewHostViewModel addNewHostViewModel, IAppSettings appSettings, IMvxLogProvider mvxLogProvider) : base(appSettings, mvxLogProvider) { AddHostVM = addNewHostViewModel ?? throw new ArgumentNullException(); AddHostVM.HostInitialized += (s, e) => Hosts.Add(e); }