Ejemplo n.º 1
0
        // Add a new VPN connection action.
        private void btnConnectVPN_Click(object sender, EventArgs e)
        {
            var sis = new SingleItemSelectorForm();

            sis.SetText("Connect to VPN", "VPN Name:");

            // Populate the combo box drop-down with the list of known VPNs.
            var rpbk = new RasPhoneBook();

            rpbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
            foreach (var rent in rpbk.Entries)
            {
                sis.comboBox1.Items.Add(rent.Name);
            }
            rpbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
            foreach (var rent in rpbk.Entries)
            {
                sis.comboBox1.Items.Add(rent.Name);
            }

            if (sis.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var pcv = new PAConnectVPN();
                pcv.VPN_Name = sis.comboBox1.Text;
                listBox1.Items.Add(pcv);
            }
        }
        /// <summary>
        /// Gets the names of all the available RAS (VPN or dial up) connections.
        /// </summary>
        /// <returns></returns>
        public List <string> GetRasConnectionNames()
        {
            _rasPhoneBook.Open();
            List <string> result = new List <string>();

            for (int i = 0; i < _rasPhoneBook.Entries.Count; i++)
            {
                RasEntry entry = _rasPhoneBook.Entries[i];
                result.Add(entry.Name);
            }
            return(result);
        }
Ejemplo n.º 3
0
        public static void Init(string entryname, string username, string password)
        {
            bool IsFoundEntry = false;

            //判断是否从电话簿中调出已有拨号连接
            if (username == null || password == null || username == "" || password == "")
            {
                using (RasPhoneBook phoneBook = new RasPhoneBook())
                {
                    phoneBook.Open();
                    foreach (RasEntry entry in phoneBook.Entries)
                    {
                        if (entry.Name == entryname)
                        {
                            IsFoundEntry = true;
                        }
                    }
                    //没有找到同名的就用第一个
                    if (!IsFoundEntry)
                    {
                        entryname = phoneBook.Entries[0].Name;
                    }
                }
            }
            else
            {
                //本地生成
                ms_nc = new NetworkCredential(username, password);
            }
            ms_entryname   = entryname;
            ms_IsInitialed = true;
            log.Debug("ADSLManager: Initial " + entryname);
        }
Ejemplo n.º 4
0
        private Encoding defEncoding           = Encoding.GetEncoding(1252); // ANSI

        private void CreateConnect()
        {
            RasPhoneBook book = new RasPhoneBook();

            try
            {
                book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                if (book.Entries.Contains(ConnectionName))
                {
                    book.Entries[ConnectionName].PhoneNumber = " ";
                    book.Entries[ConnectionName].Update();
                }
                else
                {
                    RasDevice device = RasDevice.GetDevices().
                                       Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
                    RasEntry entry = RasEntry.CreateBroadbandEntry(ConnectionName, device);
                    entry.PhoneNumber = " ";
                    book.Entries.Add(entry);
                }
            }
            catch (Exception ex)
            {
                Logger.Log($"创建PPPoE连接失败({ex.Message})");
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 初始化PPPoE拨号器
        /// </summary>
        /// <param name="connectName">连接名称</param>
        public static void Init(string connectName)
        {
            try
            {
                RasDialer    dialer    = new RasDialer();
                RasPhoneBook phoneBook = new RasPhoneBook();
                string       path      = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
                phoneBook.Open(path);

                if (phoneBook.Entries.Contains(connectName))
                {
                    phoneBook.Entries[connectName].PhoneNumber = " ";
                    phoneBook.Entries[connectName].Update();
                }
                else
                {
                    string adds = string.Empty;
                    System.Collections.ObjectModel.ReadOnlyCollection <RasDevice> readOnlyCollection = RasDevice.GetDevices();
                    RasDevice device = RasDevice.GetDevices().First(o => o.DeviceType == RasDeviceType.PPPoE);
                    RasEntry  entry  = RasEntry.CreateBroadbandEntry(connectName, device);
                    entry.PhoneNumber = " ";
                    phoneBook.Entries.Add(entry);
                }
            }
            catch (Exception e)
            {
                Utils.Log4Net.WriteLog(e.Message, e);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称,及IP)
        /// </summary>
        public void CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            RasDialer    dialer            = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();

            allUsersPhoneBook.Open();
            // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
            if (allUsersPhoneBook.Entries.Contains(updateVPNname))
            {
                allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                // 不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
                allUsersPhoneBook.Entries[updateVPNname].Update();
            }
            // 创建一个新VPN
            else
            {
                //RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
                //allUsersPhoneBook.Entries.Add(entry);
                RasEntry entryL2TP = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));

                allUsersPhoneBook.Entries.Add(entryL2TP);
                dialer.EntryName     = updateVPNname;
                dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            }
        }
Ejemplo n.º 7
0
        /// <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);
            }
        }
Ejemplo n.º 8
0
        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);
            }
        }
Ejemplo n.º 9
0
        /// <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);
            }
        }
Ejemplo n.º 10
0
 public void Disconnect()
 {
     if (_Dialer.IsBusy)
     {
         // The connection attempt has not been completed, cancel the attempt.
         this._Dialer.DialAsyncCancel();
     }
     else
     {
         // The connection attempt has completed, attempt to find the connection in the active connections.
         RasConnection connection = RasConnection.GetActiveConnectionByHandle(_handle);
         if (connection != null)
         {
             // The connection has been found, disconnect it.
             connection.HangUp();
             ConnectionStatusChanged(eConnectionState.Disconnected);
         }
         RasPhoneBook AllUsersPhoneBook = new RasPhoneBook();
         AllUsersPhoneBook.Open();
         if ((AllUsersPhoneBook.Entries.Contains(_connectionentry)))
         {
             // AllUsersPhoneBook.Entries[_connectionentry].Remove();
         }
     }
 }
Ejemplo n.º 11
0
        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.");
                }
            }
        }
Ejemplo n.º 12
0
        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.");
            }
        }
Ejemplo n.º 13
0
        /// <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);
            }
        }
Ejemplo n.º 14
0
        public void Disconnect()
        {
            if (dialer.IsBusy)
            {
                dialer.DialAsyncCancel();
            }
            else
            {
                if (handle != null)
                {
                    RasConnection Connection = RasConnection.GetActiveConnectionByHandle(handle);
                    if (Connection != null)
                    {
                        Connection.HangUp();
                    }
                }
            }

            using (RasPhoneBook PhoneBook = new RasPhoneBook())
            {
                PhoneBook.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));

                if (PhoneBook.Entries.Contains(adapterName))
                {
                    PhoneBook.Entries.Remove(adapterName);
                }
            }
        }
Ejemplo n.º 15
0
        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);
                }
            }
        }
 // 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);
 }
Ejemplo n.º 17
0
 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);
     }
 }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        /// <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");
            }
        }
Ejemplo n.º 20
0
        /// <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);
            }
        }
Ejemplo n.º 21
0
        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连接失败";
            }
        }
Ejemplo n.º 22
0
        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);
                }
            }
        }
Ejemplo n.º 23
0
        public void OpenPhoneBookTest()
        {
            RasPhoneBook target = RasPhoneBook.Open(@".\TestData\Test.pbk");

            var exists = target.Entries.Where(o => o.Name == "Test").Any();

            Assert.IsTrue(exists);
        }
Ejemplo n.º 24
0
        public PhoneBookManager(String phoneBookPath)
        {
            allUsersPhoneBook = new RasPhoneBook();
            //String defaultPhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            //allUsersPhoneBook.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));

            allUsersPhoneBook.Open(phoneBookPath);
        }
Ejemplo n.º 25
0
        public void OpenInvalidFileNameExceptionTest()
        {
            var phoneBookPath = @"C:\Blah\";

            var target = new RasPhoneBook();

            target.Open(phoneBookPath);
        }
Ejemplo n.º 26
0
        public void Setup()
        {
            var p = new RasPhoneBook();

            p.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
            EntryName = p.Entries[0].Name;

            RasConnection.GetActiveConnections().Each(c => c.HangUp());
        }
Ejemplo n.º 27
0
 static VPNConnectHelper()
 {
     pb.Open();
     dialer.EntryName = VPNNAME;
     //dialer.Timeout = 20000;
     dialer.PhoneBookPath  = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
     dialer.StateChanged  += new EventHandler <StateChangedEventArgs>(dialer_StateChanged);
     dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(dialer_DialCompleted);
 }
Ejemplo n.º 28
0
        public void Open()
        {
            if (String.IsNullOrEmpty(connectionName))
            {
                return;
            }

            lock (sync) {
                //если две нитки используют один RasHelper и одна уже получила ссылку
                if (connectionRef != Disposable.Empty)
                {
                    return;
                }
                //если соединение есть и его открыли мы тогда берем ссылку
                if (connection != null && !connection.IsDisposed)
                {
                    connectionRef = connection.GetDisposable();
                    return;
                }

                //если соединение открыли не мы, тогда выходим
                if (RasConnection.GetActiveConnections().Any(c => c.EntryName == connectionName))
                {
                    return;
                }

                string phonebookPath = null;
                foreach (var path in GetPhoneBooks())
                {
                    using (var book = new RasPhoneBook()) {
                        book.Open(path);
                        if (book.Entries.Any(e => e.Name.Match(connectionName)))
                        {
                            phonebookPath = book.Path;
                        }
                    }
                }

                if (phonebookPath == null)
                {
                    log.Warn($"Не удалось найти соединение {connectionName}, удаленное соединение устанавливаться не будет");
                    return;
                }

                using (var dialer = new RasDialer()) {
                    dialer.PhoneBookPath = phonebookPath;
                    dialer.EntryName     = connectionName;
                    var handle = dialer.Dial();

                    var rasConnection = RasConnection.GetActiveConnections().FirstOrDefault(c => c.Handle == handle);
                    connection    = new RefCountDisposable(Disposable.Create(() => rasConnection?.HangUp()));
                    connectionRef = connection.GetDisposable();
                    connection.Dispose();
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 删除指定名称的Vpn
        /// 如果Vpn正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
        /// </summary>
        /// <param name="delVpnName"></param>
        public void TryDeleteVpn(string delVpnName)
        {
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();

            allUsersPhoneBook.Open(allUsersPhoneBook.Path);
            if (allUsersPhoneBook.Entries.Contains(delVpnName))
            {
                allUsersPhoneBook.Entries.Remove(delVpnName);
            }
        }
 /// <summary>
 /// 使用Google DNS
 /// </summary>
 /// <exception cref="InvalidOperationException"></exception>
 public bool UseGoogleDns()
 {
     using (var pbk = new RasPhoneBook())
     {
         pbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
         pbk.Entries[Entry].DnsAddress    = GoogleFirstDns;
         pbk.Entries[Entry].DnsAddressAlt = GoogleSecondDns;
         return(pbk.Entries[Entry].Update());
     }
 }
 /// <summary>
 /// 使用/恢复 默认的DNS
 /// </summary>
 public bool UseDefualtDns()
 {
     using (var pbk = new RasPhoneBook())
     {
         pbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
         pbk.Entries[Entry].DnsAddress    = IPAddress.Any;
         pbk.Entries[Entry].DnsAddressAlt = IPAddress.Any;
         return(pbk.Entries[Entry].Update());
     }
 }
Ejemplo n.º 32
0
        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);
        }
Ejemplo n.º 33
0
        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);
                }
            }
        }
Ejemplo n.º 34
0
 public void OpenArgumentExceptionEmptyStringTest()
 {
     RasPhoneBook target = new RasPhoneBook();
     target.Open(string.Empty);
 }
Ejemplo n.º 35
0
        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);
        }
Ejemplo n.º 36
0
        public void OpenInvalidFileNameExceptionTest()
        {
            string phoneBookPath = @"C:\Blah\";

            RasPhoneBook target = new RasPhoneBook();
            target.Open(phoneBookPath);
        }
Ejemplo n.º 37
0
 public void OpenArgumentExceptionNullStringTest()
 {
     RasPhoneBook target = new RasPhoneBook();
     target.Open(null);
 }