public void CanConvertToUnsupportedTypeTest()
        {
            bool expected = false;

            IPAddressConverter target = new IPAddressConverter();
            bool actual = target.CanConvertTo(typeof(bool));

            Assert.AreEqual(expected, actual);
        }
        public void CanConvertFromRASIPADDRTest()
        {
            bool expected = true;

            IPAddressConverter target = new IPAddressConverter();
            bool actual = target.CanConvertFrom(typeof(NativeMethods.RASIPADDR));

            Assert.AreEqual(expected, actual);
        }
        public void CanConvertFromStringTest()
        {
            bool expected = true;

            IPAddressConverter target = new IPAddressConverter();
            bool actual = target.CanConvertFrom(typeof(string));

            Assert.AreEqual(expected, actual);
        }
Example #4
0
        /// <summary>
        /// Updates the tunnel endpoints of an Internet Key Exchange (IKEv2) connection.
        /// </summary>
        /// <param name="handle">The handle of the connection.</param>
        /// <param name="interfaceIndex">The new interface index of the endpoint.</param>
        /// <param name="localEndPoint">The new local client endpoint of the connection.</param>
        /// <param name="remoteEndPoint">The new remote server endpoint of the connection.</param>
        public void UpdateConnection(RasHandle handle, int interfaceIndex, IPAddress localEndPoint, IPAddress remoteEndPoint)
        {
            int size = Marshal.SizeOf(typeof(NativeMethods.RASUPDATECONN));

            IntPtr pRasUpdateConn = IntPtr.Zero;
            try
            {
                IPAddressConverter converter = new IPAddressConverter();

                NativeMethods.RASUPDATECONN updateConn = new NativeMethods.RASUPDATECONN();
                updateConn.version = GetCurrentApiVersion();
                updateConn.size = size;
                updateConn.interfaceIndex = interfaceIndex;
                updateConn.localEndPoint = (NativeMethods.RASTUNNELENDPOINT)converter.ConvertTo(localEndPoint, typeof(NativeMethods.RASTUNNELENDPOINT));
                updateConn.remoteEndPoint = (NativeMethods.RASTUNNELENDPOINT)converter.ConvertTo(remoteEndPoint, typeof(NativeMethods.RASTUNNELENDPOINT));

                pRasUpdateConn = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(updateConn, pRasUpdateConn, true);

                int ret = UnsafeNativeMethods.Instance.UpdateConnection(handle, pRasUpdateConn);
                if (ret == NativeMethods.ERROR_INVALID_PARAMETER)
                {
                    ThrowHelper.ThrowInvalidOperationException(Resources.Exception_InvalidIkeV2Handle);
                }
                else if (ret != NativeMethods.SUCCESS)
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (pRasUpdateConn != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pRasUpdateConn);
                }
            }
        }
Example #5
0
        /// <summary>
        /// Sets the entry properties for an existing phone book entry, or creates a new entry.
        /// </summary>
        /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> that will contain the entry.</param>
        /// <param name="value">An <see cref="DotRas.RasEntry"/> object whose properties to set.</param>        
        /// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
        /// <exception cref="System.ArgumentNullException"><paramref name="phoneBook"/> or <paramref name="value"/> are a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="System.UnauthorizedAccessException">The caller does not have the required permission to perform the action requested.</exception>
        public bool SetEntryProperties(RasPhoneBook phoneBook, RasEntry value)
        {
            if (phoneBook == null)
            {
                ThrowHelper.ThrowArgumentNullException("phoneBook");
            }

            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException("value");
            }

            if (string.IsNullOrEmpty(value.Name))
            {
                ThrowHelper.ThrowArgumentException("Entry name", Resources.Argument_StringCannotBeNullOrEmpty);
            }

            if (!RasHelper.Instance.IsValidEntryName(phoneBook, value.Name, NativeMethods.ERROR_ALREADY_EXISTS, NativeMethods.ERROR_CANNOT_OPEN_PHONEBOOK))
            {
                ThrowHelper.ThrowArgumentException("entry name", Resources.Argument_InvalidEntryName, "entry name", value.Name);
            }

            // Ensure the entry meets the minimum requirements to create or update a phone book entry.
            if ((value.PhoneNumber == null && value.AlternatePhoneNumbers.Count == 0) || (value.Device == null || (value.Device != null && string.IsNullOrEmpty(value.Device.Name))) || value.FramingProtocol == RasFramingProtocol.None || value.EntryType == RasEntryType.None)
            {
                ThrowHelper.ThrowArgumentException("entry", Resources.Argument_MissingRequiredInfo);
            }

            bool retval = false;
            int size = Marshal.SizeOf(typeof(NativeMethods.RASENTRY));
            int lpCb = size;

            IntPtr lpRasEntry = IntPtr.Zero;
            try
            {
                NativeMethods.RASENTRY entry = new NativeMethods.RASENTRY();
                entry.size = size;

#pragma warning disable 0618
                entry.autoDialDll = value.AutoDialDll;
                entry.autoDialFunc = value.AutoDialFunc;
#pragma warning restore 0618

                entry.areaCode = value.AreaCode;
                entry.channels = value.Channels;
                entry.countryCode = value.CountryCode;
                entry.countryId = value.CountryId;
                entry.customAuthKey = value.CustomAuthKey;
                entry.customDialDll = value.CustomDialDll;

                if (value.Device != null)
                {
                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(RasDeviceType));
                    if (converter == null)
                    {
                        ThrowHelper.ThrowInvalidOperationException(Resources.Exception_TypeConverterNotFound, "RasDeviceType");
                    }

                    entry.deviceName = value.Device.Name;
                    entry.deviceType = converter.ConvertToString(value.Device.DeviceType);
                }

                IPAddressConverter ipAddrConverter = new IPAddressConverter();

                entry.dialExtraPercent = value.DialExtraPercent;
                entry.dialExtraSampleSeconds = value.DialExtraSampleSeconds;
                entry.dialMode = value.DialMode;
                entry.dnsAddress = (NativeMethods.RASIPADDR)ipAddrConverter.ConvertTo(value.DnsAddress, typeof(NativeMethods.RASIPADDR));
                entry.dnsAddressAlt = (NativeMethods.RASIPADDR)ipAddrConverter.ConvertTo(value.DnsAddressAlt, typeof(NativeMethods.RASIPADDR));
                entry.encryptionType = value.EncryptionType;
                entry.entryType = value.EntryType;
                entry.frameSize = value.FrameSize;
                entry.framingProtocol = value.FramingProtocol;
                entry.hangUpExtraPercent = value.HangUpExtraPercent;
                entry.hangUpExtraSampleSeconds = value.HangUpExtraSampleSeconds;
                entry.id = value.Id;
                entry.idleDisconnectSeconds = value.IdleDisconnectSeconds;
                entry.ipAddress = (NativeMethods.RASIPADDR)ipAddrConverter.ConvertTo(value.IPAddress, typeof(NativeMethods.RASIPADDR));
                entry.networkProtocols = Utilities.GetRasNetworkProtocols(value.NetworkProtocols);
                entry.options = Utilities.GetRasEntryOptions(value);
                entry.phoneNumber = value.PhoneNumber;
                entry.script = value.Script;

                // This member should be set to zero and the subentries should be added after the entry has been created.
                entry.subentries = 0;

                entry.vpnStrategy = value.VpnStrategy;
                entry.winsAddress = (NativeMethods.RASIPADDR)ipAddrConverter.ConvertTo(value.WinsAddress, typeof(NativeMethods.RASIPADDR));
                entry.winsAddressAlt = (NativeMethods.RASIPADDR)ipAddrConverter.ConvertTo(value.WinsAddressAlt, typeof(NativeMethods.RASIPADDR));
                entry.x25Address = value.X25Address;
                entry.x25Facilities = value.X25Facilities;
                entry.x25PadType = value.X25PadType;
                entry.x25UserData = value.X25UserData;

#if (WINXP || WIN2K8 || WIN7 || WIN8)
                entry.options2 = Utilities.GetRasEntryExtendedOptions(value);
                entry.options3 = 0;
                entry.dnsSuffix = value.DnsSuffix;
                entry.tcpWindowSize = value.TcpWindowSize;
                entry.prerequisitePhoneBook = value.PrerequisitePhoneBook;
                entry.prerequisiteEntryName = value.PrerequisiteEntryName;
                entry.redialCount = value.RedialCount;
                entry.redialPause = value.RedialPause;
#endif
#if (WIN2K8 || WIN7 || WIN8)
                entry.ipv4InterfaceMetric = value.IPv4InterfaceMetric;
                entry.ipv6DnsAddress = (NativeMethods.RASIPV6ADDR)ipAddrConverter.ConvertTo(value.IPv6DnsAddress, typeof(NativeMethods.RASIPV6ADDR));
                entry.ipv6DnsAddressAlt = (NativeMethods.RASIPV6ADDR)ipAddrConverter.ConvertTo(value.IPv6DnsAddressAlt, typeof(NativeMethods.RASIPV6ADDR));
                entry.ipv6InterfaceMetric = value.IPv6InterfaceMetric;
#endif
#if (WIN7 || WIN8)
                entry.ipv6Address = (NativeMethods.RASIPV6ADDR)ipAddrConverter.ConvertTo(value.IPv6Address, typeof(NativeMethods.RASIPV6ADDR));
                entry.ipv6PrefixLength = value.IPv6PrefixLength;
                entry.networkOutageTime = value.NetworkOutageTime;
#endif

                int alternatesLength = 0;
                string alternatesList = Utilities.BuildStringList(value.AlternatePhoneNumbers, '\x00', out alternatesLength);
                if (alternatesLength > 0)
                {
                    lpCb = size + alternatesLength;
                    entry.alternateOffset = size;
                }

                lpRasEntry = Marshal.AllocHGlobal(lpCb);
                Marshal.StructureToPtr(entry, lpRasEntry, true);

                if (alternatesLength > 0)
                {
                    // Now that the pointer has been allocated, copy the string to the location.
                    Utilities.CopyString(lpRasEntry, size, alternatesList, alternatesLength);
                }

                try
                {
                    int ret = UnsafeNativeMethods.Instance.SetEntryProperties(phoneBook.Path, value.Name, lpRasEntry, lpCb, IntPtr.Zero, 0);
                    if (ret == NativeMethods.ERROR_ACCESS_DENIED)
                    {
                        ThrowHelper.ThrowUnauthorizedAccessException(Resources.Exception_AccessDeniedBySecurity);
                    }
                    else if (ret == NativeMethods.ERROR_INVALID_PARAMETER)
                    {
                        ThrowHelper.ThrowArgumentException("entry", Resources.Argument_InvalidOrConflictingEntrySettings);
                    }
                    else if (ret == NativeMethods.SUCCESS)
                    {
                        retval = true;

                        if (value.SubEntries.Count > 0)
                        {
                            // The entry has subentries associated with it, add them to the phone book.
                            for (int index = 0; index < value.SubEntries.Count; index++)
                            {
                                RasSubEntry subEntry = value.SubEntries[index];
                                if (subEntry != null)
                                {
                                    RasHelper.Instance.SetSubEntryProperties(value.Owner, value, index, subEntry);
                                }
                            }
                        }

                        if (value.Id == Guid.Empty)
                        {
                            // The entry being set is new, update any properties that need an existing entry.
                            RasEntry newEntry = null;
                            try
                            {
                                // Grab the entry from the phone book.
                                newEntry = RasHelper.Instance.GetEntryProperties(phoneBook, value.Name);
                                value.Id = newEntry.Id;
                            }
                            finally
                            {
                                newEntry = null;
                            }
                        }
                    }
                    else
                    {
                        ThrowHelper.ThrowRasException(ret);
                    }
                }
                catch (EntryPointNotFoundException)
                {
                    ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
                }
            }
            finally
            {
                if (lpRasEntry != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpRasEntry);
                }
            }

            return retval;
        }
Example #6
0
        public object GetProjectionInfo(RasHandle handle, NativeMethods.RASPROJECTION projection)
        {
            if (Utilities.IsHandleInvalidOrClosed(handle))
            {
                ThrowHelper.ThrowArgumentException("handle", Resources.Argument_InvalidHandle);
            }

            int size = 0;

            object retval = null;
            object structure = null;

            switch (projection)
            {
                case NativeMethods.RASPROJECTION.Amb:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASAMB));

                    NativeMethods.RASAMB amb = new NativeMethods.RASAMB();
                    amb.size = size;

                    structure = amb;
                    break;

                case NativeMethods.RASPROJECTION.Ccp:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPCCP));

                    NativeMethods.RASPPPCCP ccp = new NativeMethods.RASPPPCCP();
                    ccp.size = size;

                    structure = ccp;
                    break;

                case NativeMethods.RASPROJECTION.IP:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIP));

                    NativeMethods.RASPPPIP ip = new NativeMethods.RASPPPIP();
                    ip.size = size;

                    structure = ip;
                    break;

                case NativeMethods.RASPROJECTION.Ipx:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIPX));

                    NativeMethods.RASPPPIPX ipx = new NativeMethods.RASPPPIPX();
                    ipx.size = size;

                    structure = ipx;
                    break;

                case NativeMethods.RASPROJECTION.Lcp:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPLCP));

                    NativeMethods.RASPPPLCP lcp = new NativeMethods.RASPPPLCP();
                    lcp.size = size;

                    structure = lcp;
                    break;

                case NativeMethods.RASPROJECTION.Nbf:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPNBF));

                    NativeMethods.RASPPPNBF nbf = new NativeMethods.RASPPPNBF();
                    nbf.size = size;

                    structure = nbf;
                    break;

#if (WIN2K8 || WIN7 || WIN8)

                case NativeMethods.RASPROJECTION.IPv6:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIPV6));

                    NativeMethods.RASPPPIPV6 ipv6 = new NativeMethods.RASPPPIPV6();
                    ipv6.size = size;

                    structure = ipv6;
                    break;

#endif
                case NativeMethods.RASPROJECTION.Slip:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASSLIP));

                    NativeMethods.RASSLIP slip = new NativeMethods.RASSLIP();
                    slip.size = size;

                    structure = slip;
                    break;
            }

            IntPtr lpCb = new IntPtr(size);

            IntPtr lpProjection = IntPtr.Zero;
            try
            {
                lpProjection = Marshal.AllocHGlobal(lpCb);
                Marshal.StructureToPtr(structure, lpProjection, true);

                int ret = SafeNativeMethods.Instance.GetProjectionInfo(handle, projection, lpProjection, ref lpCb);
                if (ret == NativeMethods.SUCCESS)
                {
                    IPAddressConverter converter = new IPAddressConverter();

                    switch (projection)
                    {
                        case NativeMethods.RASPROJECTION.Amb:
                            NativeMethods.RASAMB amb = Utilities.PtrToStructure<NativeMethods.RASAMB>(lpProjection);

                            retval = new RasAmbInfo(
                                amb.errorCode,
                                amb.netBiosError,
                                amb.lana);

                            break;

                        case NativeMethods.RASPROJECTION.Ccp:
                            NativeMethods.RASPPPCCP ccp = Utilities.PtrToStructure<NativeMethods.RASPPPCCP>(lpProjection);

                            retval = new RasCcpInfo(
                                ccp.errorCode,
                                ccp.compressionAlgorithm,
                                new RasCompressionOptions(ccp.options),
                                ccp.serverCompressionAlgorithm,
                                new RasCompressionOptions(ccp.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.IP:
                            NativeMethods.RASPPPIP ip = Utilities.PtrToStructure<NativeMethods.RASPPPIP>(lpProjection);

                            retval = new RasIPInfo(
                                ip.errorCode,
                                (IPAddress)converter.ConvertFrom(ip.ipAddress),
                                (IPAddress)converter.ConvertFrom(ip.serverIPAddress),
                                new RasIPOptions(ip.options),
                                new RasIPOptions(ip.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.Ipx:
                            NativeMethods.RASPPPIPX ipx = Utilities.PtrToStructure<NativeMethods.RASPPPIPX>(lpProjection);

                            retval = new RasIpxInfo(
                                ipx.errorCode,
                                (IPAddress)converter.ConvertFrom(ipx.ipxAddress));

                            break;

                        case NativeMethods.RASPROJECTION.Lcp:
                            NativeMethods.RASPPPLCP lcp = Utilities.PtrToStructure<NativeMethods.RASPPPLCP>(lpProjection);

                            retval = new RasLcpInfo(
                                lcp.bundled,
                                lcp.errorCode,
                                lcp.authenticationProtocol,
                                lcp.authenticationData,
                                lcp.eapTypeId,
                                lcp.serverAuthenticationProtocol,
                                lcp.serverAuthenticationData,
                                lcp.serverEapTypeId,
                                lcp.multilink,
                                lcp.terminateReason,
                                lcp.serverTerminateReason,
                                lcp.replyMessage,
                                new RasLcpOptions(lcp.options),
                                new RasLcpOptions(lcp.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.Nbf:
                            NativeMethods.RASPPPNBF nbf = Utilities.PtrToStructure<NativeMethods.RASPPPNBF>(lpProjection);

                            retval = new RasNbfInfo(
                                nbf.errorCode,
                                nbf.netBiosErrorCode,
                                nbf.netBiosErrorMessage,
                                nbf.workstationName,
                                nbf.lana);

                            break;

                        case NativeMethods.RASPROJECTION.Slip:
                            NativeMethods.RASSLIP slip = Utilities.PtrToStructure<NativeMethods.RASSLIP>(lpProjection);

                            retval = new RasSlipInfo(
                                slip.errorCode,
                                (IPAddress)converter.ConvertFrom(slip.ipAddress));

                            break;

#if (WIN2K8 || WIN7 || WIN8)
                        case NativeMethods.RASPROJECTION.IPv6:
                            NativeMethods.RASPPPIPV6 ipv6 = Utilities.PtrToStructure<NativeMethods.RASPPPIPV6>(lpProjection);

                            retval = new RasIPv6Info(
                                ipv6.errorCode,
                                Utilities.ConvertBytesToInt64(ipv6.localInterfaceIdentifier, 0),
                                Utilities.ConvertBytesToInt64(ipv6.peerInterfaceIdentifier, 0),
                                Utilities.ConvertBytesToInt16(ipv6.localCompressionProtocol, 0),
                                Utilities.ConvertBytesToInt16(ipv6.peerCompressionProtocol, 0));

                            break;
#endif
                    }
                }
                else if (ret != NativeMethods.ERROR_INVALID_PARAMETER && ret != NativeMethods.ERROR_PROTOCOL_NOT_CONFIGURED)
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (lpProjection != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpProjection);
                }
            }

            return retval;
        }
        public void ConvertFromRASIPADDRTest()
        {
            byte[] expected = IPAddress.Loopback.GetAddressBytes();

            NativeMethods.RASIPADDR value = new NativeMethods.RASIPADDR();
            value.addr = expected;

            IPAddressConverter target = new IPAddressConverter();
            IPAddress result = (IPAddress)target.ConvertFrom(value);

            byte[] actual = result.GetAddressBytes();

            Assert.AreEqual<System.Net.Sockets.AddressFamily>(System.Net.Sockets.AddressFamily.InterNetwork, result.AddressFamily);
            CollectionAssert.AreEqual(expected, actual);
        }
 public void ConvertFromUnsupportedTypeTest()
 {
     IPAddressConverter target = new IPAddressConverter();
     target.ConvertFrom(true);
 }
        public void ConvertToIPv6RASTUNNELENDPOINTTest()
        {
            byte[] expected = IPAddress.IPv6Loopback.GetAddressBytes();

            IPAddressConverter target = new IPAddressConverter();
            NativeMethods.RASTUNNELENDPOINT result = (NativeMethods.RASTUNNELENDPOINT)target.ConvertTo(IPAddress.IPv6Loopback, typeof(NativeMethods.RASTUNNELENDPOINT));

            byte[] actual = result.addr;

            Assert.AreEqual<NativeMethods.RASTUNNELENDPOINTTYPE>(NativeMethods.RASTUNNELENDPOINTTYPE.IPv6, result.type);
            CollectionAssert.AreEqual(expected, actual);
        }
        public void ConvertFromUnknownRASTUNNELENDPOINTTest()
        {
            NativeMethods.RASTUNNELENDPOINT value = new NativeMethods.RASTUNNELENDPOINT();
            value.type = NativeMethods.RASTUNNELENDPOINTTYPE.Unknown;

            IPAddressConverter target = new IPAddressConverter();
            IPAddress result = (IPAddress)target.ConvertFrom(value);

            Assert.IsNull(result);
        }
        public void ConvertFromIPv6RASTUNNELENDPOINTTest()
        {
            byte[] expected = IPAddress.IPv6Loopback.GetAddressBytes();

            NativeMethods.RASTUNNELENDPOINT value = new NativeMethods.RASTUNNELENDPOINT();
            value.type = NativeMethods.RASTUNNELENDPOINTTYPE.IPv6;
            value.addr = expected;

            IPAddressConverter target = new IPAddressConverter();
            IPAddress result = (IPAddress)target.ConvertFrom(value);

            byte[] actual = result.GetAddressBytes();

            Assert.AreEqual<System.Net.Sockets.AddressFamily>(System.Net.Sockets.AddressFamily.InterNetworkV6, result.AddressFamily);
            CollectionAssert.AreEqual(expected, actual);
        }
        public void ConvertToRASIPV6ADDRFromNullTest()
        {
            byte[] expected = IPAddress.IPv6Any.GetAddressBytes();

            IPAddressConverter target = new IPAddressConverter();
            NativeMethods.RASIPV6ADDR result = (NativeMethods.RASIPV6ADDR)target.ConvertTo(null, typeof(NativeMethods.RASIPV6ADDR));

            byte[] actual = result.addr;

            CollectionAssert.AreEqual(expected, actual);
        }
 public void ConvertToUnsupportedTypeTest()
 {
     IPAddressConverter target = new IPAddressConverter();
     target.ConvertTo(null, typeof(bool));
 }
 public void ConvertToRASIPADDRFromIPv6Test()
 {
     IPAddressConverter target = new IPAddressConverter();
     target.ConvertTo(IPAddress.IPv6Loopback, typeof(NativeMethods.RASIPADDR));
 }
        public void ConvertToRASIPADDRTest()
        {
            byte[] expected = IPAddress.Loopback.GetAddressBytes();

            IPAddressConverter target = new IPAddressConverter();
            NativeMethods.RASIPADDR result = (NativeMethods.RASIPADDR)target.ConvertTo(IPAddress.Loopback, typeof(NativeMethods.RASIPADDR));

            byte[] actual = result.addr;

            CollectionAssert.AreEqual(expected, actual);
        }
Example #16
0
        /// <summary>
        /// Retrieves the connection status for the handle specified.
        /// </summary>
        /// <param name="handle">The remote access connection handle to retrieve.</param>
        /// <returns>A <see cref="DotRas.RasConnectionStatus"/> object containing connection status information.</returns>
        /// <exception cref="DotRas.InvalidHandleException"><paramref name="handle"/> is not a valid handle.</exception>
        public RasConnectionStatus GetConnectionStatus(RasHandle handle)
        {
            RasConnectionStatus retval = null;

            IntPtr lpRasConnStatus = IntPtr.Zero;
            try
            {
                int size = Marshal.SizeOf(typeof(NativeMethods.RASCONNSTATUS));

                NativeMethods.RASCONNSTATUS status = new NativeMethods.RASCONNSTATUS();
                status.size = size;

                lpRasConnStatus = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(status, lpRasConnStatus, true);

                int ret = SafeNativeMethods.Instance.GetConnectStatus(handle, lpRasConnStatus);
                if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else if (ret == NativeMethods.SUCCESS)
                {
                    status = Utilities.PtrToStructure<NativeMethods.RASCONNSTATUS>(lpRasConnStatus);

                    string errorMessage = null;
                    if (status.errorCode != NativeMethods.SUCCESS)
                    {
                        errorMessage = RasHelper.Instance.GetRasErrorString(status.errorCode);
                    }

                    retval = new RasConnectionStatus();
                    retval.ConnectionState = status.connectionState;
                    retval.ErrorCode = status.errorCode;
                    retval.ErrorMessage = errorMessage;
                    retval.PhoneNumber = status.phoneNumber;

                    if (!string.IsNullOrEmpty(status.deviceName) && !string.IsNullOrEmpty(status.deviceType))
                    {
                        retval.Device = RasDevice.Create(status.deviceName, status.deviceType);
                    }

#if (WIN7 || WIN8)
                    IPAddressConverter converter = new IPAddressConverter();

                    retval.LocalEndPoint = (IPAddress)converter.ConvertFrom(status.localEndPoint);
                    retval.RemoteEndPoint = (IPAddress)converter.ConvertFrom(status.remoteEndPoint);
                    retval.ConnectionSubState = status.connectionSubState;
#endif
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (lpRasConnStatus != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpRasConnStatus);
                }
            }

            return retval;
        }
Example #17
0
        /// <summary>
        /// Retrieves the entry properties for an entry within a phone book.
        /// </summary>
        /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param>
        /// <param name="entryName">Required. The name of an entry to retrieve.</param>
        /// <returns>A <see cref="DotRas.RasEntry"/> object.</returns>
        /// <exception cref="System.ArgumentException"><paramref name="entryName"/> is an empty string or null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="System.ArgumentNullException"><paramref name="phoneBook"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="System.UnauthorizedAccessException">The caller does not have the required permission to perform the action requested.</exception>
        public RasEntry GetEntryProperties(RasPhoneBook phoneBook, string entryName)
        {
            if (phoneBook == null)
            {
                ThrowHelper.ThrowArgumentNullException("phoneBook");
            }

            if (string.IsNullOrEmpty(entryName))
            {
                ThrowHelper.ThrowArgumentException("entryName", Resources.Argument_StringCannotBeNullOrEmpty);
            }

            RasEntry retval = null;

            int size = Marshal.SizeOf(typeof(NativeMethods.RASENTRY));
            bool retry = false;

            IntPtr lpCb = new IntPtr(size);
            do
            {
                NativeMethods.RASENTRY entry = new NativeMethods.RASENTRY();
                entry.size = size;

                IntPtr lpRasEntry = IntPtr.Zero;
                try
                {
                    lpRasEntry = Marshal.AllocHGlobal(lpCb);
                    Marshal.StructureToPtr(entry, lpRasEntry, true);

                    try
                    {
                        int ret = UnsafeNativeMethods.Instance.GetEntryProperties(phoneBook.Path, entryName, lpRasEntry, ref lpCb, IntPtr.Zero, IntPtr.Zero);
                        if (ret == NativeMethods.SUCCESS)
                        {
                            entry = Utilities.PtrToStructure<NativeMethods.RASENTRY>(lpRasEntry);

                            retval = new RasEntry(entryName);

                            if (entry.alternateOffset != 0)
                            {                                
                                retval.AlternatePhoneNumbers = Utilities.CreateStringCollectionByLength(lpRasEntry, entry.alternateOffset, lpCb.ToInt32() - entry.alternateOffset);
                            }

                            if (entry.subentries > 1)
                            {
                                // The first subentry in the collection is always the default entry, need to check if there are two or
                                // more subentries before loading the collection.
                                retval.SubEntries.Load(phoneBook, entry.subentries - 1);
                            }

                            retval.AreaCode = entry.areaCode;

// This warning is being disabled since the object is being loaded by the Win32 API and must have the
// data placed into the object.
#pragma warning disable 0618
                            retval.AutoDialDll = entry.autoDialDll;
                            retval.AutoDialFunc = entry.autoDialFunc;
#pragma warning restore 0618

                            retval.Channels = entry.channels;
                            retval.CountryCode = entry.countryCode;
                            retval.CountryId = entry.countryId;
                            retval.CustomAuthKey = entry.customAuthKey;
                            retval.CustomDialDll = entry.customDialDll;

                            if (entry.deviceName != null && !string.IsNullOrEmpty(entry.deviceType))
                            {
                                retval.Device = RasDevice.Create(entry.deviceName, entry.deviceType);
                            }

                            IPAddressConverter ipAddrConverter = new IPAddressConverter();

                            retval.DialExtraPercent = entry.dialExtraPercent;
                            retval.DialExtraSampleSeconds = entry.dialExtraSampleSeconds;
                            retval.DialMode = entry.dialMode;
                            retval.DnsAddress = (IPAddress)ipAddrConverter.ConvertFrom(entry.dnsAddress);
                            retval.DnsAddressAlt = (IPAddress)ipAddrConverter.ConvertFrom(entry.dnsAddressAlt);
                            retval.EncryptionType = entry.encryptionType;
                            retval.EntryType = entry.entryType;
                            retval.FrameSize = entry.frameSize;
                            retval.FramingProtocol = entry.framingProtocol;
                            retval.HangUpExtraPercent = entry.hangUpExtraPercent;
                            retval.HangUpExtraSampleSeconds = entry.hangUpExtraSampleSeconds;
                            retval.Id = entry.id;
                            retval.IdleDisconnectSeconds = entry.idleDisconnectSeconds;
                            retval.IPAddress = (IPAddress)ipAddrConverter.ConvertFrom(entry.ipAddress);
                            retval.PhoneNumber = entry.phoneNumber;
                            retval.Script = entry.script;
                            retval.VpnStrategy = entry.vpnStrategy;
                            retval.WinsAddress = (IPAddress)ipAddrConverter.ConvertFrom(entry.winsAddress);
                            retval.WinsAddressAlt = (IPAddress)ipAddrConverter.ConvertFrom(entry.winsAddressAlt);
                            retval.X25Address = entry.x25Address;
                            retval.X25Facilities = entry.x25Facilities;
                            retval.X25PadType = entry.x25PadType;
                            retval.X25UserData = entry.x25UserData;

                            Utilities.SetRasEntryOptions(retval, entry.options);
                            Utilities.SetRasNetworkProtocols(retval, entry.networkProtocols);

#if (WINXP || WIN2K8 || WIN7 || WIN8)

                            Utilities.SetRasEntryExtendedOptions(retval, entry.options2);

                            retval.DnsSuffix = entry.dnsSuffix;
                            retval.TcpWindowSize = entry.tcpWindowSize;
                            retval.PrerequisitePhoneBook = entry.prerequisitePhoneBook;
                            retval.PrerequisiteEntryName = entry.prerequisiteEntryName;
                            retval.RedialCount = entry.redialCount;
                            retval.RedialPause = entry.redialPause;
#endif
#if (WIN2K8 || WIN7 || WIN8)
                            retval.IPv6DnsAddress = (IPAddress)ipAddrConverter.ConvertFrom(entry.ipv6DnsAddress);
                            retval.IPv6DnsAddressAlt = (IPAddress)ipAddrConverter.ConvertFrom(entry.ipv6DnsAddressAlt);
                            retval.IPv4InterfaceMetric = entry.ipv4InterfaceMetric;
                            retval.IPv6InterfaceMetric = entry.ipv6InterfaceMetric;
#endif
#if (WIN7 || WIN8)
                            retval.IPv6Address = (IPAddress)ipAddrConverter.ConvertFrom(entry.ipv6Address);
                            retval.IPv6PrefixLength = entry.ipv6PrefixLength;
                            retval.NetworkOutageTime = entry.networkOutageTime;
#endif

                            retry = false;
                        }
                        else if (ret == NativeMethods.ERROR_BUFFER_TOO_SMALL)
                        {
                            retry = true;
                        }
                        else
                        {
                            ThrowHelper.ThrowRasException(ret);
                        }
                    }
                    catch (EntryPointNotFoundException)
                    {
                        ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
                    }
                }
                finally
                {
                    if (lpRasEntry != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(lpRasEntry);
                    }
                }
            }
            while (retry);

            return retval;
        }
        public void ConvertFromStringTest()
        {
            string expected = IPAddress.Loopback.ToString();

            IPAddressConverter target = new IPAddressConverter();
            IPAddress result = (IPAddress)target.ConvertFrom(expected);

            Assert.IsNotNull(result);

            string actual = result.ToString();

            Assert.AreEqual(expected, actual, true);
        }