/// <summary> /// 创建或更新一个PPPOE连接(指定PPPOE名称) /// </summary> public void CreateOrUpdatePPPOE(string updatePPPOEname) { RasDialer dialer = new RasDialer(); RasPhoneBook allUsersPhoneBook = new RasPhoneBook(); string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); allUsersPhoneBook.Open(path); // 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址 if (allUsersPhoneBook.Entries.Contains(updatePPPOEname)) { allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " "; // 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用 allUsersPhoneBook.Entries[updatePPPOEname].Update(); } // 创建一个新PPPOE else { string adds = string.Empty; ReadOnlyCollection <RasDevice> readOnlyCollection = RasDevice.GetDevices(); // foreach (var col in readOnlyCollection) // { // adds += col.Name + ":" + col.DeviceType.ToString() + "|||"; // } // _log.Info("Devices are : " + adds); // Find the device that will be used to dial the connection. RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First(); RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device); //建立宽带连接Entry entry.PhoneNumber = " "; allUsersPhoneBook.Entries.Add(entry); } }
private bool VPN_Create() { //https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa377274(v=vs.85) string preSharedKey = "kit2020!^)!$)%^";//l2tp 공유기 키 RasVpnStrategy strategy = RasVpnStrategy.L2tpOnly; RasEntry vpnEntry = RasEntry.CreateVpnEntry(VPN_Name, VPN_Connection_IP, strategy, RasDevice.Create(VPN_Name, RasDeviceType.Vpn), false); // vpnEntry.Options.RequireDataEncryption = true; //데이터 암호화 vpnEntry.Options.UsePreSharedKey = true; //l2tp/ipsec vpnEntry.Options.UseLogOnCredentials = false; // 로그인 기록 저장 vpnEntry.Options.RequireMSChap = false; //Microsoft CHAP Version vpnEntry.Options.RequireMSChap2 = true; //Microsoft CHAP Version 2 (MS-CHAP v2) vpnEntry.DnsAddress = System.Net.IPAddress.Parse(VPN_Create_VirtualIP); vpnEntry.Options.RemoteDefaultGateway = false; //게이트웨이 0.0.0.0으로 RasPhoneBook phoneBook = new RasPhoneBook(); try { phoneBook.Open(); phoneBook.Entries.Add(vpnEntry); //vpn 생성 vpnEntry.UpdateCredentials(RasPreSharedKey.Client, preSharedKey); //l2tp 공유키 설정 return(true); } catch (Exception ex) { Exception FailText = ex; MessageBox.Show(string.Concat(ex.ToString(), "\n")); return(false); } }
private void DialButton_Click(object sender, RoutedEventArgs e) { this.StatusTextBox.Clear(); this.dialer = new RasDialer(); this.dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(dialer_DialCompleted); this.dialer.StateChanged += new EventHandler <StateChangedEventArgs>(dialer_StateChanged); this.dialer.EntryName = (string)this.ConnectionComboBox.SelectedValue; this.dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); // This allows the multi-threaded dialer to update information on the user interface without causing any threading problems. this.dialer.SynchronizingObject = new DispatcherSynchronizingObject(App.Current.Dispatcher); try { // Set the credentials the dialer should use. this.dialer.Credentials = new System.Net.NetworkCredential("Test", "User"); this.handle = this.dialer.DialAsync(); // Disable the button used to initiate dialing while the operation is in progress. this.DialButton.IsEnabled = false; this.DisconnectButton.IsEnabled = true; } catch (Exception ex) { this.StatusTextBox.AppendText(ex.ToString()); this.StatusTextBox.ScrollToEnd(); } }
private void BeginConnect() { string sServerip = tServerIP.Text; string sUsername = tUsername.Text; string sPassword = tUserkey.Text; sEntryName = tVpnName.Text; if (!CreateVpnEntry(sServerip)) { return; } this.Dialer.EntryName = sEntryName; this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); try { this.Dialer.Credentials = new NetworkCredential(sUsername, sPassword); var handle = this.Dialer.DialAsync(); DoMessage(string.Format("{0} 正在尝试连接...", DateTime.Now.ToString())); // 连接状态监控 connWatcher = new RasConnectionWatcher(); connWatcher.Handle = handle; connWatcher.Disconnected += ConnWatcher_Disconnected; connWatcher.EnableRaisingEvents = true; } catch (Exception ex) { this.tMessage.AppendText(ex.ToString()); } }
Boolean DialUp() { try { using (var phoneBook = new RasPhoneBook()) { var name = VpnConfig.GetConfig().ConnectionName; var user = VpnConfig.GetConfig().Username; var pass = VpnConfig.GetConfig().Password; var pbPath = VpnConfig.GetConfig().PhoneBookPath; phoneBook.Open(pbPath); var entry = phoneBook.Entries.FirstOrDefault(e => e.Name.Equals(name)); if (entry != null) { using (var dialer = new RasDialer()) { dialer.EntryName = name; dialer.Credentials = new NetworkCredential(user, pass); dialer.PhoneBookPath = pbPath; dialer.Dial(); } } else { throw new ArgumentException( message: "entry wasn't found: " + name, paramName: "entry" ); } } return(true); } catch { // log the exception return(false); } }
public static void CreateVPN() { VPNHelper vpn = new VPNHelper(); using (DotRas.RasDialer dialer = new DotRas.RasDialer()) { DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook(); allUsersPhoneBook.Open(); if (allUsersPhoneBook.Entries.Contains(VPNConnectionName)) { return; } RasEntry entry = RasEntry.CreateVpnEntry(VPNConnectionName, IPToPing, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn)); allUsersPhoneBook.Entries.Add(entry); dialer.EntryName = VPNConnectionName; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); try { dialer.Credentials = new NetworkCredential(UserName, Password); dialer.DialAsync(); } catch (Exception) { return; } } }
public void CreateCustomPhoneBookTest() { var tempFolder = TestUtilities.GetTempPath(true); string path = null; try { path = Path.Combine(tempFolder.FullName, string.Format("{0}.pbk", TestUtilities.StripNonAlphaNumericChars(Guid.NewGuid().ToString()))); var target = new RasPhoneBook(); target.Open(path); var device = RasDevice.GetDevices().Where(o => o.Name.Contains("(PPTP)") && o.DeviceType == RasDeviceType.Vpn).FirstOrDefault(); var entry = RasEntry.CreateVpnEntry("Test Entry", IPAddress.Loopback.ToString(), RasVpnStrategy.Default, device); if (entry != null) { target.Entries.Add(entry); } Assert.IsTrue(File.Exists(path), "The phone book file was not found at the expected location. '{0}'", path); } finally { if (Directory.Exists(tempFolder.FullName)) { // The folder was created successfully, delete it before the test completes. Directory.Delete(tempFolder.FullName, true); } } }
public void CreateConnect(string ConnectName) { RasDialer dialer = new RasDialer(); RasPhoneBook book = new RasPhoneBook(); try { book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User)); if (book.Entries.Contains(ConnectName)) { book.Entries[ConnectName].PhoneNumber = " "; book.Entries[ConnectName].Update(); } else { System.Collections.ObjectModel.ReadOnlyCollection <RasDevice> readOnlyCollection = RasDevice.GetDevices(); RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First(); RasEntry entry = RasEntry.CreateBroadbandEntry(ConnectName, device); entry.PhoneNumber = " "; book.Entries.Add(entry); } } catch (Exception) { lb_status.Content = "创建PPPoE连接失败"; } }
// Token: 0x06000096 RID: 150 RVA: 0x000060EC File Offset: 0x000042EC public RasHandle ConnectVPNbyPriority(RasDialer myDialer, RasPhoneBook myPB, string server, string sVPNPrefix, string sLogin, string sPass, string sPath) { int windowsVersion = this.GetWindowsVersion(); RasHandle result = null; if (windowsVersion == this.VER_XP || windowsVersion == this.VER_VISTA) { myPB = this.SetPhoneBookPPTP(server, myPB, sVPNPrefix); } else if (windowsVersion == this.VER_W7 || windowsVersion == this.VER_W8) { myPB = this.SetPhoneBookPPTP(server, myPB, sVPNPrefix); } myDialer.EntryName = sVPNPrefix; myDialer.PhoneBookPath = sPath; myDialer.AllowUseStoredCredentials = true; try { myDialer.Credentials = new NetworkCredential(sLogin, sPass); result = myDialer.DialAsync(); } catch (Exception ex) { } return(result); }
void Dial() { this.Dialer.EntryName = EntryName; this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); try { if (this.Dialer.IsBusy) { return; } // Set the credentials the dialer should use. this.Dialer.Credentials = new NetworkCredential("14ab1", "735435"); // NOTE: The entry MUST be in the phone book before the connection can be dialed. // Begin dialing the connection; this will raise events from the dialer instance. this.handle = this.Dialer.Dial(); } catch (Exception ex) { LogUtil.Write(ex.ToString()); if (ex.Message.Contains("已经拨了这个连接")) { System.Diagnostics.Process.Start(AppDomain.CurrentDomain.BaseDirectory + "系统重启.bat"); } } }
private void Form2_Load(object sender, EventArgs e) { this.Dialer.Timeout = 20000; this.Dialer.Credentials = null; this.Dialer.EapOptions = new DotRas.RasEapOptions(false, false, false); this.Dialer.HangUpPollingInterval = 0; this.Dialer.Options = new DotRas.RasDialOptions(false, false, false, false, false, false, false, false, false, false); this.Dialer.SynchronizingObject = this; //this.Dialer.StateChanged += new System.EventHandler<DotRas.StateChangedEventArgs>(this.Dialer_StateChanged); this.Dialer.DialCompleted += new System.EventHandler <DotRas.DialCompletedEventArgs>(this.Dialer_DialCompleted); string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); //创建VPN this.AllUsersPhoneBook.Open(path); if (!this.AllUsersPhoneBook.Entries.Contains(EntryName)) { RasEntry entry = RasEntry.CreateBroadbandEntry(EntryName, RasDevice.GetDeviceByName("(PPPoE)", RasDeviceType.PPPoE)); this.AllUsersPhoneBook.Entries.Add(entry); } InitAction(); }
public void Dial() { this.Disconnect(); this.CreateVpn(); this.isDialing = true; // This button will be used to dial the connection. this.rasDialer.EntryName = this.VPNItem.EntryName; this.rasDialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); //MS 5M this.rasDialer.Timeout = this.Timeout; try { // Set the credentials the dialer should use. this.rasDialer.Credentials = new NetworkCredential(this.VPNItem.User, this.VPNItem.Password); this.rasDialer.AllowUseStoredCredentials = true; this.rasDialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); //this.rasDialer. // NOTE: The entry MUST be in the phone book before the connection can be dialed. // Begin dialing the connection; this will raise events from the dialer instance. this.rasDialer.DialAsync(); } catch (Exception ex) { LogManager.ErrorWithCallback(string.Format("-> VPN拨号异常:{0}", ex.ToString())); this.vpnManualReset.Set(); this.isDialing = false; } }
/// <summary> /// Occurs when the user clicks the Dial 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 DialButton_Click(object sender, EventArgs e) { this.StatusTextBox.Clear(); // This button will be used to dial the connection. this.Dialer.EntryName = EntryName; this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); try { // Set the credentials the dialer should use. this.Dialer.Credentials = new NetworkCredential("Test", "User"); // NOTE: The entry MUST be in the phone book before the connection can be dialed. // Begin dialing the connection; this will raise events from the dialer instance. this.handle = this.Dialer.DialAsync(); // Enable the disconnect button for use later. this.DisconnectButton.Enabled = true; } catch (Exception ex) { this.StatusTextBox.AppendText(ex.ToString()); } }
/// <summary> /// 测试拨号连接 /// </summary> public void Connect(string RasName) { try { if (OnHandle != null) { OnHandle(string.Format("正在拨号 {0}...", RasName)); } RasDialer dialer = new RasDialer(); dialer.EntryName = RasName; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Timeout = 1000; dialer.Dial(); Thread.Sleep(100); if (OnHandle != null) { OnHandle(string.Format("拨号完成")); } } catch (Exception ex) { LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(ADSLDialerUtil)); throw; } }
public static void CreateVPN() { VPN vpn = new VPN(); DotRas.RasDialer dialer = new DotRas.RasDialer(); DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook(); allUsersPhoneBook.Open(); if (allUsersPhoneBook.Entries.Contains(vpn.VPNConnectionName)) { return; } RasEntry entry = RasEntry.CreateVpnEntry(vpn.VPNConnectionName, vpn.IPToPing, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn)); allUsersPhoneBook.Entries.Add(entry); dialer.EntryName = vpn.VPNConnectionName; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); try { dialer.DialAsync(); } catch (Exception) { return; } }
public bool Connect(VpnConnection selectedConnection) { _dialer.Credentials = new NetworkCredential(_loginMonitor.User.Name, _loginMonitor.SecurePassword); try { string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); _phoneBook.Open(path); _entry = _phoneBook.Entries .FirstOrDefault(x => x.PhoneNumber == selectedConnection.Hostname); if (_entry != null) { _dialer.EntryName = _entry.Name; _dialer.DialAsync(); return(true); } } catch (InvalidOperationException) { Disconnect(); } catch (RasException) { Disconnect(); } return(false); }
// Token: 0x0600008A RID: 138 RVA: 0x00005A3C File Offset: 0x00003C3C public RasPhoneBook ClearPhoneBook(RasPhoneBook myPB, string sVPNPrefix) { try { foreach (RasEntry rasEntry in myPB.Entries) { if (rasEntry.Name.CompareTo(sVPNPrefix) == 0) { myPB.Entries.Remove(rasEntry); break; } } } catch (Exception ex) { string path = myPB.Path; if (File.Exists(path)) { File.Delete(path); myPB = new RasPhoneBook(); myPB.Open(path); } } return(myPB); }
/// <summary> /// 创建或更新一个VPN连接(指定VPN名称,及IP) /// </summary> public void CreateOrUpdateVPN(string updateVPNname, string updateVPNip) { Log.debug(TAG, "CreateOrUpdateVPN"); RasDialer dialer = new RasDialer(); RasPhoneBook allUsersPhoneBook = new RasPhoneBook(); allUsersPhoneBook.Open(); RasEntry entry = null; if (allUsersPhoneBook.Entries.Contains(updateVPNname)) { entry = allUsersPhoneBook.Entries[updateVPNname]; entry.EncryptionType = RasEncryptionType.Optional; entry.PhoneNumber = updateVPNip; IPAddress _ip; IPAddress.TryParse(updateVPNip, out _ip); entry.IPAddress = _ip; entry.Options.UsePreSharedKey = true; entry.UpdateCredentials(RasPreSharedKey.Client, "123456"); entry.Update(); } else { entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn)); entry.EncryptionType = RasEncryptionType.Optional; entry.Options.UsePreSharedKey = true; allUsersPhoneBook.Entries.Add(entry); entry.UpdateCredentials(RasPreSharedKey.Client, "123456"); } }
public void OpenInvalidFileNameExceptionTest() { string phoneBookPath = @"C:\Blah\"; RasPhoneBook target = new RasPhoneBook(); target.Open(phoneBookPath); }
/// <summary> /// Connect /// </summary> /// <param name="connection"></param> private void Connect(string connection) { try { CreatePPPOE(connection); var dialer = new RasDialer { EntryName = connection, PhoneNumber = " ", AllowUseStoredCredentials = true, PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers), Credentials = new NetworkCredential("057111414695", "336875"), Timeout = 1000 }; var myras = dialer.Dial(); while (myras.IsInvalid) { Thread.Sleep(5000); myras = dialer.Dial(); } if (!myras.IsInvalid) { Console.WriteLine($"RasDialer Success! {DateTime.Now}"); } } catch (Exception ex) { throw new Exception($"RasDialer error! {DateTime.Now} connection error is :: {ex.ToString()}"); //Console.WriteLine($"RasDialer error! {DateTime.Now} connection error is :: {ex.ToString()}"); } }
void Btn_DialupClick(object sender, EventArgs e) { try { string username = Username.Text.Replace("\\r", "\r").Replace("\\n", "\n"); string password = Password.Text.ToString(); RasDialer dialer = new RasDialer(); dialer.EntryName = "PPPoEDial"; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new NetworkCredential(username, password); dialer.Timeout = 1000; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { lb_Status.Text = "拨号失败"; } if (!myras.IsInvalid) { lb_Status.Text = "拨号成功! "; RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras); RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); lb_IPAddr.Text = "获得IP: " + ipaddr.IPAddress.ToString(); btn_Dialup.Enabled = false; btn_Hungup.Enabled = true; } } catch (Exception) { lb_Status.Text = "拨号出现异常"; } }
/// <summary> /// 创建或更新一个PPPOE连接(指定PPPOE名称) /// </summary> static void CreateOrUpdatePPPOE(string updatePPPOEname) { RasDialer dialer = new RasDialer(); RasPhoneBook allUsersPhoneBook = new RasPhoneBook(); string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); allUsersPhoneBook.Open(path); // 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址 if (allUsersPhoneBook.Entries.Contains(updatePPPOEname)) { allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " "; // 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用 allUsersPhoneBook.Entries[updatePPPOEname].Update(); } // 创建一个新PPPOE else { string adds = string.Empty; ReadOnlyCollection <RasDevice> readOnlyCollection = RasDevice.GetDevices(); RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First(); RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device); //建立宽带连接Entry entry.PhoneNumber = " "; allUsersPhoneBook.Entries.Add(entry); } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). if (this._rasConnectionWatcher != null) { this._rasConnectionWatcher.Dispose(); this._rasConnectionWatcher = null; } if (this._rasPhoneBook != null) { this._rasPhoneBook.Dispose(); this._rasPhoneBook = null; } if (this._rasDialer != null) { this._rasDialer.Dispose(); this._rasDialer = null; } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public void IpSecConnectionCreate(string ipSecConnectionName, string presharedKey) { if (ipSecConnectionName == null) { throw new ArgumentNullException(nameof(ipSecConnectionName)); } if (presharedKey == null) { throw new ArgumentNullException(nameof(presharedKey)); } if (ipSecConnectionName.Length == 0) { throw new ArgumentException($"nameof(ipSecConnectionName) is empty string"); } if (presharedKey.Length == 0) { throw new ArgumentException($"nameof(presharedKey) is empty string"); } using (var rasPhoneBook = new RasPhoneBook()) { rasPhoneBook.Open(IpSecClient._phoneBookPath); var ipSecRasEntry = RasEntry.CreateVpnEntry( ipSecConnectionName, "0.0.0.0", RasVpnStrategy.L2tpOnly, RasDevice.Create(ipSecConnectionName, RasDeviceType.Vpn) ); //ipSecRasEntry.DnsAddress = System.Net.IPAddress.Parse("0.0.0.0"); //ipSecRasEntry.DnsAddressAlt = System.Net.IPAddress.Parse("0.0.0.0"); ipSecRasEntry.EncryptionType = RasEncryptionType.Require; ipSecRasEntry.EntryType = RasEntryType.Vpn; ipSecRasEntry.Options.RequireDataEncryption = true; ipSecRasEntry.Options.UsePreSharedKey = true; // used only for IPSec - L2TP/IPsec VPN ipSecRasEntry.Options.UseLogOnCredentials = false; ipSecRasEntry.Options.RequireMSChap2 = true; //rasEntry.Options.RemoteDefaultGateway = true; ipSecRasEntry.Options.SecureFileAndPrint = true; ipSecRasEntry.Options.SecureClientForMSNet = true; ipSecRasEntry.Options.ReconnectIfDropped = false; // If the entry with the same name has already been added, Add throws ArgumentException // with message: '<Entry name>' already exists in the phone book.\r\nParameter name: item" rasPhoneBook.Entries.Add(ipSecRasEntry); // RasEntry.UpdateCredentials() has to be executed after RasEntry has been added to the Phone Book. // Otherwise InvalidOperationException is thrown with message: // "The entry is not associated with a phone book." ipSecRasEntry.UpdateCredentials(RasPreSharedKey.Client, presharedKey); //ipSecRasEntry.UpdateCredentials(new System.Net.NetworkCredential("username", "password")); Console.WriteLine($"VPN connection {ipSecConnectionName} created successfully."); } }
public void IpSecConnectionRemove(string ipSecConnectionName) { if (ipSecConnectionName == null) { throw new ArgumentNullException(nameof(ipSecConnectionName)); } if (ipSecConnectionName.Length == 0) { throw new ArgumentException($"nameof(ipSecConnectionName) is empty string"); } using (var rasPhoneBook = new RasPhoneBook()) { rasPhoneBook.Open(IpSecClient._phoneBookPath); var ipSecRasEntry = IpSecClient.RasEntryFindByName(rasPhoneBook, ipSecConnectionName); if (ipSecRasEntry.Remove()) { Console.WriteLine($"VPN connection {ipSecConnectionName} removed successfully."); } else { throw new Exception("RasEntry.Remove() failed."); } } }
/// <summary> /// Method used for diagnostics. /// </summary> /// <param name="phoneBook"></param> private static void PhoneBookEntriesList(RasPhoneBook phoneBook) { foreach (RasEntry entry in phoneBook.Entries) { Console.WriteLine($"\t{entry.Name}"); } }
public bool Dial() { this.HangUp(); //this.CreateADSL(); this.isDialing = true; // This button will be used to dial the connection. this.rasDialer.EntryName = this.ADSLItem.EntryName; this.rasDialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); //MS 5 Mins this.rasDialer.Timeout = this.Timeout; try { // Set the credentials the dialer should use. this.rasDialer.Credentials = new NetworkCredential(this.ADSLItem.User, this.ADSLItem.Password); this.rasDialer.AllowUseStoredCredentials = true; //this.rasDialer. // NOTE: The entry MUST be in the phone book before the connection can be dialed. // Begin dialing the connection; this will raise events from the dialer instance. RasHandle rasHandle = this.rasDialer.Dial(); bool b = !rasHandle.IsInvalid; return(b); } catch (Exception ex) { LogManager.ErrorWithCallback(string.Format("-> ADSL拨号异常:{0}", ex.ToString())); this.isDialing = false; } return(false); }
/// <summary> /// 创建或更新一个PPPOE连接 /// </summary> /// <param name="updatePPPOEName"></param> private void CreateOrUpdatePPPOE(string updatePPPOEName) { var allUsersPhoneBook = new RasPhoneBook(); var path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); allUsersPhoneBook.Open(path); //如果该名称的PPPOE已经存在,则更新这个PPPOE服务器地址 if (allUsersPhoneBook.Entries.Contains(updatePPPOEName)) { allUsersPhoneBook.Entries[updatePPPOEName].PhoneNumber = " "; //不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用 allUsersPhoneBook.Entries[updatePPPOEName].Update(); } //创建一个新的PPPOE else { var address = string.Empty; var readOnlyCollection = RasDevice.GetDevices(); var device = RasDevice.GetDevices().First(o => o.DeviceType == RasDeviceType.PPPoE); //建立宽带连接 var entry = RasEntry.CreateBroadbandEntry(updatePPPOEName, device); entry.PhoneNumber = " "; allUsersPhoneBook.Entries.Add(entry); } }
/// <summary> /// 创建一个PPPOE连接 /// </summary> /// <param name="updatePPPOEName"></param> private void CreatePPPOE(string updatePPPOEName) { var conns = RasConnection.GetActiveConnections(); if (conns != null) { foreach (var conn in conns) { conn.HangUp(); } } var allUsersPhoneBook = new RasPhoneBook(); var path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); allUsersPhoneBook.Open(path); //创建一个新的PPPOE var address = string.Empty; var readOnlyCollection = RasDevice.GetDevices(); var device = RasDevice.GetDevices().First(o => o.DeviceType == RasDeviceType.PPPoE); //建立宽带连接 var entry = RasEntry.CreateBroadbandEntry(updatePPPOEName, device); entry.PhoneNumber = " "; if (!allUsersPhoneBook.Entries.Contains(updatePPPOEName)) { allUsersPhoneBook.Entries.Add(entry); } }
private void dial_Click(object sender, RoutedEventArgs e) { try { string username = tb_username.Text.Replace("\\r", "\r").Replace("\\n", "\n"); string password = pb_password.Password.ToString(); RasDialer dialer = new RasDialer(); dialer.EntryName = "PPPoEDialer"; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new System.Net.NetworkCredential(username, password); dialer.Timeout = 500; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { lb_status.Content = "拨号失败"; } if (!myras.IsInvalid) { lb_status.Content = "拨号成功! "; RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras); RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); lb_message.Content = "获得IP: " + ipaddr.IPAddress.ToString(); dial.IsEnabled = false; hangup.IsEnabled = true; } } catch (Exception) { lb_status.Content = "拨号出现异常"; } }
public void CreateCustomPhoneBookTest() { DirectoryInfo tempFolder = TestUtilities.GetTempPath(true); string path = null; try { path = Path.Combine(tempFolder.FullName, string.Format("{0}.pbk", TestUtilities.StripNonAlphaNumericChars(Guid.NewGuid().ToString()))); RasPhoneBook target = new RasPhoneBook(); target.Open(path); RasEntry entry = RasEntry.CreateVpnEntry("Test Entry", IPAddress.Loopback.ToString(), RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false)); if (entry != null) { target.Entries.Add(entry); } Assert.IsTrue(File.Exists(path), "The phone book file was not found at the expected location. '{0}'", path); } finally { if (Directory.Exists(tempFolder.FullName)) { // The folder was created successfully, delete it before the test completes. Directory.Delete(tempFolder.FullName, true); } } }
/// <summary> /// 宽带连接,成功返回true,失败返回 false /// </summary> /// <param name="PPPOEname">宽带连接名称</param> /// <param name="username">宽带账号</param> /// <param name="password">宽带密码</param> /// <returns></returns> public static bool Connect(string PPPOEname, string username, string password, ref string msg, int delay = 10000) { try { CreateOrUpdatePPPOE(PPPOEname); using (RasDialer dialer = new RasDialer()) { dialer.EntryName = PPPOEname; dialer.AllowUseStoredCredentials = true; dialer.Timeout = 1000; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Credentials = new NetworkCredential(username, password); dialer.Dial(); return(true); } } catch (RasException re) { msg = re.ErrorCode + " " + re.Message; return(false); } finally { Thread.Sleep(delay); } }
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); }
public override void Initialize() { base.Initialize(); this._phoneBookPath = System.IO.Path.GetTempFileName(); this._entryName = Guid.NewGuid().ToString(); this._phoneBook = new RasPhoneBook(); this._phoneBook.Open(this._phoneBookPath); this._entry = new RasEntry(this._entryName); this._entry.Device = RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn); this._entry.EncryptionType = RasEncryptionType.Require; this._entry.EntryType = RasEntryType.Vpn; this._entry.FramingProtocol = RasFramingProtocol.Ppp; this._entry.NetworkProtocols.IP = true; this._entry.NetworkProtocols.IPv6 = true; this._entry.PhoneNumber = IPAddress.Loopback.ToString(); this._entry.VpnStrategy = RasVpnStrategy.Default; this._phoneBook.Entries.Add(this._entry); }
/// <summary> /// Indicates whether the entry name is valid for the phone book specified. /// </summary> /// <param name="phoneBook">Required. An <see cref="DotRas.RasPhoneBook"/> to validate the name against.</param> /// <param name="entryName">Required. The name of an entry to check.</param> /// <param name="acceptableResults">Any additional results that are considered acceptable results from the call.</param> /// <returns><b>true</b> if the entry name is valid, otherwise <b>false</b>.</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> public bool IsValidEntryName(RasPhoneBook phoneBook, string entryName, params int[] acceptableResults) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } if (string.IsNullOrEmpty(entryName)) { ThrowHelper.ThrowArgumentException("entryName", Resources.Argument_StringCannotBeNullOrEmpty); } bool retval = false; try { int ret = SafeNativeMethods.Instance.ValidateEntryName(phoneBook.Path, entryName); if (ret == NativeMethods.SUCCESS) { retval = true; } else if (acceptableResults != null && acceptableResults.Length > 0) { for (int index = 0; index < acceptableResults.Length; index++) { if (acceptableResults[index] == ret) { retval = true; break; } } } } catch (EntryPointNotFoundException) { ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform); } return retval; }
/// <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 OpenAllUsersProfileFileTest() { RasPhoneBookType expected = RasPhoneBookType.AllUsers; string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); RasPhoneBook target = new RasPhoneBook(); target.Open(phoneBookPath); RasPhoneBookType actual = target.PhoneBookType; Assert.AreEqual<RasPhoneBookType>(expected, actual); }
public void OpenArgumentExceptionNullStringTest() { RasPhoneBook target = new RasPhoneBook(); target.Open(null); }
/// <summary> /// Retrieves a list of entry names within a phone book. /// </summary> /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> whose entry names to retrieve.</param> /// <returns>An array of <see cref="NativeMethods.RASENTRYNAME"/> structures, or a null reference if the phone-book was not found.</returns> /// <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 NativeMethods.RASENTRYNAME[] GetEntryNames(RasPhoneBook phoneBook) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } NativeMethods.RASENTRYNAME[] retval = null; int size = Marshal.SizeOf(typeof(NativeMethods.RASENTRYNAME)); IntPtr lpCb = new IntPtr(size); IntPtr lpcEntries = IntPtr.Zero; bool retry = false; do { NativeMethods.RASENTRYNAME entry = new NativeMethods.RASENTRYNAME(); entry.size = size; IntPtr pEntries = IntPtr.Zero; try { pEntries = Marshal.AllocHGlobal(lpCb); Marshal.StructureToPtr(entry, pEntries, true); try { int ret = UnsafeNativeMethods.Instance.EnumEntries(IntPtr.Zero, phoneBook.Path, pEntries, ref lpCb, ref lpcEntries); if (ret == NativeMethods.ERROR_BUFFER_TOO_SMALL) { retry = true; } else if (ret == NativeMethods.SUCCESS) { retry = false; int entries = lpcEntries.ToInt32(); if (entries > 0) { retval = Utilities.CreateArrayOfType<NativeMethods.RASENTRYNAME>(pEntries, size, entries); } } else { ThrowHelper.ThrowRasException(ret); } } catch (EntryPointNotFoundException) { ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform); } } finally { if (pEntries != IntPtr.Zero) { Marshal.FreeHGlobal(pEntries); } } } while (retry); return retval; }
public void OpenArgumentExceptionEmptyStringTest() { RasPhoneBook target = new RasPhoneBook(); target.Open(string.Empty); }
/// <summary> /// Indicates whether the entry name is valid for the phone book specified. /// </summary> /// <param name="phoneBook">Required. An <see cref="DotRas.RasPhoneBook"/> to validate the name against.</param> /// <param name="entryName">Required. The name of an entry to check.</param> /// <returns><b>true</b> if the entry name is valid, otherwise <b>false</b>.</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> public bool IsValidEntryName(RasPhoneBook phoneBook, string entryName) { return RasHelper.Instance.IsValidEntryName(phoneBook, entryName, null); }
/// <summary> /// Deletes a subentry from the specified phone book entry. /// </summary> /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param> /// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> containing the subentry to be deleted.</param> /// <param name="subEntryId">The one-based index of the subentry to delete.</param> /// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="phoneBook"/> or <paramref name="entry"/> 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 bool DeleteSubEntry(RasPhoneBook phoneBook, RasEntry entry, int subEntryId) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } if (entry == null) { ThrowHelper.ThrowArgumentNullException("entry"); } if (subEntryId <= 0) { ThrowHelper.ThrowArgumentException("subEntryId", Resources.Argument_ValueCannotBeLessThanOrEqualToZero); } bool retval = false; int ret = UnsafeNativeMethods.Instance.DeleteSubEntry(phoneBook.Path, entry.Name, subEntryId); if (ret == NativeMethods.SUCCESS) { retval = true; } else { ThrowHelper.ThrowRasException(ret); } return retval; }
/// <summary> /// Retrieves the subentry properties for an entry within a phone book. /// </summary> /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param> /// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> containing the subentry.</param> /// <param name="subEntryId">The zero-based index of the subentry to retrieve.</param> /// <returns>A new <see cref="DotRas.RasSubEntry"/> object.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="phoneBook"/> or <paramref name="entry"/> 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 RasSubEntry GetSubEntryProperties(RasPhoneBook phoneBook, RasEntry entry, int subEntryId) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } if (entry == null) { ThrowHelper.ThrowArgumentNullException("entry"); } RasSubEntry retval = null; int size = Marshal.SizeOf(typeof(NativeMethods.RASSUBENTRY)); bool retry = false; IntPtr lpCb = new IntPtr(size); do { NativeMethods.RASSUBENTRY subentry = new NativeMethods.RASSUBENTRY(); subentry.size = size; IntPtr lpRasSubEntry = IntPtr.Zero; try { lpRasSubEntry = Marshal.AllocHGlobal(lpCb); Marshal.StructureToPtr(subentry, lpRasSubEntry, true); try { int ret = UnsafeNativeMethods.Instance.GetSubEntryProperties(phoneBook.Path, entry.Name, subEntryId + 2, lpRasSubEntry, ref lpCb, IntPtr.Zero, IntPtr.Zero); if (ret == NativeMethods.SUCCESS) { subentry = Utilities.PtrToStructure<NativeMethods.RASSUBENTRY>(lpRasSubEntry); retval = new RasSubEntry(); retval.Device = RasDevice.Create(subentry.deviceName, subentry.deviceType); retval.PhoneNumber = subentry.phoneNumber; if (subentry.alternateOffset != 0) { retval.AlternatePhoneNumbers = Utilities.CreateStringCollectionByLength(lpRasSubEntry, subentry.alternateOffset, lpCb.ToInt32() - subentry.alternateOffset); } 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 (lpRasSubEntry != IntPtr.Zero) { Marshal.FreeHGlobal(lpRasSubEntry); } } } while (retry); return retval; }
/// <summary> /// Renames an existing entry in a phone book. /// </summary> /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry to be renamed.</param> /// <param name="entryName">Required. The name of an entry to rename.</param> /// <param name="newEntryName">Required. The new name of the entry.</param> /// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns> /// <exception cref="System.ArgumentException"><paramref name="entryName"/> or <paramref name="newEntryName"/> 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 bool RenameEntry(RasPhoneBook phoneBook, string entryName, string newEntryName) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } if (string.IsNullOrEmpty(entryName)) { ThrowHelper.ThrowArgumentException("entryName", Resources.Argument_StringCannotBeNullOrEmpty); } if (string.IsNullOrEmpty(newEntryName)) { ThrowHelper.ThrowArgumentException("newEntryName", Resources.Argument_StringCannotBeNullOrEmpty); } bool retval = false; try { int ret = UnsafeNativeMethods.Instance.RenameEntry(phoneBook.Path, entryName, newEntryName); if (ret == NativeMethods.SUCCESS) { retval = true; } else if (ret == NativeMethods.ERROR_CANNOT_FIND_PHONEBOOK_ENTRY) { ThrowHelper.ThrowArgumentException("entryName", Resources.Argument_InvalidEntryName, "entryName", entryName); } else if (ret == NativeMethods.ERROR_ACCESS_DENIED) { ThrowHelper.ThrowUnauthorizedAccessException(Resources.Exception_AccessDeniedBySecurity); } else if (ret == NativeMethods.ERROR_ALREADY_EXISTS) { ThrowHelper.ThrowArgumentException("newEntryName", Resources.Argument_EntryAlreadyExists); } else { ThrowHelper.ThrowRasException(ret); } } catch (EntryPointNotFoundException) { ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform); } return retval; }
public void IPv6RemoteDefaultGatewayAfterReloadTest() { bool expected = true; this._entry.Options.IPv6RemoteDefaultGateway = expected; this._entry.Update(); this._entry = null; this._phoneBook.Dispose(); this._phoneBook = null; this._phoneBook = new RasPhoneBook(); this._phoneBook.Open(this._phoneBookPath); this._entry = this._phoneBook.Entries[this._entryName]; bool actual = this._entry.Options.IPv6RemoteDefaultGateway; Assert.AreEqual(expected, actual); }
public void OpenPhoneBookInCustomFolderThatDoesNotAlreadyExistTest() { DirectoryInfo tempFolder = TestUtilities.GetTempPath(false); string path = null; try { path = Path.Combine(tempFolder.FullName, string.Format("{0}.pbk", TestUtilities.StripNonAlphaNumericChars(Guid.NewGuid().ToString()))); RasPhoneBook target = new RasPhoneBook(); target.EnableFileWatcher = true; target.Open(path); } finally { if (Directory.Exists(tempFolder.FullName)) { // The folder was created successfully, delete it before the test completes. Directory.Delete(tempFolder.FullName, true); } } }
/// <summary> /// Creates a new VPN entry in the phonebook. /// </summary> /// <param name="phonebook">The phonebook to receive the entry.</param> /// <param name="entryName">The name of the entry.</param> /// <returns>The entry id.</returns> public static Guid CreateValidVpnEntry(RasPhoneBook phonebook, string entryName) { return CreateVpnEntry(phonebook, entryName, "testvpn"); }
/// <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; }
/// <summary> /// Creates a new invalid VPN entry in the phonebook. /// </summary> /// <param name="phonebook">The phonebook to receive the entry.</param> /// <param name="entryName">The name of the entry.</param> /// <returns>The entry id.</returns> public static Guid CreateInvalidVpnEntry(RasPhoneBook phonebook, string entryName) { return CreateVpnEntry(phonebook, entryName, "yahoo.com"); }
/// <summary> /// Sets the subentry properties for an existing subentry, or creates a new subentry. /// </summary> /// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> that will contain the entry.</param> /// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> whose subentry to set.</param> /// <param name="subEntryId">The zero-based index of the subentry to set.</param> /// <param name="value">An <see cref="DotRas.RasSubEntry"/> 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="entry"/> or <paramref name="value"/> 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 bool SetSubEntryProperties(RasPhoneBook phoneBook, RasEntry entry, int subEntryId, RasSubEntry value) { if (phoneBook == null) { ThrowHelper.ThrowArgumentNullException("phoneBook"); } if (value == null) { ThrowHelper.ThrowArgumentNullException("value"); } if (entry == null) { ThrowHelper.ThrowArgumentNullException("entry"); } bool retval = false; int size = Marshal.SizeOf(typeof(NativeMethods.RASSUBENTRY)); int lpCb = size; IntPtr lpRasSubEntry = IntPtr.Zero; try { NativeMethods.RASSUBENTRY subentry = new NativeMethods.RASSUBENTRY(); subentry.size = size; subentry.phoneNumber = value.PhoneNumber; if (value.Device != null) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(RasDeviceType)); if (converter == null) { ThrowHelper.ThrowInvalidOperationException(Resources.Exception_TypeConverterNotFound, "RasDeviceType"); } subentry.deviceName = value.Device.Name; subentry.deviceType = converter.ConvertToString(value.Device.DeviceType); } int alternatesLength = 0; string alternatesList = Utilities.BuildStringList(value.AlternatePhoneNumbers, '\x00', out alternatesLength); if (alternatesLength > 0) { lpCb = size + alternatesLength; subentry.alternateOffset = size; } lpRasSubEntry = Marshal.AllocHGlobal(lpCb); Marshal.StructureToPtr(subentry, lpRasSubEntry, true); if (alternatesLength > 0) { Utilities.CopyString(lpRasSubEntry, size, alternatesList, alternatesLength); } try { int ret = UnsafeNativeMethods.Instance.SetSubEntryProperties(phoneBook.Path, entry.Name, subEntryId + 2, lpRasSubEntry, lpCb, IntPtr.Zero, 0); if (ret == NativeMethods.SUCCESS) { retval = true; } else { ThrowHelper.ThrowRasException(ret); } } catch (EntryPointNotFoundException) { ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform); } } finally { if (lpRasSubEntry != IntPtr.Zero) { Marshal.FreeHGlobal(lpRasSubEntry); } } return retval; }
/// <summary> /// Creates a VPN entry for the phonebook. /// </summary> /// <param name="phonebook">The phonebook to receive the entry.</param> /// <param name="entryName">The name of the entry.</param> /// <param name="serverAddress">The server address to connect to.</param> /// <returns>The entry id.</returns> private static Guid CreateVpnEntry(RasPhoneBook phonebook, string entryName, string serverAddress) { Guid entryId = Guid.Empty; RasEntry entry = RasEntry.CreateVpnEntry(entryName, serverAddress, RasVpnStrategy.PptpOnly, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn)); if (entry != null) { phonebook.Entries.Add(entry); entryId = entry.Id; } return entryId; }