public void GetSubEntryHandleTest() { RasHandle expected = new RasHandle(new IntPtr(1), true); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetSubEntryHandle(It.IsAny <RasHandle>(), It.IsAny <int>())).Returns(expected); RasConnection target = new RasConnection(); RasHandle actual = target.GetSubEntryHandle(1); Assert.AreSame(expected, actual); }
public void GetNapStatusTest() { RasNapStatus expected = new RasNapStatus(RasIsolationState.Unknown, DateTime.MinValue); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetNapStatus(It.IsAny <RasHandle>())).Returns(expected); RasConnection target = new RasConnection(); RasNapStatus actual = target.GetNapStatus(); Assert.AreSame(expected, actual); }
public void GetProjectionInfoLcpTest() { RasLcpInfo expected = new RasLcpInfo(false, 0, RasLcpAuthenticationType.None, RasLcpAuthenticationDataType.None, 0, RasLcpAuthenticationType.None, RasLcpAuthenticationDataType.None, 0, false, 0, 0, null, new RasLcpOptions(), new RasLcpOptions()); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfo(It.IsAny <RasHandle>(), NativeMethods.RASPROJECTION.Lcp)).Returns(expected); RasConnection target = new RasConnection(); RasLcpInfo actual = (RasLcpInfo)target.GetProjectionInfo(RasProjectionType.Lcp); Assert.AreSame(expected, actual); }
public void ClearLinkStatisticsTest() { bool expected = true; Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.ClearLinkStatistics(It.IsAny <RasHandle>(), It.IsAny <int>())).Returns(expected); RasConnection target = new RasConnection(); bool actual = target.ClearLinkStatistics(); Assert.AreEqual(expected, actual); }
public void GetLinkStatisticsTest() { RasLinkStatistics expected = new RasLinkStatistics(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TimeSpan.MinValue); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetLinkStatistics(It.IsAny <RasHandle>(), It.IsAny <int>())).Returns(expected); RasConnection target = new RasConnection(); RasLinkStatistics actual = target.GetLinkStatistics(); Assert.AreSame(expected, actual); }
public void ConnectionOptionsTest() { RasConnectionOptions expected = new RasConnectionOptions() { AllUsers = true }; RasConnection target = new RasConnection(); target.ConnectionOptions = expected; RasConnectionOptions actual = target.ConnectionOptions; Assert.AreSame(expected, actual); }
public void GetProjectionInfoIPv6Test() { RasIPv6Info expected = new RasIPv6Info(0, 0, 0, 0, 0); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Default = mock.Object; mock.Setup(o => o.GetProjectionInfo(It.IsAny <RasHandle>(), NativeMethods.RASPROJECTION.IPv6)).Returns(expected); RasConnection target = new RasConnection(); RasIPv6Info actual = (RasIPv6Info)target.GetProjectionInfo(RasProjectionType.IPv6); Assert.AreSame(expected, actual); }
private void GetAddressButton_Click(object sender, EventArgs e) { foreach (RasConnection connection in RasConnection.GetActiveConnections()) { if (connection.EntryId == (Guid)((ComboBoxItem)this.ConnectionsComboBox.SelectedItem).Value) { RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP); if (ipAddresses != null) { this.ClientAddressTextBox.Text = ipAddresses.IPAddress.ToString(); this.ServerAddressTextBox.Text = ipAddresses.ServerIPAddress.ToString(); } } } }
private void DisconnectButton_Click(object sender, RoutedEventArgs e) { if (this.dialer.IsBusy) { this.dialer.DialAsyncCancel(); } else { RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle); if (connection != null) { connection.HangUp(); } } }
public void GetProjectionInfoNullApiResultTest() { RasPppInfo expected = null; Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfoEx(It.IsAny <RasHandle>())).Returns(expected); RasConnection target = new RasConnection(); RasPppInfo actual = (RasPppInfo)target.GetProjectionInfo(RasProjectionType.Ppp); Assert.AreEqual(expected, actual); }
public void GetProjectionInfoPppTest() { RasPppInfo expected = new RasPppInfo(0, IPAddress.Any, IPAddress.Any, new RasIPOptions(NativeMethods.RASIPO.None), new RasIPOptions(NativeMethods.RASIPO.None), 0, null, null, false, false, RasLcpAuthenticationType.None, RasLcpAuthenticationDataType.None, RasLcpAuthenticationType.None, RasLcpAuthenticationDataType.None, 0, 0, new RasLcpOptions(), new RasLcpOptions(), RasCompressionType.None, RasCompressionType.None, new RasCompressionOptions(), new RasCompressionOptions()); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfoEx(It.IsAny <RasHandle>())).Returns(expected); RasConnection target = new RasConnection(); RasPppInfo actual = (RasPppInfo)target.GetProjectionInfo(RasProjectionType.Ppp); Assert.AreSame(expected, actual); }
public void GetProjectionInfoIpxTest() { RasIpxInfo expected = new RasIpxInfo(0, IPAddress.Any); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfo(It.IsAny <RasHandle>(), NativeMethods.RASPROJECTION.Ipx)).Returns(expected); RasConnection target = new RasConnection(); RasIpxInfo actual = (RasIpxInfo)target.GetProjectionInfo(RasProjectionType.Ipx); Assert.AreSame(expected, actual); }
/// <summary> /// Interrupts connection made with RAS. /// </summary> private void DisconnectRasConn() { Task.Run(() => { var connections = RasConnection.GetActiveConnections(); foreach (var c in connections) { if (c.Handle == _handle) { c.HangUp(); } } }); }
public void GetProjectionInfoIkeV2Test() { RasIkeV2Info expected = new RasIkeV2Info(0, IPAddress.Any, IPAddress.Any, 0, IPAddress.Any, IPAddress.Any, 0, RasIkeV2AuthenticationType.None, 0, new RasIkeV2Options(), RasIPSecEncryptionType.None, null, null); Mock <IRasHelper> mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfoEx(It.IsAny <RasHandle>())).Returns(expected); RasConnection target = new RasConnection(); RasIkeV2Info actual = (RasIkeV2Info)target.GetProjectionInfo(RasProjectionType.IkeV2); Assert.AreSame(expected, actual); }
public void Disconnect() { if (RD.IsBusy) { RD.DialAsyncCancel(); } else { RasConnection Connection = RasConnection.GetActiveConnectionByHandle(Handle); if (Connection != null) { Connection.HangUp(); RemoveAdaptor(); } } }
public void GetProjectionInfoPppNullResultTest() { RasPppInfo expected = null; var result = new RasIkeV2Info(0, IPAddress.Any, IPAddress.Any, 0, IPAddress.Any, IPAddress.Any, 0, RasIkeV2AuthenticationType.None, 0, new RasIkeV2Options(), RasIPSecEncryptionType.None, null, null); var mock = new Mock <IRasHelper>(); RasHelper.Instance = mock.Object; mock.Setup(o => o.GetProjectionInfoEx(It.IsAny <RasHandle>())).Returns(result); var target = new RasConnection(); var actual = (RasPppInfo)target.GetProjectionInfo(RasProjectionType.Ppp); Assert.AreEqual(expected, actual); }
/// <summary> /// Occurs when the user clicks the Disconnect button. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param> private void DisconnectButton_Click(object sender, EventArgs e) { if (Dialer.IsBusy) { // The connection attempt has not been completed, cancel the attempt. Dialer.DialAsyncCancel(); } else { // The connection attempt has completed, attempt to find the connection in the active connections. var connection = RasConnection.GetActiveConnections().FirstOrDefault(_ => _.Handle == handle); // The connection has been found, disconnect it. connection?.HangUp(); } }
/// <summary> /// 断开所有连接 /// </summary> public static void Hangup() { try { foreach (RasConnection conn in RasConnection.GetActiveConnections()) { conn.HangUp(); } PPPoEHangupSuccessEvent?.Invoke(null, null); } catch (Exception e) { Utils.Log4Net.WriteLog(e.Message, e); PPPoEHangupFailEvent?.Invoke(null, new Msg(e.Message)); } }
private void button_getIP_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); foreach (RasConnection connection in RasConnection.GetActiveConnections()) { RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP); if (ipAddresses != null) { sb.AppendFormat("ClientIP:{0}\r\n", ipAddresses.IPAddress.ToString()); sb.AppendFormat("ServerIP:{0}\r\n", ipAddresses.ServerIPAddress.ToString()); } sb.AppendLine(); } MessageBox.Show(sb.ToString()); }
public bool ConnectVPN() { try { DisconnectVPN(); string _server = GetVPNServers(isLimitedToJapan); conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == ConnectionName).FirstOrDefault(); if (conn != null) { conn.HangUp(); Console.WriteLine("VPN Disconnected!"); } Master(_server); RasDialer dialer = new RasDialer(); dialer.EntryName = ConnectionName; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new NetworkCredential("vpn", "vpn"); //dialer.EapOptions = new DotRas.RasEapOptions(false, false, false); //dialer.HangUpPollingInterval = 0; //dialer.Options = new DotRas.RasDialOptions(false, false, false, false, false, false, false, false, false, false); dialer.DialCompleted += new System.EventHandler <DialCompletedEventArgs>(dialer_DialCompleted); dialer.StateChanged += new System.EventHandler <StateChangedEventArgs>(dialer_StateChanged); //dialer.DialAsync(); dialer.Dial(); //Console.ReadLine(); //DisplayIPAddresses(); //Console.ReadLine(); isConnected = true; } catch { isConnected = false; Dispose(); } return(isConnected); }
/// <summary> /// Connect /// </summary> /// <param name="connectName"></param> /// <param name="userName"></param> /// <param name="password"></param> public static void Connect(string connectName, string userName, string password) { //关闭现有连接 IReadOnlyCollection <RasConnection> conns = RasConnection.GetActiveConnections(); if (conns.Count != 0) { foreach (var conn in conns) { conn.HangUp(); } } RasPhoneBook rasPhoneBook = new RasPhoneBook(); string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); rasPhoneBook.Open(path); //创建一个新的PPPOE连接 IReadOnlyCollection <RasDevice> rasDevices = RasDevice.GetDevices(); RasDevice device = rasDevices.First(d => d.DeviceType == RasDeviceType.PPPoE); var entry = RasEntry.CreateBroadbandEntry(connectName, device); entry.PhoneNumber = userName; //如果不存在该名字的用户名和密码的连接,则Add 存在则更新 if (!rasPhoneBook.Entries.Contains(connectName)) { rasPhoneBook.Entries.Add(entry); } else { rasPhoneBook.Entries[connectName].Update(); } RasDialer dialer = new RasDialer { EntryName = connectName, PhoneNumber = userName, AllowUseStoredCredentials = true, PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers), Credentials = new NetworkCredential(userName, password), Timeout = 1000 * 10 }; RasHandle rasHandle = dialer.Dial(); }
private void UpdateTrayIcon() { var connections = RasConnection.EnumerateConnections().ToList(); if (connections.Count != 0) { _trayIcon.Text = $"Connected to: {string.Join(", ", connections.Select(x => x.EntryName))}"; _trayIcon.Icon = _onIcon; } else { _trayIcon.Text = "Not connected"; _trayIcon.Icon = _offIcon; } var strip = _trayIcon.ContextMenuStrip; strip.Items.Clear(); foreach (var profile in GetProfiles()) { var connection = connections.FirstOrDefault(x => x.EntryName.Equals(profile)); strip.Items.Add( profile, connection != null ? _checkIcon : null, (s, e) => { if (connection != null) { connection.Disconnect(new CancellationToken()); } else { var dialer = new RasDialer { EntryName = profile }; dialer.Connect(); } }); } strip.Items.Add(new ToolStripSeparator()); strip.Items.Add("Exit", null, OnExit); }
/// <summary> /// 获取当前的ADSL ip /// </summary> /// <param name="ipAddress"></param> /// <param name="oldConn"></param> private string GetIPAddress() { string ipAddress = string.Empty; var conns = RasConnection.GetActiveConnections(); foreach (var conn in conns) { if (conn.Device.DeviceType == RasDeviceType.PPPoE) { RasIPInfo ipAddresses = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); ipAddress = ipAddresses.IPAddress.ToString(); return(ipAddress); } } return(string.Empty); }
void Btn_HungupClick(object sender, EventArgs e) { try { ReadOnlyCollection <RasConnection> conList = RasConnection.GetActiveConnections(); foreach (RasConnection con in conList) { con.HangUp(); } Thread.Sleep(1000); lb_Status.Text = "注销成功"; lb_IPAddr.Text = "已注销"; btn_Dialup.Enabled = true; btn_Hungup.Enabled = false; } catch (Exception) { lb_Status.Text = "注销出现异常"; } }
public void Disconnect() { Log.debug(TAG, "Disconnect dialer.EntryName : " + dialer.EntryName); if (dialer.IsBusy) { dialer.DialAsyncCancel(); } else { RasConnection connection = RasConnection.GetActiveConnectionByHandle(handle); if (connection != null) { connection.HangUp(); } } allUsersPhoneBook.Entries.Remove(VPNNAME); }
private void Disconnect() { if (_dialer.IsBusy) { _dialer.DialAsyncCancel(); } else if (_handle != null) { var activeConnectionByHandle = RasConnection.GetActiveConnections().FirstOrDefault(c => c.Handle == _handle); if (activeConnectionByHandle != null) { activeConnectionByHandle.HangUp(); } _handle = null; IsConnected = false; } }
public bool DisconnectDotras() { if (dialer.IsBusy) { dialer.DialAsyncCancel(); } else { RasConnection connection = RasConnection.GetActiveConnectionByHandle(handle); if (connection != null) { connection.HangUp(); } } return(true); }
private bool Login(string username, string password) { try { // F**k it! username = "******" + username; dialer.EntryName = ConnectionName; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new NetworkCredential(username, password); dialer.Timeout = 1000; dialer.StateChanged += Dialer_StateChanged; dialer.Error += Dialer_Error; info.rasHandle = dialer.Dial(); if (info.rasHandle.IsInvalid) { throw new Exception("拨号失败"); } else { Logger.Log("拨号成功"); RasConnection conn = RasConnection.GetActiveConnections(). Where(o => o.Handle == info.rasHandle).First(); if (conn == null) { throw new Exception("Unable to get active connection by handle"); } info.ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); Logger.Log("获得IP: " + info.ipaddr.IPAddress.ToString()); StartHeartBeat(); info.Connected = true; } return(true); } catch (Exception ex) { Logger.Log($"拨号异常({ex.Message})"); MessageBox.Show(ex.Message, "拨号异常"); return(false); } }
public static void Disconnect() { if (Global.Dialer.IsBusy) { Global.Dialer.DialAsyncCancel(); } else { if (Global.Handle != null) { ReadOnlyCollection <RasConnection> connections = RasConnection.GetActiveConnections(); foreach (RasConnection connection in connections) { connection?.HangUp(); } } } }
private void btnDisconnect_Click(object sender, EventArgs e) { foreach (RasConnection connection in RasConnection.GetActiveConnections()) { if (connection.EntryName.Equals(dial.EntryName)) { connection.HangUp(); btnDisconnect.Visible = false; btnConnect.Visible = true; cmbServerChoice.Enabled = true; while (proBarMain.Value > 0) { proBarMain.Value -= 1; } } } }
public static void ClassInitialize(TestContext context) { entryName = Guid.NewGuid().ToString(); phonebookPath = Path.GetTempFileName(); RasPhoneBook pbk = new RasPhoneBook(); pbk.Open(phonebookPath); entryId = TestUtilities.CreateValidVpnEntry(pbk, entryName); using (RasDialer dialer = new RasDialer()) { dialer.EntryName = entryName; dialer.PhoneBookPath = phonebookPath; dialer.Credentials = TestUtilities.GetValidCredentials(); handle = dialer.Dial(); } target = RasConnection.GetActiveConnectionById(entryId); }
/// <summary> /// Retrieves a read-only list of active connections. /// </summary> /// <returns>A new read-only collection of <see cref="DotRas.RasConnection"/> objects, or an empty collection if no active connections were found.</returns> public ReadOnlyCollection<RasConnection> GetActiveConnections() { ReadOnlyCollection<RasConnection> retval = null; int size = Marshal.SizeOf(typeof(NativeMethods.RASCONN)); StructBufferedPInvokeParams info = new StructBufferedPInvokeParams(); info.BufferSize = new IntPtr(size); info.Count = IntPtr.Zero; bool retry = false; do { NativeMethods.RASCONN conn = new NativeMethods.RASCONN(); conn.size = size; try { info.Address = Marshal.AllocHGlobal(info.BufferSize); Marshal.StructureToPtr(conn, info.Address, true); int ret = SafeNativeMethods.Instance.EnumConnections(info); if (ret == NativeMethods.ERROR_BUFFER_TOO_SMALL) { retry = true; } else if (ret == NativeMethods.SUCCESS) { retry = false; NativeMethods.RASCONN[] connections = Utilities.CreateArrayOfType<NativeMethods.RASCONN>( info.Address, size, info.Count.ToInt32()); RasConnection[] tempArray = null; if (connections == null || connections.Length == 0) { tempArray = new RasConnection[0]; } else { tempArray = new RasConnection[connections.Length]; for (int index = 0; index < connections.Length; index++) { NativeMethods.RASCONN current = connections[index]; RasConnection item = new RasConnection(); item.Handle = new RasHandle(current.handle, current.subEntryId > 1); item.EntryName = current.entryName; item.Device = RasDevice.Create(current.deviceName, current.deviceType); item.PhoneBookPath = current.phoneBook; item.SubEntryId = current.subEntryId; item.EntryId = current.entryId; #if (WINXP || WIN2K8 || WIN7 || WIN8) item.SessionId = current.sessionId; Utilities.SetRasConnectionOptions(item, current.connectionOptions); #endif #if (WIN2K8 || WIN7 || WIN8) item.CorrelationId = current.correlationId; #endif tempArray[index] = item; } } retval = new ReadOnlyCollection<RasConnection>(tempArray); } else { ThrowHelper.ThrowRasException(ret); } } catch (EntryPointNotFoundException) { ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform); } finally { if (info.Address != IntPtr.Zero) { Marshal.FreeHGlobal(info.Address); } } } while (retry); return retval; }