void ThenTheAllAddressShouldBeBroadcast() {
     byte[] b = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
     PhysicalAddress addr = new PhysicalAddress(b);
     Assert.AreEqual(_validAddr1, addr);
     Assert.AreEqual(_validAddr2, addr);
     Assert.AreEqual(_comparedAddr, addr);
 }
Example #2
0
        public void PhysicalAddress_SameAddresses_Pass()
        {
            byte[] byteAddress1 = { 0x01, 0x20, 0x03, 0x40, 0x05, 0x60 };
            
            PhysicalAddress address1 = new PhysicalAddress(byteAddress1);
            PhysicalAddress address2 = new PhysicalAddress(byteAddress1);

            Assert.Equal(address1, address2);
            Assert.Equal(address1.GetHashCode(), address2.GetHashCode());
        }
Example #3
0
        public void PhysicalAddress_Clone_Pass()
        {
            byte[] byteAddress1 = { 0x01, 0x20, 0x03, 0x40, 0x05, 0x60 };
            PhysicalAddress address1 = new PhysicalAddress(byteAddress1);

            byte[] byteAddressClone = address1.GetAddressBytes();
            Assert.Equal(byteAddress1, byteAddressClone);

            byteAddressClone[0] = 0xFF;
            Assert.NotEqual(byteAddress1, byteAddressClone);
        }
 public PhysicalAddressForm(PhysicalAddress address)
 {
     InitializeComponent();
     // populate the grid view
     int n = dgPhysicalAddress.Rows.Add();
     dgPhysicalAddress.Rows[n].Cells[0].Value = address.Street;
     dgPhysicalAddress.Rows[n].Cells[1].Value = address.City;
     dgPhysicalAddress.Rows[n].Cells[2].Value = address.State;
     dgPhysicalAddress.Rows[n].Cells[4].Value = address.PostalCode;
     dgPhysicalAddress.Rows[n].Cells[3].Value = address.CountryOrRegion;
 }
Example #5
0
        public void PhysicalAddress_DifferentAddresses_DifferentSize_Pass()
        {
            byte[] byteAddress1 = { 0x01, 0x20, 0x03, 0x40, 0x05};
            byte[] byteAddress2 = { 0x01, 0x20, 0x03, 0x40, 0x05, 0x60 };

            PhysicalAddress address1 = new PhysicalAddress(byteAddress1);
            PhysicalAddress address2 = new PhysicalAddress(byteAddress2);

            Assert.NotEqual(address1.GetHashCode(), address2.GetHashCode());
            Assert.NotEqual(address1, address2);
        }
 public String BuildAddressString(PhysicalAddress address)
 {
     if (address == null)
     {
         return "null";
     }
     else {
         return String.Format("{0}, {1}, {2}, {3}", 
             address.Street == "" ? "<No Street>" : address.Street, 
             address.City == "" ? "<No City>" : address.City, 
             address.State == "" ? "<No State>" : address.State,
             address.CountryOrRegion == "" ? "<No Country Or Region>" : address.CountryOrRegion
             );
     }
 }
Example #7
0
    public void UpdateDevInfo(ICaptureDevice dev)
    {
        // if we are sending packet to all adapters
        if (dev == null)
        {
            if (sIP == null)
            {
                sIP = IPAddress.Parse("255.255.255.255");
                Console.WriteLine("Set sIP to: " + sIP.ToString());
            }
            if (dIP == null)
            {
                dIP = IPAddress.Parse("255.255.255.255");
                Console.WriteLine("Set dIP to: " + dIP.ToString());
            }
            if (sMAC == null)
            {
                sMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set sMAC to: " + sMAC.ToString());
            }
            if (dMAC == null)
            {
                dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set dMAC to: " + dMAC.ToString());
            }
        }
        // if we picked an actual adapter
        else
        {
            dev.Open();
            // if source address is not defined, fill out the sIP
            List<IPAddress> ipAddresses = Utility.GetIPAddress(dev);
            foreach (IPAddress add in ipAddresses)
            {
                if (sIP == null && dIP != null)
                {
                    if (dIP.ToString().Contains(".") && add.ToString().Contains("."))
                    {
                        sIP = add;
                        Console.WriteLine("Set sIP to: " + add.ToString());
                    }
                    else if (dIP.ToString().Contains(":") && add.ToString().Contains(":"))
                    {
                        sIP = add;
                        Console.WriteLine("Set sIP to: " + add.ToString());
                    }
                }
            }

            if (sIP == null)
            {
                Console.WriteLine("The chosen adapter did not have a valid address");
                Environment.Exit(1);
            }

            //fill out source mac if it is null
            if (sMAC == null)
            {
                sMAC = dev.MacAddress;
                Console.WriteLine("Set sMAC to: " + sMAC.ToString());
            }
            if (dMAC == null)
            {
                dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set dMAC to: " + dMAC.ToString());
            }
            dev.Close();
        }
    }
Example #8
0
 /// <summary>Creates a new ArpRequestResult instance.</summary>
 /// <param name="address">The physical address.</param>
 public ArpRequestResult(PhysicalAddress address)
 {
     Exception = null;
     Address   = address;
 }
 /// <summary>Sends a Wake On LAN signal (magic packet) to a client.</summary>
 /// <param name="target">Destination <see cref="IPEndPoint"/>.</param>
 /// <param name="macAddress">The MAC address of the client.</param>
 /// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception>
 /// <returns>An asynchronous <see cref="Task"/> which sends a Wake On LAN signal (magic packet) to a client.</returns>
 public static Task SendWolAsync(this IPEndPoint target, PhysicalAddress macAddress)
 {
     return(Net.MagicPacket.SendAsync(target, macAddress));
 }
Example #10
0
        public static void getLocalMacAndIP( out byte[] ip, out PhysicalAddress mac )
        {
            ip = new byte[4];
            mac = PhysicalAddress.None;
            //get the interface
            NetworkInterface TrueNic = null;
            foreach ( NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces() )
            {
                if ( nic.OperationalStatus == OperationalStatus.Up )
                {
                    TrueNic = nic;
                    break;
                }
            }

            //get the interface ipv4
            foreach ( IPAddress ips in Dns.GetHostEntry( Environment.MachineName ).AddressList )
            {
                if ( ips.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork )
                {
                    ip = ips.GetAddressBytes();
                    break;
                }
            }
            //get the interface mac
            mac = PhysicalAddress.Parse( TrueNic.GetPhysicalAddress().ToString() );
        }
Example #11
0
        public int Attach(byte leds_ = 0x0)
        {
            state = state_.ATTACHED;

            // Make sure command is received
            HIDapi.hid_set_nonblocking(handle, 0);

            byte[] a = { 0x0 };

            // Connect
            if (!isUSB)
            {
                // Input report mode
                Subcommand(0x03, new byte[] { 0x30 }, 1, false);
                a[0] = 0x1;
                dump_calibration_data();
            }
            else
            {
                Subcommand(0x03, new byte[] { 0x3f }, 1, false);

                a = Enumerable.Repeat((byte)0, 64).ToArray();
                form.console.Text += "Using USB.\r\n";

                a[0] = 0x80;
                a[1] = 0x01;
                HIDapi.hid_write(handle, a, new UIntPtr(2));
                HIDapi.hid_read(handle, a, new UIntPtr(64));

                if (a[2] != 0x3)
                {
                    PadMacAddress = new PhysicalAddress(new byte[] { a[9], a[8], a[7], a[6], a[5], a[4] });
                }

                // USB Pairing
                a    = Enumerable.Repeat((byte)0, 64).ToArray();
                a[0] = 0x80; a[1] = 0x02;                 // Handshake
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x03;                 // 3Mbit baud rate
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x02;                 // Handshake at new baud rate
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                a[0] = 0x80; a[1] = 0x04;                 // Prevent HID timeout
                HIDapi.hid_write(handle, a, new UIntPtr(2));

                dump_calibration_data();
            }

            a[0] = leds_;
            Subcommand(0x30, a, 1);
            Subcommand(0x40, new byte[] { (imu_enabled ? (byte)0x1 : (byte)0x0) }, 1, true);
            Subcommand(0x3, new byte[] { 0x30 }, 1, true);
            Subcommand(0x48, new byte[] { 0x1 }, 1, true);

            Subcommand(0x41, new byte[] { 0x03, 0x00, 0x00, 0x01 }, 4, false);             // higher gyro performance rate

            DebugPrint("Done with init.", DebugType.COMMS);

            HIDapi.hid_set_nonblocking(handle, 1);

            return(0);
        }
Example #12
0
 /// <summary>Sends a Wake On LAN signal (magic packet) to a client.</summary>
 /// <param name="target">Destination <see cref="IPEndPoint"/>.</param>
 /// <param name="macAddress">The MAC address of the client.</param>
 /// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception>
 public static void SendWol(this IPEndPoint target, PhysicalAddress macAddress)
 {
     Net.MagicPacket.Send(target, macAddress);
 }
Example #13
0
 public ARPTableInfo(IPAddress ipAddress, PhysicalAddress macAddress)
 {
     IPAddress  = ipAddress;
     MACAddress = macAddress;
 }
Example #14
0
 public NpgsqlMacAddress(PhysicalAddress macAddr)
 {
     this.macAddr = macAddr;
 }
Example #15
0
 public static string GetHyphenatedHwAddress(PhysicalAddress hwAddress)
 {
     return(BitConverter.ToString(hwAddress.GetAddressBytes()));
 }
Example #16
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stack">Stack</param>
        /// <param name="emisor">Emisor</param>
        /// <param name="source">Ip Source</param>
        /// <param name="dest">Ip Dest</param>
        /// <param name="hwSource">Hw Source</param>
        /// <param name="hwDest">Hw Dest</param>
        /// <param name="tcp">Packet</param>
        /// <param name="date">Date</param>
        public TcpStream(TcpStreamStack stack, ETcpEmisor emisor, PhysicalAddress hwSource, PhysicalAddress hwDest, IPEndPoint source, IPEndPoint dest, TcpPacket tcp, DateTime date)
        {
            _TcpStack             = stack;
            _IsFirst              = true;
            _StartDate            = date;
            _SourceHwAddress      = hwSource;
            _DestinationHwAddress = hwDest;
            _Key        = TcpStreamStack.GetKey(source, dest, emisor == ETcpEmisor.Server);
            _LastPacket = tcp;

            if (tcp != null)
            {
                if (emisor == ETcpEmisor.Server)
                {
                    _Destination = source;
                    _Source      = dest;
                }
                else
                {
                    _Source      = source;
                    _Destination = dest;
                }

                Add(date, emisor, tcp);
            }
            else
            {
                Close();
            }
        }
 public DCP.BlockErrors SendSetRequest(PhysicalAddress destination, int timeoutMs, int retries, DCP.BlockOptions option, byte[] data, bool permanent)
 {
     return(SendSetRequest(destination, timeoutMs, retries, option, permanent ? DCP.BlockQualifiers.Permanent : DCP.BlockQualifiers.Temporary, data));
 }
 public IAsyncResult BeginSetNameRequest(PhysicalAddress destination, string name, bool permanent)
 {
     byte[] bytes = Encoding.ASCII.GetBytes(name);
     return(BeginSetRequest(destination, DCP.BlockOptions.DeviceProperties_NameOfStation, permanent ? DCP.BlockQualifiers.Permanent : DCP.BlockQualifiers.Temporary, bytes));
 }
 public IAsyncResult BeginSetResetRequest(PhysicalAddress destination)
 {
     return(BeginSetRequest(destination, DCP.BlockOptions.Control_FactoryReset, DCP.BlockQualifiers.Permanent, null));
 }
Example #20
0
 public AddressLease(PhysicalAddress owner, InternetAddress address, DateTime expiration)
 {
     this.m_Owner = owner;
     this.m_Address = address;
     this.m_Expiration = expiration;
 }
Example #21
0
        /// <exception cref="PSInvalidCastException">The only kind of exception this method can throw</exception>
        internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType)
        {
            if (expectedDotNetType == null)
            {
                throw new ArgumentNullException("expectedDotNetType");
            }

            if (cimObject == null)
            {
                return(null);
            }

            if (expectedDotNetType.GetTypeInfo().IsGenericType&& expectedDotNetType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                expectedDotNetType = expectedDotNetType.GetGenericArguments()[0];
            }

            if (LanguagePrimitives.IsCimIntrinsicScalarType(expectedDotNetType))
            {
                return(LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture));
            }
            if (expectedDotNetType == typeof(CimInstance))
            {
                return(LanguagePrimitives.ConvertTo(cimObject, expectedDotNetType, CultureInfo.InvariantCulture));
            }

            if (expectedDotNetType.IsArray)
            {
                Type dotNetElementType = GetElementType(expectedDotNetType);
                if (dotNetElementType != null)
                {
                    var   cimArray    = (Array)LanguagePrimitives.ConvertTo(cimObject, typeof(Array), CultureInfo.InvariantCulture);
                    Array dotNetArray = Array.CreateInstance(dotNetElementType, cimArray.Length);
                    for (int i = 0; i < dotNetArray.Length; i++)
                    {
                        object dotNetElement = ConvertFromCimToDotNet(cimArray.GetValue(i), dotNetElementType);
                        dotNetArray.SetValue(dotNetElement, i);
                    }
                    return(dotNetArray);
                }
            }

            Type convertibleCimType = GetConvertibleCimType(expectedDotNetType);

            if (convertibleCimType != null)
            {
                object cimIntrinsicValue = LanguagePrimitives.ConvertTo(cimObject, convertibleCimType, CultureInfo.InvariantCulture);
                object dotNetObject      = LanguagePrimitives.ConvertTo(cimIntrinsicValue, expectedDotNetType, CultureInfo.InvariantCulture);
                return(dotNetObject);
            }

            Func <Func <object>, object> exceptionSafeReturn = delegate(Func <object> innerAction)
            {
                try
                {
                    return(innerAction());
                }
                catch (Exception e)
                {
                    throw CimValueConverter.GetInvalidCastException(
                              e,
                              "InvalidCimToDotNetCast",
                              cimObject,
                              expectedDotNetType.FullName);
                }
            };

            if (typeof(ObjectSecurity).IsAssignableFrom(expectedDotNetType))
            {
                var sddl = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    var objectSecurity = (ObjectSecurity)Activator.CreateInstance(expectedDotNetType);
                    objectSecurity.SetSecurityDescriptorSddlForm(sddl);
                    return objectSecurity;
                }));
            }

            if (typeof(X509Certificate2) == expectedDotNetType)
            {
                var cimIntrinsicValue = (byte[])LanguagePrimitives.ConvertTo(cimObject, typeof(byte[]), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    return new X509Certificate2(cimIntrinsicValue);
                }));
            }

            if (typeof(X500DistinguishedName) == expectedDotNetType)
            {
                var cimIntrinsicValue = (byte[])LanguagePrimitives.ConvertTo(cimObject, typeof(byte[]), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    return new X500DistinguishedName(cimIntrinsicValue);
                }));
            }

            if (typeof(PhysicalAddress) == expectedDotNetType)
            {
                var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    return PhysicalAddress.Parse(cimIntrinsicValue);
                }));
            }

            if (typeof(IPEndPoint) == expectedDotNetType)
            {
                var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    int indexOfLastColon = cimIntrinsicValue.LastIndexOf(':');
                    int port = int.Parse(cimIntrinsicValue.Substring(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture);
                    IPAddress address = IPAddress.Parse(cimIntrinsicValue.Substring(0, indexOfLastColon));
                    return new IPEndPoint(address, port);
                }));
            }

            // WildcardPattern is only supported as an "in" parameter - we do not support the reverse translation (i.e. from "a%" to "a*")

            if (typeof(XmlDocument) == expectedDotNetType)
            {
                var cimIntrinsicValue = (string)LanguagePrimitives.ConvertTo(cimObject, typeof(string), CultureInfo.InvariantCulture);
                return(exceptionSafeReturn(delegate
                {
                    XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                        cimIntrinsicValue,
                        true,                                /* preserve non elements: whitespace, processing instructions, comments, etc. */
                        null);                               /* default maxCharactersInDocument */
                    return doc;
                }));
            }

            // unrecognized type = throw invalid cast exception
            throw CimValueConverter.GetInvalidCastException(
                      null, /* inner exception */
                      "InvalidCimToDotNetCast",
                      cimObject,
                      expectedDotNetType.FullName);
        }
        public static SharpPcap.ICaptureDevice GetPcapDevice(string localIp)
        {
            IPAddress       searchIp  = IPAddress.Parse(localIp);
            PhysicalAddress searchMac = null;
            Dictionary <PhysicalAddress, SharpPcap.ICaptureDevice> networks = new Dictionary <PhysicalAddress, SharpPcap.ICaptureDevice>();

            //search all networks
            foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                PhysicalAddress mac = null;
                try
                {
                    mac = nic.GetPhysicalAddress();
                }
                catch (Exception)
                {
                    //interface have no mac address
                    continue;
                }
                foreach (var entry in nic.GetIPProperties().UnicastAddresses)
                {
                    if (searchIp.Equals(entry.Address))
                    {
                        searchMac = mac;
                        break;
                    }
                }
                if (searchMac != null)
                {
                    break;
                }
            }

            //validate
            if (searchMac == null)
            {
                return(null);
            }

            //search all pcap networks
            foreach (SharpPcap.ICaptureDevice dev in SharpPcap.CaptureDeviceList.Instance)
            {
                try
                {
                    dev.Open();
                    networks.Add(dev.MacAddress, dev);
                    dev.Close();
                }
                catch { }
            }

            //find link
            if (networks.ContainsKey(searchMac))
            {
                return(networks[searchMac]);
            }
            else
            {
                return(null);
            }
        }
Example #23
0
 /// <summary>Commit a physical address in the contact's collection of addresses.</summary>
 /// <param name="contact">The contact that is having this address committed.</param>
 /// <param name="arrayNode">The array node where this address is being committed.</param>
 /// <param name="value">The address being committed.</param>
 private static void _CommitAddress(Contact contact, string arrayNode, PhysicalAddress value)
 {
     Assert.IsTrue(arrayNode.StartsWith(PropertyNames.PhysicalAddressCollection + PropertyNames.PhysicalAddressArrayNode, StringComparison.Ordinal));
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.AddressLabel, value.AddressLabel);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.Locality, value.City);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.Country, value.Country);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.ExtendedAddress, value.ExtendedAddress);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.POBox, value.POBox);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.Region, value.State);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.Street, value.Street);
     contact._SetOrRemoveStringProperty(arrayNode + PropertyNames.PostalCode, value.ZipCode);
 }
Example #24
0
 internal InterfaceArpEntry(IPAddress ipAddress, PhysicalAddress physicalAddress, bool isDynamic)
 {
     IPAddress       = ipAddress;
     PhysicalAddress = physicalAddress;
     IsDynamic       = isDynamic;
 }
Example #25
0
        public virtual void Can_query_using_any_mapped_data_types_with_nulls()
        {
            using (var context = CreateContext())
            {
                context.Set <MappedNullableDataTypes>().Add(
                    new MappedNullableDataTypes
                {
                    Int = 911,
                });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var entity = context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911);

                byte?param1 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Bigint == param1));

                short?param2 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Smallint == param2));

                long?param3 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Bigint == param3));

                float?param4 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Real == param4));

                double?param5 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Double_precision == param5));

                decimal?param6 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Decimal == param6));

                decimal?param7 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Numeric == param7));

                string param8 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Text == param8));

                byte[] param9 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Bytea == param9));

                DateTime?param10 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Timestamp == param10));

                DateTime?param11 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Timestamptz == param11));

                DateTime?param12 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Date == param12));

                TimeSpan?param13 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Time == param13));

                DateTimeOffset?param14 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Timetz == param14));

                TimeSpan?param15 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Interval == param15));

                Guid?param16 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Uuid == param16));

                bool?param17 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Bool == param17));

                PhysicalAddress param18 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Macaddr == param18));

                NpgsqlPoint?param19 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Point == param19));

                string param20 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Jsonb == param20));

                Dictionary <string, string> param21 = null;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 911 && e.Hstore == param21));

                //SomeComposite param22 = null;
                //Assert.Same(entity, context.Set<MappedNullableDataTypes>().Single(e => e.Int == 911 && e.SomeComposite == param20));
            }
        }
Example #26
0
 public override bool Pair(PhysicalAddress master)
 {
     return(true); // ignore
 }
Example #27
0
        public virtual void Can_query_using_any_mapped_data_type()
        {
            using (var context = CreateContext())
            {
                context.Set <MappedNullableDataTypes>().Add(
                    new MappedNullableDataTypes
                {
                    Tinyint          = 80,
                    Smallint         = 79,
                    Int              = 999,
                    Bigint           = 78L,
                    Real             = 84.4f,
                    Double_precision = 85.5,
                    Decimal          = 101.7m,
                    Numeric          = 103.9m,

                    Text  = "Gumball Rules!",
                    Bytea = new byte[] { 86 },

                    Timestamp = new DateTime(2015, 1, 2, 10, 11, 12),
                    //Timestamptz = new DateTime(2016, 1, 2, 11, 11, 12, DateTimeKind.Utc),
                    Date = new DateTime(2015, 1, 2, 0, 0, 0),
                    Time = new TimeSpan(11, 15, 12),
                    //Timetz = new DateTimeOffset(0, 0, 0, 12, 0, 0, TimeSpan.FromHours(2)),
                    Interval = new TimeSpan(11, 15, 12),

                    Uuid = new Guid("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"),
                    Bool = true,

                    Macaddr = PhysicalAddress.Parse("08-00-2B-01-02-03"),
                    Point   = new NpgsqlPoint(5.2, 3.3),
                    Jsonb   = @"{""a"": ""b""}",
                    Hstore  = new Dictionary <string, string> {
                        { "a", "b" }
                    },

                    //SomeComposite = new SomeComposite { SomeNumber = 8, SomeText = "foo" }
                });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var entity = context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999);

                byte?param1 = 80;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Tinyint == param1));

                short?param2 = 79;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Smallint == param2));

                long?param3 = 78L;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Bigint == param3));

                float?param4 = 84.4f;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Real == param4));

                double?param5 = 85.5;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Double_precision == param5));

                decimal?param6 = 101.7m;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Decimal == param6));

                decimal?param7 = 103.9m;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Numeric == param7));

                var param8 = "Gumball Rules!";
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Text == param8));

                var param9 = new byte[] { 86 };
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Bytea == param9));

                DateTime?param10 = new DateTime(2015, 1, 2, 10, 11, 12);
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Timestamp == param10));

                //DateTime? param11 = new DateTime(2019, 1, 2, 14, 11, 12, DateTimeKind.Utc);
                //Assert.Same(entity, context.Set<MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Timestamptz == param11));

                DateTime?param12 = new DateTime(2015, 1, 2, 0, 0, 0);
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Date == param12));

                TimeSpan?param13 = new TimeSpan(11, 15, 12);
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Time == param13));

                //DateTimeOffset? param14 = new DateTimeOffset(0, 0, 0, 12, 0, 0, TimeSpan.FromHours(2));
                //Assert.Same(entity, context.Set<MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Timetz == param14));

                TimeSpan?param15 = new TimeSpan(11, 15, 12);
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Interval == param15));

                Guid?param16 = new Guid("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11");
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Uuid == param16));

                bool?param17 = true;
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Bool == param17));

                var param18 = PhysicalAddress.Parse("08-00-2B-01-02-03");
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Macaddr.Equals(param18)));

                // PostgreSQL doesn't support equality comparison on point
                // NpgsqlPoint? param19 = new NpgsqlPoint(5.2, 3.3);
                // Assert.Same(entity, context.Set<MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Point == param19));

                var param20 = @"{""a"": ""b""}";
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Jsonb == param20));

                var param21 = new Dictionary <string, string> {
                    { "a", "b" }
                };
                Assert.Same(entity, context.Set <MappedNullableDataTypes>().Single(e => e.Int == 999 && e.Hstore == param21));

                //SomeComposite param22 = new SomeComposite { SomeNumber = 8, SomeText = "foo" };
                //Assert.Same(entity, context.Set<MappedNullableDataTypes>().Single(e => e.Int == 999 && e.SomeComposite.Equals(param20)));
            }
        }
Example #28
0
 /// <summary>
 /// Sendet ein Wake-On-LAN-Signal an einen Client.
 /// </summary>
 /// <param name="target">Der Ziel-IPEndPoint.</param>
 /// <param name="macAddress">The MAC address of the client.</param>
 /// <param name="password">The SecureOn password of the client.</param>
 /// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception>
 public static void SendWol(this IPEndPoint target, PhysicalAddress macAddress, SecureOnPassword password)
 {
     Net.MagicPacket.Send(target, macAddress, password);
 }
Example #29
0
        public virtual void Can_insert_and_read_back_all_mapped_nullable_data_types()
        {
            using (var context = CreateContext())
            {
                context.Set <MappedNullableDataTypes>().Add(
                    new MappedNullableDataTypes
                {
                    Tinyint          = 80,
                    Smallint         = 79,
                    Int              = 77,
                    Bigint           = 78L,
                    Real             = 84.4f,
                    Double_precision = 85.5,
                    Decimal          = 101.1m,
                    Numeric          = 103.3m,

                    Text  = "Gumball Rules!",
                    Bytea = new byte[] { 86 },

                    Timestamp = new DateTime(2016, 1, 2, 11, 11, 12),
                    //Timestamptz = new DateTime(2016, 1, 2, 11, 11, 12, DateTimeKind.Utc),
                    Date = new DateTime(2015, 1, 2, 10, 11, 12),
                    Time = new TimeSpan(11, 15, 12),
                    //Timetz = new DateTimeOffset(0, 0, 0, 12, 0, 0, TimeSpan.FromHours(2)),
                    Interval = new TimeSpan(11, 15, 12),

                    Uuid = new Guid("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"),
                    Bool = true,

                    Macaddr = PhysicalAddress.Parse("08-00-2B-01-02-03"),
                    Point   = new NpgsqlPoint(5.2, 3.3),
                    Jsonb   = @"{""a"": ""b""}",
                    Hstore  = new Dictionary <string, string> {
                        { "a", "b" }
                    },

                    //SomeComposite = new SomeComposite { SomeNumber = 8, SomeText = "foo" }
                });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var entity = context.Set <MappedNullableDataTypes>().Single(e => e.Int == 77);

                Assert.Equal(80, entity.Tinyint.Value);
                Assert.Equal(79, entity.Smallint.Value);
                Assert.Equal(77, entity.Int);
                Assert.Equal(78, entity.Bigint);
                Assert.Equal(84.4f, entity.Real);
                Assert.Equal(85.5, entity.Double_precision);
                Assert.Equal(101.1m, entity.Decimal);
                Assert.Equal(103.3m, entity.Numeric);

                Assert.Equal("Gumball Rules!", entity.Text);
                Assert.Equal(new byte[] { 86 }, entity.Bytea);

                Assert.Equal(new DateTime(2016, 1, 2, 11, 11, 12), entity.Timestamp);
                //Assert.Equal(new DateTime(2016, 1, 2, 11, 11, 12), entity.Timestamptz);
                Assert.Equal(new DateTime(2015, 1, 2, 0, 0, 0), entity.Date);
                Assert.Equal(new TimeSpan(11, 15, 12), entity.Time);
                //Assert.Equal(new DateTimeOffset(0, 0, 0, 12, 0, 0, TimeSpan.FromHours(2)), entity.Timetz);
                Assert.Equal(new TimeSpan(11, 15, 12), entity.Interval);

                Assert.Equal(new Guid("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"), entity.Uuid);
                Assert.Equal(true, entity.Bool);

                Assert.Equal(PhysicalAddress.Parse("08-00-2B-01-02-03"), entity.Macaddr);
                Assert.Equal(new NpgsqlPoint(5.2, 3.3), entity.Point);
                Assert.Equal(@"{""a"": ""b""}", entity.Jsonb);
                Assert.Equal(new Dictionary <string, string> {
                    { "a", "b" }
                }, entity.Hstore);

                //Assert.Equal(new SomeComposite { SomeNumber = 8, SomeText = "foo" }, entity.SomeComposite);
            }
        }
Example #30
0
 /// <summary>Sends a Wake On LAN signal (magic packet) to a client.</summary>
 /// <param name="target">Destination <see cref="IPEndPoint"/>.</param>
 /// <param name="macAddress">The MAC address of the client.</param>
 /// <param name="password">The SecureOn password of the client.</param>
 /// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception>
 /// <returns>An asynchronous <see cref="Task"/> which sends a Wake On LAN signal (magic packet) to a client.</returns>
 public static Task SendWolAsync(this IPEndPoint target, PhysicalAddress macAddress, SecureOnPassword password)
 {
     return(Net.MagicPacket.SendAsync(target, macAddress, password));
 }
 public static string ToFormattedString(this PhysicalAddress value) =>
 BitConverter.ToString(value.GetAddressBytes()).Replace('-', ':');
Example #32
0
    //constructor, reads in the args
    public Param(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            string curStr = args[i];

            try
            {
                if (String.Compare(curStr, "-adapter", true) == 0)
                {
                    string nextStr = args[++i];
                    adapter = nextStr;
                    Console.WriteLine("Read in adapter as: " + adapter);
                }
                else if (String.Compare(curStr, "-v6EH", true) == 0)
                {
                    string nextStr = args[++i];
                    string[] tempEHArray = nextStr.Split(',');
                    //ExtentionHeader =

                    int[] tempInt = Array.ConvertAll(tempEHArray, int.Parse);
                    foreach (int curInt in tempInt)
                    {
                        ExtentionHeader.Add((IPProtocolType)curInt);
                    }
                    packetType = PacketType.IP;
                    IPProtocol = IPProtocolType.IPV6;

                    Console.WriteLine("Read in -v6EH as: " + string.Join(",", tempEHArray));
                    Console.WriteLine("Setting packetType as: " + packetType.ToString());
                    Console.WriteLine("Setting IPProtocol as: " + IPProtocol.ToString());
                }
                else if (String.Compare(curStr, "-dMAC", true) == 0)
                {
                    string nextStr = args[++i];
                    nextStr = nextStr.Replace(':', '-').ToUpper();
                    dMAC = PhysicalAddress.Parse(nextStr);
                    Console.WriteLine("Read in dMAC as: " + dMAC.ToString());
                }
                else if (String.Compare(curStr, "-sMAC", true) == 0)
                {
                    string nextStr = args[++i];
                    nextStr = nextStr.Replace(':', '-').ToUpper();
                    sMAC = PhysicalAddress.Parse(nextStr);
                    Console.WriteLine("Read in sMAC as: " + sMAC.ToString());
                }
                else if (String.Compare(curStr, "-dIP", true) == 0)
                {
                    string nextStr = args[++i];
                    dIP = IPAddress.Parse(nextStr);
                    Console.WriteLine("Read in dIP as: " + dIP.ToString());
                }
                else if (String.Compare(curStr, "-sIP", true) == 0)
                {
                    string nextStr = args[++i];
                    sIP = IPAddress.Parse(nextStr);
                    Console.WriteLine("Read in sIP as: " + sIP.ToString());
                }
                else if (String.Compare(curStr, "-IP", true) == 0)
                {
                    string nextStr = args[++i];
                    packetType = PacketType.IP;
                    if (nextStr.StartsWith("0x"))
                    {
                        IPProtocol = (IPProtocolType)Convert.ToInt32(nextStr, 16);
                    }
                    else
                    {
                        IPProtocol = (IPProtocolType)Convert.ToInt32(nextStr);
                    }
                    Console.WriteLine("Read in IP as: " + IPProtocol.ToString());
                }
                else if (String.Compare(curStr, "-EtherType", true) == 0)
                {
                    string nextStr = args[++i];
                    packetType = PacketType.EtherType;
                    if (nextStr.StartsWith("0x"))
                    {
                        EtherTypeProtocol = (EthernetPacketType)Convert.ToInt32(nextStr, 16);
                    }
                    else
                    {
                        EtherTypeProtocol = (EthernetPacketType)Convert.ToInt32(nextStr);
                    }
                    Console.WriteLine("Read in EtherType as: " + EtherTypeProtocol.ToString());
                }
                else if (String.Compare(curStr, "-sPort", true) == 0)
                {
                    string nextStr = args[++i];
                    sPort = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in sPort as: " + sPort.ToString());
                }
                else if (String.Compare(curStr, "-dPort", true) == 0)
                {
                    string nextStr = args[++i];
                    dPort = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in dPort as: " + dPort.ToString());
                }
                else if (String.Compare(curStr, "-type", true) == 0)
                {
                    string nextStr = args[++i];
                    type = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in type as: " + type.ToString());
                }
                else if (String.Compare(curStr, "-tcpFlag", true) == 0)
                {
                    string nextStr = args[++i];
                    tcpFlag = (byte)Byte.Parse(nextStr);
                    Console.WriteLine("Read in tcpFlag as: " + tcpFlag.ToString());
                }
                else if (String.Compare(curStr, "-code", true) == 0)
                {
                    string nextStr = args[++i];
                    code = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in code as: " + code.ToString());
                }
                else if (String.Compare(curStr, "-payload", true) == 0)
                {
                    string nextStr = args[++i];
                    if (nextStr.StartsWith("0x"))
                    {
                        payload = Utility.ParseHex(nextStr);
                        Console.WriteLine("Read in -payload as: 0x" + BitConverter.ToString(payload));
                    }
                    else
                    {
                        payload = Encoding.ASCII.GetBytes(nextStr);
                        Console.WriteLine("Read in -payload as: " + System.Text.Encoding.Default.GetString(payload));
                    }
                }
                else if (String.Compare(curStr, "-adapter", true) == 0)
                {
                    string nextStr = args[++i];
                    adapter = nextStr;
                    Console.WriteLine("Read in -adapter as: " + adapter);
                }
                else if (String.Compare(curStr, "-IPv4Frag", true) == 0)
                {
                    IPv4Frag = true;
                    Console.WriteLine("Read in -ipv4frag as: " + IPv4Frag);
                }
                else if (String.Compare(curStr, "-ICMP", true) == 0)
                {
                    packetType = PacketType.ICMP;
                }
                else if (String.Compare(curStr, "-tcp", true) == 0)
                {
                    packetType = PacketType.TCP;
                }
                else if (String.Compare(curStr, "-udp", true) == 0)
                {
                    packetType = PacketType.UDP;
                }
                else if (String.Compare(curStr, "-ICMPv6", true) == 0)
                {
                    packetType = PacketType.ICMPv6;
                }
                else if (String.Compare(curStr, "-h", true) == 0)
                {
                    Utility.PrintHelp();
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("Unrecognized param: " + curStr);
                    Utility.PrintHelp();
                    Environment.Exit(1);
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Another arg was expected after " + curStr);
                Environment.Exit(1);
            }
            catch (FormatException)
            {
                Console.WriteLine("The address specified for " + curStr + " was not in the correct format.");
                Environment.Exit(1);
            }
            catch (DllNotFoundException e)
            {
                Console.WriteLine("A required DLL was not found, is WinPcap and .NET framework installed?");
                Console.WriteLine("Exception Message: " + e.Message);
                Console.WriteLine("StackTrace: " + e.StackTrace);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught while handling commandline.");
                Console.WriteLine("Exception Message: " + e.Message);
                Console.WriteLine("StackTrace: " + e.StackTrace);
                Environment.Exit(1);
            }
        }

        // do some checks to make sure this param combination is valid

        if (dIP == null && dMAC == null)
        {
            Console.WriteLine("-dIP or -dMAC has to be set to send a packet.");
            Environment.Exit(1);
        }

        if (dIP == null &&
            (packetType == PacketType.ICMP ||
            packetType == PacketType.ICMPv6 ||
            packetType == PacketType.IP ||
            packetType == PacketType.TCP ||
            packetType == PacketType.UDP))
        {
            Console.WriteLine("dIP needs to be defined for IP based packets.");
            Environment.Exit(1);
        }

        if (packetType == PacketType.ICMPv6 && (dIP == null || !dIP.ToString().Contains(":")))
        {
            Console.WriteLine("dIP needs to be IPv6 for ICMPv6 packets.");
            Environment.Exit(1);
        }
        else if ((packetType == PacketType.ICMP && (dIP == null || !dIP.ToString().Contains("."))))
        {
            Console.WriteLine("dIP needs to be IPv4 for ICMP packets.");
            Environment.Exit(1);
        }

        if (ExtentionHeader.Count != 0 && (dIP == null || !dIP.ToString().Contains(":")))
        {
            Console.WriteLine("dIP needs to be IPv6 for ExtensionHeader packets.");
            Environment.Exit(1);
        }

        if (ExtentionHeader.Count == 1)
        {
            Console.WriteLine("There needs to be at least 2 extension headers.");
            Environment.Exit(1);
        }

        if (dMAC == null && packetType == PacketType.EtherType)
        {
            Console.WriteLine("dMAC needs to be defined for EtherType based packets.");
            Environment.Exit(1);
        }
    }
Example #33
0
        /// <summary>
        /// Actively monitor ARP packets for signs of new clients after the scanner is done. This method should be called from the StartScan method.
        /// </summary>
        /// <param name="view">UI controls</param>
        public static void BackgroundScanStart(IView view)
        {
            view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Starting background scan..."));
            BackgroundScanDisabled = false;

            IPAddress myipaddress = AppConfiguration.LocalIp;

            #region Assign OnPacketArrival event handler and start capturing

            capturedevice.OnPacketArrival += (object sender, CaptureEventArgs e) =>
            {
                if (BackgroundScanDisabled)
                {
                    return;
                }

                Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                if (packet == null)
                {
                    return;
                }

                ArpPacket ArpPacket = packet.Extract <ArpPacket>();

                if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                {
                    ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);
                    view.ListView1.Invoke(new Action(() =>
                    {
                        string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                        string ip  = ArpPacket.SenderProtocolAddress.ToString();
                        var device = new Device
                        {
                            IP           = ArpPacket.SenderProtocolAddress,
                            MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                            DeviceName   = "Resolving",
                            ManName      = "Getting information...",
                            DeviceStatus = "Online"
                        };

                        //Add device to list
                        view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                        //Add device to main device list
                        _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                        //Get hostname and mac vendor for the current device
                        _ = Task.Run(async() =>
                        {
                            try
                            {
                                #region Get Hostname

                                IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                device.DeviceName     = hostEntry?.HostName ?? ip;

                                #endregion

                                #region Get MacVendor

                                var Name       = VendorAPI.GetVendorInfo(mac);
                                device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                #endregion

                                view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                            }
                            catch (Exception ex)
                            {
                                if (ex is SocketException)
                                {
                                    var Name       = VendorAPI.GetVendorInfo(mac);
                                    device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                    view.ListView1.BeginInvoke(new Action(() =>
                                    {
                                        device.DeviceName = ip;
                                        view.ListView1.UpdateObject(device);
                                    }));
                                }
                                else
                                {
                                    view.MainForm.BeginInvoke(
                                        new Action(() =>
                                    {
                                        device.DeviceName = ip;
                                        device.ManName    = "Error";
                                        view.ListView1.UpdateObject(device);
                                    }));
                                }
                            }
                        });
                    }));

                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found"));
                }
                else if (ClientList.ContainsKey(ArpPacket.SenderProtocolAddress))
                {
                    foreach (var Device in Main.Devices)
                    {
                        if (Device.Key.Equals(ArpPacket.SenderProtocolAddress))
                        {
                            Device.Value.TimeSinceLastArp = DateTime.Now;
                            break;
                        }
                    }
                }
            };

            //Start receiving packets
            capturedevice.StartCapture();

            //Update UI state
            view.MainForm.BeginInvoke(new Action(() =>
            {
                view.PictureBox.Image  = NetStalker.Properties.Resources.color_ok;
                view.StatusLabel2.Text = "Ready";
                view.Tile.Enabled      = true;
                view.Tile2.Enabled     = true;
            }));

            if (!LoadingBarCalled)
            {
                CallTheLoadingBar(view);
                view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning..."));
            }

            view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found"));

            #endregion
        }
		public Contact GetCanonicalContact(ContactEntry c)
		{
			Contact contact = new Contact();

			IList<string> groups = new List<string>();
			foreach (GroupMembership group in c.GroupMembership)
			{
				foreach (GroupEntry ge in groupsFeed.Entries)
				{
					if (group.HRef.Equals(ge.Id.AbsoluteUri))
					{
						groups.Add(ge.Title.Text);
					}
				}
				
			}

			string title = c.Title.Text;
			if (title.Contains("\""))
				title = title.Replace("\"", "%20");

			Name name = GetCannonicalName(title, null, null, null,
			    Notation, NameNotation.Formal);

			contact.Names.Add(name);
			foreach (string g in groups)
			{
				contact.Names.GetLabelsAt(0).Add(g);
			}

			bool setPreffered = false;
			foreach (EMail e in c.Emails)
			{
				EmailAddress email = new EmailAddress(e.Address);
				if (setPreffered == false)
				{
					contact.EmailAddresses.Add(email, PropertyLabels.Preferred);
					setPreffered = true;
				}
				else
					contact.EmailAddresses.Add(email);
			}

			foreach (Organization o in c.Organizations)
			{
				Microsoft.Communications.Contacts.Position pos  =
					new Microsoft.Communications.Contacts.Position(o.Name, o.Title, o.Name, null, null, o.Title, null);

				contact.Positions.Add(pos, PropertyLabels.Business);
			}

			foreach (PostalAddress pa in c.PostalAddresses)
			{
				PhysicalAddress adr = new PhysicalAddress(
					null, pa.Value, null,null, null, null, null, 
					null
				);

				if (pa.Home)
				{
					contact.Addresses.Add(adr, PropertyLabels.Personal);
				}
				else if (pa.Work)
				{
					contact.Addresses.Add(adr, PropertyLabels.Business);
				}
				else
					contact.Addresses.Add(adr);
			}

			foreach (Google.GData.Extensions.PhoneNumber n in c.Phonenumbers)
			{

				Microsoft.Communications.Contacts.PhoneNumber phone = 
					new Microsoft.Communications.Contacts.PhoneNumber(n.Value);

				if (n.Work)
				{
					if (n.Primary)
						contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Business, PropertyLabels.Preferred);
					else
						contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Business);
				}

				if (n.Home)
				{
					if (n.Primary)
						contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Personal, PropertyLabels.Preferred);
					else
						contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Personal);
				}

				if (n.Rel == null) break;

				if (n.Rel.Contains("#mobile"))
					contact.PhoneNumbers.Add(phone, PhoneLabels.Cellular);

				if (n.Rel.Contains("#home_fax"))
					contact.PhoneNumbers.Add(phone, PhoneLabels.Fax, PropertyLabels.Personal);

				if (n.Rel.Contains("#work_fax"))
					contact.PhoneNumbers.Add(phone, PhoneLabels.Fax, PropertyLabels.Business);

				if (n.Rel.Contains("#pager"))
					contact.PhoneNumbers.Add(phone, PhoneLabels.Pager);

				if (n.Rel.Contains("#other"))
					contact.PhoneNumbers.Add(phone, PhoneLabels.Voice);
				
			}

			DateTime lastChanged = c.Updated.ToUniversalTime();
			contact.Dates.Add(lastChanged, "LastModificationTime" );
			
			int lastIndexOfDash = c.Id.AbsoluteUri.LastIndexOf('/') + 1;
			string absoluteUri = c.Id.AbsoluteUri.Substring(lastIndexOfDash,c.Id.AbsoluteUri.Length-lastIndexOfDash);
			Guid guid = new Guid(absoluteUri.PadLeft(32, '0'));
			contact.ContactIds.Add(guid, "Gmail");

			return contact;
		}
 void GivenThePhysicalAddressBroadcastIsArrayOf6Bytes() {
     byte[] b = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
     _validAddr1 = new PhysicalAddress(b);
 }
Example #36
0
 public AddressLease(PhysicalAddress owner, InternetAddress address)
     : this(owner, address, DateTime.Now.AddDays(1))
 {
 }
 void GivenThePhysicalAddressBroadcastIsOtherObjectPhysicalAddress() {
     byte[] b = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
     PhysicalAddress othrAddr = new PhysicalAddress(b);
     _comparedAddr = new PhysicalAddress(othrAddr);
 }
Example #38
0
        /// <summary>
        /// Probe for active devices on the network
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public async static Task ProbeDevices()
        {
            await Task.Run(() =>
            {
                if (AppConfiguration.NetworkSize == 1)
                {
                    for (int ipindex = 1; ipindex <= 255; ipindex++)
                    {
                        if (capturedevice.MacAddress == null)
                        {
                            continue;
                        }
                        ArpPacket arprequestpacket    = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + ipindex), capturedevice.MacAddress, myipaddress);
                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                        ethernetpacket.PayloadPacket  = arprequestpacket;
                        capturedevice.SendPacket(ethernetpacket);
                    }
                }

                else if (AppConfiguration.NetworkSize == 2)
                {
                    for (int i = 1; i <= 255; i++)
                    {
                        for (int j = 1; j <= 255; j++)
                        {
                            ArpPacket arprequestpacket    = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j), capturedevice.MacAddress, myipaddress);
                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                            ethernetpacket.PayloadPacket  = arprequestpacket;
                            capturedevice.SendPacket(ethernetpacket);
                            if (!GatewayCalled)
                            {
                                ArpPacket ArpForGateway        = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), AppConfiguration.GatewayIp, capturedevice.MacAddress, myipaddress);//???
                                EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                                EtherForGateway.PayloadPacket  = ArpForGateway;
                                capturedevice.SendPacket(EtherForGateway);
                                GatewayCalled = true;
                            }
                        }
                    }
                }

                else if (AppConfiguration.NetworkSize == 3)
                {
                    for (int i = 1; i <= 255; i++)
                    {
                        for (int j = 1; j <= 255; j++)
                        {
                            for (int k = 1; k <= 255; k++)
                            {
                                ArpPacket arprequestpacket = new ArpPacket(ArpOperation.Request,
                                                                           PhysicalAddress.Parse("00-00-00-00-00-00"),
                                                                           IPAddress.Parse(Root + i + '.' + j + '.' + k), capturedevice.MacAddress,
                                                                           myipaddress);
                                EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress,
                                                                                   PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);
                                ethernetpacket.PayloadPacket = arprequestpacket;
                                capturedevice.SendPacket(ethernetpacket);
                                if (!GatewayCalled)
                                {
                                    ArpPacket ArpForGateway        = new ArpPacket(ArpOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), AppConfiguration.GatewayIp, capturedevice.MacAddress, myipaddress); //???
                                    EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetType.Arp);                                         //???
                                    EtherForGateway.PayloadPacket  = ArpForGateway;
                                    capturedevice.SendPacket(EtherForGateway);
                                    GatewayCalled = true;
                                }
                            }
                        }
                    }
                }
            });
        }
Example #39
0
 /// <summary>Creates a new ArpRequestResult instance.</summary>
 /// <param name="exception">The error which occurred.</param>
 public ArpRequestResult(Exception exception)
 {
     Exception = exception;
     Address   = null;
 }
 void AndGivenThePhysicalAddressBroadcastIsArrayOf10BytesWhereFrom2To7bytesThereIsAddress() {
     byte[] b = { 0, 1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 8, 9 };
     _validAddr2 = new PhysicalAddress(b, 2);
 }
Example #41
0
        private static Fixup ConvertFixupDefinition(
            FixupDefinition def, Dictionary<object, object> objectMap)
        {
            Fixup fixup = new Fixup();
            fixup.StartIndex = def.DataOffset;
            switch (def.Location)
            {
                case FixupLocation.LowByte:
                    fixup.LocationType = FixupLocationType.LowByte;
                    break;
                case FixupLocation.Offset:
                case FixupLocation.LoaderResolvedOffset:
                    fixup.LocationType = FixupLocationType.Offset;
                    break;
                case FixupLocation.Base:
                    fixup.LocationType = FixupLocationType.Base;
                    break;
                case FixupLocation.Pointer:
                    fixup.LocationType = FixupLocationType.Pointer;
                    break;
                default:
                    throw new InvalidDataException("The fixup location is not supported.");
            }
            fixup.Mode = def.Mode;

            IAddressReferent referent;
            if (def.Target.Referent is UInt16)
            {
                referent = new PhysicalAddress((UInt16)def.Target.Referent, 0);
            }
            else
            {
                referent = (IAddressReferent)objectMap[def.Target.Referent];
            }
            fixup.Target = new SymbolicTarget
            {
                Referent = (IAddressReferent)referent,
                Displacement = def.Target.Displacement
            };
            //f.Frame = null;
            return fixup;
        }
 void WhenTheUserInitializesPhysicalAddresOthersAddress() {
     _notSameAddr = new PhysicalAddress(_comparedAddr);
 }
 public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime, PhysicalAddress mac)
 {
     return(GenerateTimeBasedGuid(dateTime, GenerateClockSequenceBytes(dateTime), GenerateNodeBytes(mac)));
 }
Example #44
0
        /// <summary>
        /// Populates the list with devices connected on LAN
        /// </summary>
        /// <param name="view">UI controls</param>
        /// <param name="InterfaceFriendlyName"></param>
        public static void StartScan(IView view, string InterfaceFriendlyName)
        {
            #region initialization

            if (capturedevice != null)
            {
                GatewayCalled          = false;
                BackgroundScanDisabled = true;
                capturedevice.StopCapture();
                capturedevice.Close();
                capturedevice = null;
            }
            else
            {
                ClientList   = new Dictionary <IPAddress, PhysicalAddress>();
                Main.Devices = new ConcurrentDictionary <IPAddress, Device>();
            }

            #endregion

            //Get list of interfaces
            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            //crucial for reflection on any network changes
            capturedevicelist.Refresh();
            capturedevice = (from devicex in capturedevicelist where ((NpcapDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0];
            //open device in promiscuous mode with 1000ms timeout
            capturedevice.Open(DeviceMode.Promiscuous, 1000);
            //Arp filter
            capturedevice.Filter = "arp";

            IPAddress myipaddress = AppConfiguration.LocalIp;

            //Probe for active devices on the network
            if (DiscoveryTimer == null)
            {
                StartDescoveryTimer();
            }

            #region Retrieving ARP packets floating around and find out the sender's IP and MAC

            //Scan duration
            long       scanduration = 8000;
            RawCapture rawcapture   = null;

            //Main scanning task
            ScannerTask = Task.Run(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ArpPacket ArpPacket = packet.Extract <ArpPacket>();
                        if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                        {
                            ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);

                            string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                            string ip  = ArpPacket.SenderProtocolAddress.ToString();
                            var device = new Device
                            {
                                IP           = ArpPacket.SenderProtocolAddress,
                                MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                                DeviceName   = "Resolving",
                                ManName      = "Getting information...",
                                DeviceStatus = "Online"
                            };

                            //Add device to UI list
                            view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                            //Add device to main device list
                            _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                            //Get hostname and mac vendor for the current device
                            _ = Task.Run(async() =>
                            {
                                try
                                {
                                    #region Get Hostname

                                    IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                    device.DeviceName     = hostEntry?.HostName ?? ip;

                                    #endregion

                                    #region Get MacVendor

                                    var Name       = VendorAPI.GetVendorInfo(mac);
                                    device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                    #endregion

                                    view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                                }
                                catch (Exception ex)
                                {
                                    if (ex is SocketException)
                                    {
                                        var Name       = VendorAPI.GetVendorInfo(mac);
                                        device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                        view.ListView1.BeginInvoke(new Action(() =>
                                        {
                                            device.DeviceName = ip;
                                            view.ListView1.UpdateObject(device);
                                        }));
                                    }
                                    else
                                    {
                                        view.MainForm.BeginInvoke(
                                            new Action(() =>
                                        {
                                            device.DeviceName = ip;
                                            device.ManName    = "Error";
                                            view.ListView1.UpdateObject(device);
                                        }));
                                    }
                                }
                            });
                        }

                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }

                    stopwatch.Stop();
                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found"));

                    //Initial scanning is over now we start the background scan.
                    Main.OperationIsInProgress = false;

                    //Start passive monitoring
                    BackgroundScanStart(view);
                }
                catch
                {
                    //Show an error in the UI in case something went wrong
                    view.MainForm.Invoke(new Action(() =>
                    {
                        view.StatusLabel.Text = "Error occurred";
                        view.PictureBox.Image = Properties.Resources.color_error;
                    }));
                }
            });

            #endregion
        }
Example #45
0
        // scanner response - new target
        private void scanner_OnResponse(string ip, bool ipv6, PhysicalAddress mac, string hostname, List <string> ipv6List = null)
        {
            Window.Dispatcher.Invoke(new UI(delegate
            {
                // check for existing MAC and update current item
                var items = Window.TargetList.Where(o => o.MAC.Replace(":", "") == mac.ToString());

                if (items.Count() > 0)
                {
                    var item = items.First();

                    if (ipv6)
                    {
                        item.IPv6 = ip;

                        // change ipv6List
                        if (ipv6List != null && ipv6List.Count > 0)
                        {
                            item.IPv6List = ipv6List;
                        }

                        // add ip to the list after ping response (ipv6List is null)
                        if (ipv6List == null && !item.IPv6List.Contains(ip))
                        {
                            item.IPv6List.Add(ip);
                        }
                    }
                    else
                    {
                        item.IP = ip;
                    }
                }
                // add new item
                else
                {
                    var item = new Target {
                        Hostname = hostname, MAC = Network.FriendlyPhysicalAddress(mac), PMAC = mac, Vendor = GetVendorFromMAC(mac.ToString())
                    };

                    if (ipv6)
                    {
                        item.IPv6 = ip;

                        // change ipv6List
                        if (ipv6List != null && ipv6List.Count > 0)
                        {
                            item.IPv6List = ipv6List;
                        }

                        // add ip to the list after ping response (ipv6List is null)
                        if (ipv6List == null && !item.IPv6List.Contains(ip))
                        {
                            item.IPv6List.Add(ip);
                        }
                    }
                    else
                    {
                        item.IP = ip;
                    }

                    // exclude local MAC
                    if (mac.ToString() != DeviceInfo.PMAC.ToString())
                    {
                        Window.TargetList.Add(item);
                        Window.TargetList.Sort();
                    }
                }
            }));
        }
Example #46
0
        private void ProcessIncoming(byte[] localMsg, IPEndPoint clientEP)
        {
            try {
                int currIdx = 0;
                if (localMsg[0] != 'D' || localMsg[1] != 'S' || localMsg[2] != 'U' || localMsg[3] != 'C')
                {
                    return;
                }
                else
                {
                    currIdx += 4;
                }

                uint protocolVer = BitConverter.ToUInt16(localMsg, currIdx);
                currIdx += 2;

                if (protocolVer > MaxProtocolVersion)
                {
                    return;
                }

                uint packetSize = BitConverter.ToUInt16(localMsg, currIdx);
                currIdx += 2;

                if (packetSize < 0)
                {
                    return;
                }

                packetSize += 16;                 //size of header
                if (packetSize > localMsg.Length)
                {
                    return;
                }
                else if (packetSize < localMsg.Length)
                {
                    byte[] newMsg = new byte[packetSize];
                    Array.Copy(localMsg, newMsg, packetSize);
                    localMsg = newMsg;
                }

                uint crcValue = BitConverter.ToUInt32(localMsg, currIdx);
                //zero out the crc32 in the packet once we got it since that's whats needed for calculation
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;
                localMsg[currIdx++] = 0;

                uint crcCalc = Crc32Algorithm.Compute(localMsg);
                if (crcValue != crcCalc)
                {
                    return;
                }

                uint clientId = BitConverter.ToUInt32(localMsg, currIdx);
                currIdx += 4;

                uint messageType = BitConverter.ToUInt32(localMsg, currIdx);
                currIdx += 4;

                if (messageType == (uint)MessageType.DSUC_VersionReq)
                {
                    byte[] outputData = new byte[8];
                    int    outIdx     = 0;
                    Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_VersionRsp), 0, outputData, outIdx, 4);
                    outIdx += 4;
                    Array.Copy(BitConverter.GetBytes((ushort)MaxProtocolVersion), 0, outputData, outIdx, 2);
                    outIdx += 2;
                    outputData[outIdx++] = 0;
                    outputData[outIdx++] = 0;

                    SendPacket(clientEP, outputData, 1001);
                }
                else if (messageType == (uint)MessageType.DSUC_ListPorts)
                {
                    // Requested information on gamepads - return MAC address
                    int numPadRequests = BitConverter.ToInt32(localMsg, currIdx);
                    currIdx += 4;
                    if (numPadRequests < 0 || numPadRequests > 4)
                    {
                        return;
                    }

                    int requestsIdx = currIdx;
                    for (int i = 0; i < numPadRequests; i++)
                    {
                        byte currRequest = localMsg[requestsIdx + i];
                        if (currRequest < 0 || currRequest > 4)
                        {
                            return;
                        }
                    }

                    byte[] outputData = new byte[16];
                    for (byte i = 0; i < numPadRequests; i++)
                    {
                        byte currRequest = localMsg[requestsIdx + i];
                        var  padData     = controllers[i];                   //controllers[currRequest];

                        int outIdx = 0;
                        Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_PortInfo), 0, outputData, outIdx, 4);
                        outIdx += 4;

                        outputData[outIdx++] = (byte)padData.PadId;
                        outputData[outIdx++] = (byte)padData.constate;
                        outputData[outIdx++] = (byte)padData.model;
                        outputData[outIdx++] = (byte)padData.connection;

                        var addressBytes = padData.PadMacAddress.GetAddressBytes();
                        if (addressBytes.Length == 6)
                        {
                            outputData[outIdx++] = addressBytes[0];
                            outputData[outIdx++] = addressBytes[1];
                            outputData[outIdx++] = addressBytes[2];
                            outputData[outIdx++] = addressBytes[3];
                            outputData[outIdx++] = addressBytes[4];
                            outputData[outIdx++] = addressBytes[5];
                        }
                        else
                        {
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                            outputData[outIdx++] = 0;
                        }

                        outputData[outIdx++] = (byte)padData.battery;                        //(byte)padData.BatteryStatus;
                        outputData[outIdx++] = 0;

                        SendPacket(clientEP, outputData, 1001);
                    }
                }
                else if (messageType == (uint)MessageType.DSUC_PadDataReq)
                {
                    byte            regFlags = localMsg[currIdx++];
                    byte            idToReg  = localMsg[currIdx++];
                    PhysicalAddress macToReg = null;
                    {
                        byte[] macBytes = new byte[6];
                        Array.Copy(localMsg, currIdx, macBytes, 0, macBytes.Length);
                        currIdx += macBytes.Length;
                        macToReg = new PhysicalAddress(macBytes);
                    }

                    lock (clients) {
                        if (clients.ContainsKey(clientEP))
                        {
                            clients[clientEP].RequestPadInfo(regFlags, idToReg, macToReg);
                        }
                        else
                        {
                            var clientTimes = new ClientRequestTimes();
                            clientTimes.RequestPadInfo(regFlags, idToReg, macToReg);
                            clients[clientEP] = clientTimes;
                        }
                    }
                }
            } catch (Exception e) { }
        }
Example #47
0
 public Adapter(string Name, NetworkInterfaceType type, IPAddress ip, IPAddress ipSubnet, PhysicalAddress mac)
 {
     this.Name     = Name;
     this.type     = type;
     this.ip       = ip;
     this.ipSubnet = ipSubnet;
     this.mac      = mac;
 }
		public Contact GetCanonicalContact(PIMPersonalInfo pim, PIMNumbers num, IList<PIMAddresses> adr)
		{
			if (pim == null)
				return null;

			Contact contact = new Contact();

			if (pim.FormalName != null)
			{
				string[] names = pim.FormalName.Split(new char[] { ' ' });

				if (pim.FirstName == null && pim.LastName == null && pim.MiddleName == null)
				{
					if (names.Length > 2)
						pim.FirstName = names[0];
					else if (names.Length == 2)
						pim.FirstName = names[1];
					else if (names.Length > 0)
						pim.FirstName = names[0];

					if (names.Length == 3)
						pim.MiddleName = names[1];
					else if (names.Length > 3)
						pim.MiddleName = names[names.Length - 2];

					if (names.Length >= 3)
						pim.LastName = names[2];
					else if (names.Length > 1)
						pim.LastName = names[0];
				}
			}

			Name name = new Name(
				pim.FormalName,
				pim.GivenNamePronunciation, 
				null,
				pim.Title,
				pim.FirstName,
				pim.MiddleName,
				pim.LastName,
				null,
				pim.Suffix,
				pim.Nick);

			name.FormattedName = pim.LastName;
			if (name.FormattedName != null &&
				name.FormattedName != "")
				name.FormattedName += " ";
			name.FormattedName += pim.FirstName;
			if (name.FormattedName != null &&
				name.FormattedName != "")
				name.FormattedName += " ";
			name.FormattedName += pim.MiddleName;
			name.FormattedName = name.FormattedName.Trim();

			contact.Names.Add(name);

			PhoneNumber phone = null;
			
			if (num.Mobile.Count > 0)
			{
				foreach (string ph in num.Mobile) {
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Cellular);
				}
			}

			if (num.MobileHome.Count > 0)
			{
				foreach (string ph in num.MobileHome) {
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Cellular, PropertyLabels.Personal);
				}
			}

			if (num.MobileWork.Count > 0)
			{
				foreach (string ph in num.MobileWork) {
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Cellular, PropertyLabels.Business);
				}
			}

			if (num.Telephone.Count > 0)
			{
				foreach (string ph in num.Telephone)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Voice);
				}
			}

			if (num.Home.Count > 0)
			{
				foreach (string ph in num.Home)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Personal);
				}
			}

			if (num.Work.Count > 0)
			{
				foreach (string ph in num.Work)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Voice, PropertyLabels.Business);
				}
			}

			if (num.Fax.Count > 0)
			{
				foreach (string ph in num.Fax)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Fax);
				}
			}

			if (num.FaxHome.Count > 0)
			{
				foreach (string ph in num.FaxHome)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Fax, PropertyLabels.Personal);
				}
			}

			if (num.FaxWork.Count > 0)
			{
				foreach (string ph in num.FaxWork)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Fax, PropertyLabels.Business);
				}
			}

			if (num.Pager.Count > 0)
			{
				foreach (string ph in num.Pager)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Pager);
				}
			}

			if (num.Video.Count > 0)
			{
				foreach (string ph in num.Video)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Video);
				}
			}

			if (num.VideoHome.Count > 0)
			{
				foreach (string ph in num.VideoHome)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Video, PropertyLabels.Personal);
				}
			}

			if (num.VideoWork.Count > 0)
			{
				foreach (string ph in num.VideoWork)
				{
					phone = new PhoneNumber(ph);
					contact.PhoneNumbers.Add(phone, PhoneLabels.Video, PropertyLabels.Business);
				}
			}

			foreach (PIMAddresses a in adr)
			{
				PhysicalAddress phys = new PhysicalAddress(
					a.POBox, a.Street, a.City, a.State, a.PostalCode, a.Country,
					null, null);

				if (a.Private != null)
				{
					contact.Addresses.Add(phys, PropertyLabels.Personal);
				}
				else if (a.Business != null)
				{
					contact.Addresses.Add(phys, PropertyLabels.Business);
				}
				else
				{
					contact.Addresses.Add(phys, PropertyLabels.Personal);
				}
			}

			Position pos = new Position(null, null, pim.Company, null, null, pim.JobTitle, null);
			contact.Positions.Add(pos, PropertyLabels.Business);

			DateTime lastChanged = DateTime.Now;
			contact.Dates.Add(lastChanged, new string[] { "LastModificationTime" });
			
			return contact;
		}
Example #49
0
        /// <summary>
        /// Sends command packet to control the MSProtocolTestSuiteNetworkEventSimulator filter
        /// </summary>
        /// <param name="sCommand">Flag to specify the command type</param>
        /// <param name="localMacAddress">The MAC address used to specify the local NIC used to send the command packet</param>
        /// <param name="remoteMacAddress">The MAC address specifying the target NIC</param>
        /// <returns>Flag to specify whether it has sent the command packet successfully</returns>
        private static bool SendCommand(SimulatorCommand sCommand, PhysicalAddress localMacAddress, PhysicalAddress remoteMacAddress = null)
        {
            IPAddress ipv4Address = GetIPAddress4FromMACAddress(localMacAddress);

            if (ipv4Address == null)
            {
                return(false);
            }
            BindLocalIP(ipv4Address);

            byte[] buffer = SimulatorCommandBuilder.GetCommandPacket(sCommand, remoteMacAddress);

            if (buffer == null)
            {
                return(false);
            }
            udpClient.Send(buffer, buffer.Length, broadcastHostname, nesPort);

            return(true);
        }