示例#1
0
 public Planet(int plntID, string hstSysName, char plntLtr,
               string plntName, DiscoveryMethod discMethd, float orbtPrd,
               float ParsDist, float tempKlvn, string discFclt)
 {
     PlanetID          = plntID;
     HostSystemName    = hstSysName;
     PlanetLetter      = plntLtr;
     PlanetName        = plntName;
     DiscoveryMethod   = discMethd;
     OrbitPeriodDays   = orbtPrd;
     ParsecsDistance   = ParsDist;
     TempInKelvins     = tempKlvn;
     DiscoveryFacility = discFclt;
 }
示例#2
0
        private void DiscoveryMethodsDropdown_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = (sender as ComboBox).SelectedItem;

            if (selectedItem != null)
            {
                DiscoveryMethod discoveryMethod = (DiscoveryMethod)selectedItem;
                ipAddressLabel.Visibility    = discoveryMethod == DiscoveryMethod.DirectedBroadcast ? Visibility.Visible : Visibility.Collapsed;
                ipAddressInput.Visibility    = discoveryMethod == DiscoveryMethod.DirectedBroadcast ? Visibility.Visible : Visibility.Collapsed;
                numberOfHopsLabel.Visibility = discoveryMethod == DiscoveryMethod.MulticastBroadcast ? Visibility.Visible : Visibility.Collapsed;
                numberOfHopsInput.Visibility = discoveryMethod == DiscoveryMethod.MulticastBroadcast ? Visibility.Visible : Visibility.Collapsed;
                subnetRangeLabel.Visibility  = discoveryMethod == DiscoveryMethod.SubnetSearch ? Visibility.Visible : Visibility.Collapsed;
                subnetRangeInput.Visibility  = discoveryMethod == DiscoveryMethod.SubnetSearch ? Visibility.Visible : Visibility.Collapsed;

                ResetDiscoveredPrinterData();
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            string ficheiro = Path.Combine(Environment.GetFolderPath(
                                               Environment.SpecialFolder.UserProfile),
                                           @"source\repos\lp2_exercicios\problemas\02\029.tsv");
            IEnumerable <Planet> planetEnumerable;

            planetEnumerable = PlanetLoader.LoadPlanets(ficheiro);

            int numberOfPlanets =
                (from plnt in planetEnumerable
                 select plnt
                ).Count();

            DiscoveryMethod prevalentDiscMethod =
                (from plnt in planetEnumerable
                 group plnt by plnt.DiscoveryMethod into plntGrp
                 orderby plntGrp.Count() descending
                 select plntGrp.Key
                ).First();

            int maxExoplanetsInSingleSystem =
                ((from plnt in planetEnumerable
                  group plnt by plnt.HostSystemName into plntNameGrp
                  orderby plntNameGrp.Count() descending
                  select plntNameGrp).First()
                ).Count();

            float averageOrbitalPeriod =
                (from plnt in planetEnumerable
                 select plnt.OrbitPeriodDays
                ).Average();

            Planet furthestPlanet =
                (from plnt in planetEnumerable
                 orderby plnt.ParsecsDistance descending
                 select plnt
                ).First();

            float avgTempInTwoPlusPlanetSys =
                (from plnt in planetEnumerable
                 where plnt.HostSystemName.Count() >= 2
                 group plnt by plnt.TempInKelvins into plntTempGrp
                 select plntTempGrp.Key
                ).Average();

            string facilityWithLeastDiscoveries =
                (from plnt in planetEnumerable
                 group plnt by plnt.DiscoveryFacility into plntDiscFclt
                 orderby plntDiscFclt.Count() ascending
                 select plntDiscFclt.Key
                ).First();

            Console.WriteLine($"Number of Planets: {numberOfPlanets}");
            Console.WriteLine($"Prevalent Discovery Method: " +
                              $"{prevalentDiscMethod}");
            Console.WriteLine($"Maximum Number of Exoplanets in a single " +
                              $"System: {maxExoplanetsInSingleSystem}");
            Console.WriteLine($"Average Orbital Period: " +
                              $"{averageOrbitalPeriod} days");
            Console.WriteLine($"Fursthest Exoplanet is " +
                              $"{furthestPlanet.PlanetName}, which is " +
                              $"{furthestPlanet.ParsecsDistance:f2} Parsecs away");
            Console.WriteLine($"Average Temperature of Exoplanets in " +
                              $"systems with two or more Exoplanets: " +
                              $"{avgTempInTwoPlusPlanetSys}");
            Console.WriteLine($"Facility with the least Discoveries: " +
                              $"{facilityWithLeastDiscoveries}");
        }
        /// <summary>
        /// Discover local peers using the provided <see cref="DiscoveryMethod"/> asynchronously. Makes a single async request 
        /// for peers to announce. Ensure that you append to the OnPeerDiscovered event to handle discovered peers. 
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod"></param>
        public static void DiscoverPeersAsync(DiscoveryMethod discoveryMethod)
        {
            if (!IsDiscoverable(discoveryMethod))
                throw new InvalidOperationException("Please ensure this peer is discoverable before attempting to discover other peers.");

            NetworkComms.CommsThreadPool.EnqueueItem(QueueItemPriority.Normal, (state) =>
                {
                    try
                    {
                        DiscoverPeers(discoveryMethod, 0);
                    }
                    catch (Exception) { }
                }, null);
        }
示例#5
0
 public IEnumerable<LocalNetworkMachine> GetLocalNetworkComputers(DiscoveryMethod method)
 {
     return null;
 }
 /// <summary>
 /// Discover local peers using the provided <see cref="DiscoveryMethod"/> and default discover time. Returns
 /// dictionary keyed on peer network identifier. IMPORTANT NOTE: For IP networks we strongly recommend using the UDP 
 /// broadcast discovery method.
 /// </summary>
 /// <param name="discoveryMethod">The <see cref="DiscoveryMethod"/> to use for discovering peers.</param>
 /// <returns></returns>
 public static Dictionary<ShortGuid, Dictionary<ConnectionType, List<EndPoint>>> DiscoverPeers(DiscoveryMethod discoveryMethod)
 {
     return DiscoverPeers(discoveryMethod, DefaultDiscoverTimeMS);
 }
        /// <summary>
        /// Discover local peers using the provided <see cref="DiscoveryMethod"/>. Returns
        /// dictionary keyed on peer network identifier. IMPORTANT NOTE: For IP networks we strongly recommend using the UDP 
        /// broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod">The <see cref="DiscoveryMethod"/> to use for discovering peers.</param>
        /// <param name="discoverTimeMS">The wait time, after all requests have been made, in milliseconds before all discovered peers are returned.</param>
        /// <returns></returns>
        public static Dictionary<ShortGuid, Dictionary<ConnectionType, List<EndPoint>>> DiscoverPeers(DiscoveryMethod discoveryMethod, int discoverTimeMS)
        {
            if (!IsDiscoverable(discoveryMethod))
                throw new InvalidOperationException("Please ensure this peer is discoverable before attempting to discover other peers.");

            Dictionary<ShortGuid, Dictionary<ConnectionType, List<EndPoint>>> result;
            lock (_discoverSyncRoot)
            {
                //Clear the discovered peers cache
                lock (_syncRoot)
                    _discoveredPeers = new Dictionary<ShortGuid, Dictionary<ConnectionType, Dictionary<EndPoint, DateTime>>>();

                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                    result = DiscoverPeersUDP(discoverTimeMS);
#if !NETFX_CORE && !WINDOWS_PHONE
                else if (discoveryMethod == DiscoveryMethod.TCPPortScan)
                    result = DiscoverPeersTCP(discoverTimeMS);
#endif
#if NET35 || NET4
                else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
                    result = DiscoverPeersBT(discoverTimeMS);
#endif
                else
                    throw new NotImplementedException("Peer discovery has not been implemented for the provided connection type.");
            }

            return result;
        }
 /// <summary>
 /// Returns the local endpoints that are currently used to make this peer discoverable using
 /// the provided <see cref="DiscoveryMethod"/>.
 /// </summary>
 /// <param name="discoveryMethod"></param>
 /// <returns></returns>
 public static List<EndPoint> LocalDiscoveryEndPoints(DiscoveryMethod discoveryMethod)
 {
     Dictionary<DiscoveryMethod, List<EndPoint>> result = LocalDiscoveryEndPoints();
     if (result.ContainsKey(discoveryMethod))
         return result[discoveryMethod];
     else
         return new List<EndPoint>();
 }
 /// <summary>
 /// Returns true if local discovery endPoints exist for the provided <see cref="DiscoveryMethod"/>.
 /// </summary>
 /// <param name="discoveryMethod"></param>
 /// <returns></returns>
 public static bool IsDiscoverable(DiscoveryMethod discoveryMethod)
 {
     return LocalDiscoveryEndPoints(discoveryMethod).Count > 0;
 }
        /// <summary>
        /// Disable this peers discoverable status for the provided <see cref="DiscoveryMethod"/>. 
        /// </summary>
        /// <param name="discoveryMethod">The <see cref="DiscoveryMethod"/> to disable discovery for.</param>
        public static void DisableDiscoverable(DiscoveryMethod discoveryMethod)
        {
#if !NETFX_CORE && !WINDOWS_PHONE
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
            {
                lock (_syncRoot)
                {
                    if (_discoveryListeners.ContainsKey(discoveryMethod))
                    {
                        Connection.StopListening(_discoveryListeners[discoveryMethod]);
                        _discoveryListeners.Remove(discoveryMethod);
                    }
                }
            }
#if NET35 || NET4
            else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
            {
                lock (_syncRoot)
                {
                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                        radio.Mode = RadioMode.Connectable;

                    if (_discoveryListeners.ContainsKey(discoveryMethod))
                    {
                        Connection.StopListening(_discoveryListeners[discoveryMethod]);
                        _discoveryListeners.Remove(discoveryMethod);
                    }
                }
            }
#endif
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod">The discovery method for which this peer should be discoverable</param>
        /// <param name="localDiscoveryEndPoint">The local endpoint with which to make this peer discoverable</param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod, EndPoint localDiscoveryEndPoint)
        {
#if !NETFX_CORE && !WINDOWS_PHONE
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
            {
                lock (_syncRoot)
                {
                    if (_discoveryListeners.ContainsKey(discoveryMethod))
                        return;

                    if (!HostInfo.IP.FilteredLocalAddresses().Contains((localDiscoveryEndPoint as IPEndPoint).Address))
                        throw new ArgumentException("Provided endpoint must use a valid local address", "localDiscoveryEndPoint");

                    if ((localDiscoveryEndPoint as IPEndPoint).Port == 0)
                    {
                        IPAddress address = (localDiscoveryEndPoint as IPEndPoint).Address;

                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }
                    else
                    {
                        //Based on the connection type select all local endPoints and then enable discoverable
                        ConnectionListenerBase listener;
                        if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                            listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                        else
                            listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                        Connection.StartListening(listener, localDiscoveryEndPoint);

                        //Once we are successfully listening we can break
                        _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                    }

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#if NET35 || NET4
            else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
            {
                lock (_syncRoot)
                {
                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                        if (radio.LocalAddress == (localDiscoveryEndPoint as BluetoothEndPoint).Address)
                            radio.Mode = RadioMode.Discoverable;

                    _discoveryListeners.Add(discoveryMethod, Connection.StartListening(ConnectionType.Bluetooth, localDiscoveryEndPoint, true));

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#endif
            else
                throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// Uses all suitable and allowed adaptors, e.g. for IP networks uses <see cref="HostInfo.IP.FilteredLocalAddresses()"/>.
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod"></param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod)
        {
            lock (_syncRoot)
            {
                if (_discoveryListeners.ContainsKey(discoveryMethod))
                    return;

                //Based on the connection type select all local endPoints and then enable discoverable
#if !NETFX_CORE && !WINDOWS_PHONE
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
                {
                    //We should select one of the target points across all adaptors, no need for all adaptors to have
                    //selected a single uniform port which is what happens if we just pass IPAddress.Any to the StartListening method
                    List<IPAddress> localAddresses = new List<IPAddress>();

                    if (ListenMode == LocalListenMode.EachAdaptorIndependently || ListenMode == LocalListenMode.Both)
                        localAddresses.AddRange(HostInfo.IP.FilteredLocalAddresses());

                    if (ListenMode == LocalListenMode.OnlyZeroAdaptor || ListenMode == LocalListenMode.Both)
                        localAddresses.Add(IPAddress.Any);

                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();
                    foreach (IPAddress address in localAddresses)
                    {
                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                listeners.Add(listener);
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }

                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#if NET35 || NET4
                else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
                {
                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();

                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                    {
                        radio.Mode = RadioMode.Discoverable;
                        listeners.AddRange(Connection.StartListening(ConnectionType.Bluetooth, new BluetoothEndPoint(radio.LocalAddress, BluetoothDiscoveryService), true));
                    }
                    
                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#endif
                else
                    throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
                
                //Add the packet handlers if required
                foreach (var byMethodPair in _discoveryListeners)
                {
                    foreach(ConnectionListenerBase listener in byMethodPair.Value)
                    {
                        if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                            listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                    }
                }
                    
            }
        }