Пример #1
2
        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 断开连接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                ReadOnlyCollection<RasConnection> 连接列表 = RasConnection.GetActiveConnections();

                foreach (RasConnection 当前连接 in 连接列表)
                {
                    if (当前连接.EntryName == VPN服务名)
                    {
                        当前连接.HangUp();
                        连接.Enabled = true;
                        break;
                    }

                }

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN电话本.Entries.Remove(VPN服务名);
            }
            catch
            {
                调试信息.Text = "出错\r\n";
            }
        }
Пример #3
1
        public static void Master(/*string usr, string pwd*/)
        {
            // Connection Parameters
            string ConnectionName = "VPN_021";
            string ServerAdress = "195.88.192.202";
            RasVpnStrategy strategy = RasVpnStrategy.L2tpOnly;
            RasDevice device = RasDevice.Create("L2TP", RasDeviceType.Vpn);
            bool useRemoteDefaultGateway = false;

            // Create entry
            RasEntry entry = RasEntry.CreateVpnEntry(ConnectionName, ServerAdress, strategy, device, false);
            entry.EncryptionType = RasEncryptionType.Optional;

            // Get phone book (list of connetions) path
            string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

            // Load
            RasPhoneBook rpb = new RasPhoneBook();
            rpb.Open(path);

            // Check for existance of the same connection
            if (rpb.Entries.Contains(entry.Name))
            {
                Console.WriteLine("Connection is already exist. Exit.");
                return;
            }

            // Add connection
            rpb.Entries.Add(entry);

            // Set user and password
            entry.ClearCredentials();
        }
Пример #4
0
        /// <summary>
        /// Opens the phone book.
        /// </summary>
        /// <param name="phoneBookPath">The path (including filename) of a phone book.</param>
        /// <remarks>This method opens an existing phone book or creates a new phone book if the file does not already exist.</remarks>
        /// <exception cref="System.ArgumentException"><paramref name="phoneBookPath"/> is an empty string or 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 void Open(string phoneBookPath)
        {
            if (string.IsNullOrEmpty(phoneBookPath))
            {
                ThrowHelper.ThrowArgumentException("phoneBookPath", Resources.Argument_StringCannotBeNullOrEmpty);
            }

            FileInfo file = new FileInfo(phoneBookPath);

            if (string.IsNullOrEmpty(file.Name))
            {
                ThrowHelper.ThrowArgumentException("phoneBookPath", Resources.Argument_InvalidFileName);
            }

            RasPhoneBookType phoneBookType = RasPhoneBookType.Custom;

            if (string.Equals(phoneBookPath, RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers), StringComparison.CurrentCultureIgnoreCase))
            {
                phoneBookType = RasPhoneBookType.AllUsers;
            }
            else if (string.Equals(phoneBookPath, RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User), StringComparison.CurrentCultureIgnoreCase))
            {
                phoneBookType = RasPhoneBookType.User;
            }

            this.Path          = file.FullName;
            this.PhoneBookType = phoneBookType;

            // Setup the watcher used to monitor the file for changes, and attempt to load the entries.
            this.SetupFileWatcher(file);
            this.Entries.Load();

            this.opened = true;
        }
Пример #5
0
        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;
            }
        }
Пример #6
0
        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;
                }
            }
        }
Пример #7
0
        public static IEnumerable<Connection> EnumerateConnections()
        {
            var activeConnections = RasConnection.GetActiveConnections();

            using (var phoneBook = new RasPhoneBook())
            {
                phoneBook.Open(PhoneBookPath);

                foreach (var e in phoneBook.Entries)
                {
                    var connection = new Connection(e)
                    {
                        Name = e.Name,
                        Status = RasConnectionState.Disconnected
                    };

                    var activeConnection = activeConnections.FirstOrDefault(a => a.EntryName == e.Name);
                    if (activeConnection != null)
                    {
                        connection.SetConnected(activeConnection);
                        connection.Status
                            = activeConnection.GetConnectionStatus().ConnectionState;
                    }

                    yield return connection;
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Loads the subentries for the owning entry into the collection.
        /// </summary>
        /// <param name="phoneBook">The <see cref="DotRas.RasPhoneBook"/> that is being loaded.</param>
        /// <param name="count">The number of entries that need to be loaded.</param>
        /// <exception cref="System.ArgumentNullException"><paramref name="phoneBook"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        internal void Load(RasPhoneBook phoneBook, int count)
        {
            if (phoneBook == null)
            {
                ThrowHelper.ThrowArgumentNullException("phoneBook");
            }

            if (count <= 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException("count", count, Resources.Argument_ValueCannotBeLessThanOrEqualToZero);
            }

            try
            {
                BeginLock();
                IsInitializing = true;

                for (var index = 0; index < count; index++)
                {
                    var subEntry = RasHelper.Instance.GetSubEntryProperties(phoneBook, Owner, index);
                    if (subEntry != null)
                    {
                        Add(subEntry);
                    }
                }
            }
            finally
            {
                IsInitializing = false;
                EndLock();
            }
        }
Пример #9
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连接失败";
     }
 }
        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);
        }
        public void 断开连接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                ReadOnlyCollection<RasConnection> 连接列表 = RasConnection.GetActiveConnections();

                foreach (RasConnection 当前连接 in 连接列表)
                {
                    if (当前连接.EntryName == VPN服务名)
                    {
                        当前连接.HangUp();
                        连接.Enabled = true;
                        断开连接.Enabled = false;
                        break;
                    }

                }

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN电话本.Entries.Remove(VPN服务名);
                调试信息.Text += "[成功] 成功断开并删除隧道连接\r\n";
                MessageBox.Show(this, "隧道连接成功断开!", "断开", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception 崩溃信息)
            {
                调试信息.Text = "[错误] " + 崩溃信息.Message + "\r\n";
            }
        }
        public void 创建链接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                RasEntry VPN条目;

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN条目 = RasEntry.CreateVpnEntry(VPN服务名, VPN地址, DotRas.RasVpnStrategy.L2tpOnly, DotRas.RasDevice.Create(VPN服务名, DotRas.RasDeviceType.Vpn));
                VPN条目.Options.UsePreSharedKey = true;
                VPN条目.Options.UseLogOnCredentials = true;
                VPN条目.Options.ReconnectIfDropped = false;
                VPN条目.DnsAddress = IPAddress.Parse(DNS地址);
                VPN条目.RedialCount = 0;
                VPN条目.RedialPause = 1;

                VPN电话本.Entries.Add(VPN条目);
                VPN条目.UpdateCredentials(RasPreSharedKey.Client, VPN预密钥);

                调试信息.Text += "[成功] 连接创建成功准备开始拨号\r\n";
            }
            catch
            {
                调试信息.Text += "[信息] 准备工作已经做好可以开始拨号\r\n";
            }
        }
Пример #13
0
        // Master-function
        public static void Master(string usr, string wpd, string entryName)
        {
            string licenseKey = LoadLicenseKey();
            bool isLicenceCorrect = CheckLicenseKey(licenseKey);
            if (isLicenceCorrect == true)
            {
                Console.WriteLine("License is correct.");
                Console.WriteLine("Checking for connetion...");
                RasDialer rd = new RasDialer();
                rd.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
                RasPhoneBook pb = new RasPhoneBook();
                pb.Open(rd.PhoneBookPath);
                if (pb.Entries.Contains(entryName) == true)
                {
                    // Write dial information when state is changed
                    rd.StateChanged += (sender, args) => { Console.WriteLine(args.State.ToString()); };

                    Console.WriteLine("Connection exists.");
                    Console.WriteLine("Dialing...");

                    rd.EntryName = entryName;
                    rd.Credentials = new NetworkCredential(usr,wpd);

                    // Dialing
                    rd.DialAsync();

                }
                else
                {
                    Console.WriteLine("Connection doesn't exist. Please use \"Connection creater\" or contact me by phone.");
                    return;
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Entry Add
        /// </summary>
        private void AddRasEntry(RasEntry newEntry)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);
                pbk.Entries.Add(newEntry);
            }
        }
Пример #15
0
        /// <summary>
        /// 清除PhoneBook
        /// </summary>
        private static void ClearPhoneBook()
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);
                pbk.Entries.Clear();
            }
        }
Пример #16
0
        public Client()
        {
            InitializeComponent();

            connections = new RasPhoneBook();
            currentVPN = new RasDialer();

            CheckForUpdates();

            FormClosing += Client_Closing;
        }
Пример #17
0
        public void Open(bool openUserPhoneBook)
        {
            RasPhoneBookType phoneBookType = RasPhoneBookType.AllUsers;

            if (openUserPhoneBook)
            {
                phoneBookType = RasPhoneBookType.User;
            }

            this.Open(RasPhoneBook.GetPhoneBookPath(phoneBookType));
            this.PhoneBookType = phoneBookType;
        }
Пример #18
0
        public static void ClassInitialize(TestContext context)
        {
            entryName = Guid.NewGuid().ToString();
            invalidEntryName = Guid.NewGuid().ToString();
            phonebookPath = Path.GetTempFileName();

            RasPhoneBook pbk = new RasPhoneBook();
            pbk.Open(phonebookPath);

            entryId = TestUtilities.CreateValidVpnEntry(pbk, entryName);
            
            // The invalid server must be a valid DNS name that would need to be resolved.
            invalidEntryId = TestUtilities.CreateInvalidVpnEntry(pbk, invalidEntryName);
        }
Пример #19
0
 public bool Connect()
 {
     dialer = new RasDialer();
     //string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
     //    + Path.DirectorySeparatorChar + Application.ProductName + Path.DirectorySeparatorChar + "PhoneBook.pbk";
     using (RasPhoneBook phoneBook = new RasPhoneBook())
     {
         phoneBook.Open();
         RasEntry entry = null;
         if (phoneBook.Entries.Contains(connName))
         {
             phoneBook.Entries.Remove(connName);
         }
         if (model.VpnType.ToUpper().Equals("L2TP"))
         {
             entry = RasEntry.CreateVpnEntry(connName, model.Address, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
         }
         else
         {
             entry = RasEntry.CreateVpnEntry(connName, model.Address, RasVpnStrategy.PptpOnly, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
         }
         phoneBook.Entries.Add(entry);
         entry.Options.PreviewDomain = false;
         entry.Options.ShowDialingProgress = false;
         entry.Options.PromoteAlternates = false;
         entry.Options.DoNotNegotiateMultilink = false;
         entry.DnsAddress = IPAddress.Parse("8.8.8.8");
         entry.DnsAddressAlt = IPAddress.Parse("110.75.217.1");
         if (model.VpnType.ToUpper().Equals("L2TP") && !string.IsNullOrEmpty(model.L2tpSec))
         {
             entry.Options.UsePreSharedKey = true;
             entry.UpdateCredentials(RasPreSharedKey.Client, model.L2tpSec);
             entry.Update();
         }
         dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
         dialer.EapOptions = new DotRas.RasEapOptions(false, false, false);
         dialer.HangUpPollingInterval = 0;
         dialer.Options = new DotRas.RasDialOptions(false, false, false, false, false, false, false, false, false, false);
         dialer.EntryName = connName;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
         dialer.AllowUseStoredCredentials = true;
         dialer.AutoUpdateCredentials = RasUpdateCredential.AllUsers;
         dialer.Credentials = new NetworkCredential(model.Username, model.Password);
         eventX = new ManualResetEvent(false);
     }
     handle = dialer.DialAsync();
     eventX.WaitOne(Timeout.Infinite, true);
     return connectSatuts;
 }
Пример #20
0
        public void ConnectionsList()
        {
            using (var rasPhoneBook = new RasPhoneBook())
            {
                // If RasPhoneBookType.AllUsers and code is executed with non-admin privileges:
                // System.UnauthorizedAccessException: 
                // Access to the path 'C:\ProgramData\Microsoft\Network\Connections\Pbk\rasphone.pbk' is denied.
                rasPhoneBook.Open(IpSecClient._phoneBookPath);

                // Diagnostics
                Console.WriteLine("VPN connections: ");
                IpSecClient.PhoneBookEntriesList(rasPhoneBook);
                Console.WriteLine();
            }
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the MainWindowViewModel class.
        /// </summary>
        public MainWindowViewModel()
        {
            this.phonebook = new RasPhoneBook();
            this.phonebook.Changed += new EventHandler<EventArgs>(this.phonebook_Changed);
            this.phonebook.EnableFileWatcher = true;

            this.dialer = new RasDialer();
            this.dialer.DialCompleted += new System.EventHandler<DialCompletedEventArgs>(this.dialer_DialCompleted);
            this.dialer.StateChanged += new System.EventHandler<StateChangedEventArgs>(this.dialer_StateChanged);

            this.CreateEntry = new RelayCommand(() => this.OnCreateEntry());
            this.Dial = new RelayCommand<RasEntry>((item) => this.OnDial(item));
            this.Disconnect = new RelayCommand(() => this.OnDisconnect());
            this.WindowInit = new RelayCommand(() => this.OnWindowInit());
        }
Пример #22
0
        public static void CreateVPN(string connName, string serverIP, string userName, string password)
        {
            if (connName.ToUpper().EndsWith("US"))
            {
                CreateVPN_US(connName, serverIP, userName, password);
                return;
            }
            DotRas.RasDialer dialer = new DotRas.RasDialer();
            DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook();
            allUsersPhoneBook.Open();

            RasEntry entry = null;
            if (!allUsersPhoneBook.Entries.Contains(connName))
            {
                entry = RasEntry.CreateVpnEntry(connName, serverIP, RasVpnStrategy.PptpOnly, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
                entry.Options = RasEntryOptions.Custom;
                entry.EncryptionType = RasEncryptionType.Optional;
                entry.Options = entry.Options |= RasEntryOptions.RequirePap;
                entry.Options = entry.Options |= RasEntryOptions.RequireChap;
                entry.Options = entry.Options |= RasEntryOptions.RequireMSChap;
                entry.Options = entry.Options |= RasEntryOptions.RequireMSChap2;
                allUsersPhoneBook.Entries.Add(entry);
            }
            else
            {
                entry = allUsersPhoneBook.Entries[connName];
                entry.PhoneNumber = serverIP;
                IPAddress _ip;
                IPAddress.TryParse(serverIP, out _ip);
                entry.IPAddress = _ip;
            }
            dialer.EntryName = connName;
            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            try
            {
                NetworkCredential nc = new NetworkCredential(userName, password);
                entry.UpdateCredentials(nc);
                entry.Update();
                dialer.DialAsync();
            }
            catch (Exception e)
            {
                Log.Error(serverIP + "Create VPN Connection fail.\n +" + e.Message);
                return;
            }
        }
Пример #23
0
        static void Main(string[] args)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    Console.WriteLine(entry.Name);
                }
            }

            Console.WriteLine("Press any key to continue.");
            Console.ReadKey(true);
        }
Пример #24
0
        /// <summary>
        /// Opens the phone book.
        /// </summary>
        /// <param name="fileName">The path (including filename) of a phone book.</param>
        /// <remarks>This method opens an existing phone book or creates a new phone book if the file does not already exist.</remarks>
        /// <exception cref="System.ArgumentException"><paramref name="fileName"/> is an empty string or 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 static RasPhoneBook Open(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                ThrowHelper.ThrowArgumentException("fileName", Resources.Argument_StringCannotBeNullOrEmpty);
            }
            else if (string.IsNullOrWhiteSpace(Path.GetFileName(fileName)))
            {
                ThrowHelper.ThrowArgumentException("fileName", Resources.Argument_InvalidFileName);
            }

            RasPhoneBook result = new RasPhoneBook();

            result.Load(fileName);

            return(result);
        }
Пример #25
0
        static void Main(string[] args)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    Console.WriteLine(entry.Name);
                }
            }

            Console.WriteLine("Press any key to continue.");
            Console.ReadKey(true);
        }
        public void 创建链接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                RasEntry VPN条目;

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN条目 = RasEntry.CreateVpnEntry(VPN服务名, VPN地址, DotRas.RasVpnStrategy.PptpOnly, DotRas.RasDevice.Create(VPN服务名, DotRas.RasDeviceType.Vpn));
                VPN条目.Options.UseLogOnCredentials = true;
                VPN条目.Options.ReconnectIfDropped = false;
                VPN条目.RedialCount = 0;
                VPN条目.RedialPause = 1;

                VPN电话本.Entries.Add(VPN条目);
            }
            catch
            {
                //调试信息.Text = "[信息] 准备工作已经做好可以开始拨号\r\n";
            }
        }
Пример #27
0
        private static bool CreateConnector()
        {
            RasPhoneBook book = new RasPhoneBook();
            try
            {
                book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                if (book.Entries.Contains(ConnectorName))
                {
                    book.Entries[ConnectorName].PhoneNumber = " ";
                    book.Entries[ConnectorName].Update();
                }
                else
                {
                    //ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
                    RasDevice device = RasDevice.GetDevices().First(o => o.DeviceType == RasDeviceType.PPPoE);
                    RasEntry entry = RasEntry.CreateBroadbandEntry(ConnectorName, device);
                    entry.PhoneNumber = " ";
                    book.Entries.Add(entry);
                }
                try
                {
                    ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
                    foreach (RasConnection con in conList)
                    {
                        con.HangUp();
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("General - Logout abnormal(Exception): " + ex);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create a PPPoE connection fails(Exception): " + ex);
                return false;
            }
        }
Пример #28
0
        public modem()
        {
            try
            {
                dialer    = new RasDialer();
                phonebook = new RasPhoneBook();

                dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(dialer_DialCompleted);
                dialer.StateChanged  += new EventHandler <StateChangedEventArgs>(dialer_StateChanged);
                phonebook.Open();

                Entry = new string[phonebook.Entries.Count];

                for (int i = 0; i < phonebook.Entries.Count; i++)
                {
                    Entry[i] = phonebook.Entries[i].Name;
                }
            }
            catch (Exception ex)
            {
                IPayBox.AddToLog(IPayBox.Logs.Main, "Не удалось инициализировать класс работы с GPRS;" + ex.Message);
            }
        }
Пример #29
0
        /// <summary>
        /// 初始化RasEntry列表
        /// </summary>
        private void InitRasEntryList()
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            this.cmbPhoneNumber.Items.Clear();
            this.entryList.Clear();
            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    if (RasEntryType.Vpn == entry.EntryType)
                    {
                        AddEntry(entry);
                    }
                }
            }
            if (this.cmbPhoneNumber.Items.Count > 0)
            {
                this.cmbPhoneNumber.SelectedIndex = 0;
            }
        }
Пример #30
0
 /// <summary>
 /// 删除指定名称的VPN
 /// 如果VPN正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
 /// </summary>
 /// <param name="delVpnName"></param>
 public void TryDeleteVPN(string delVpnName)
 {
     RasDialer dialer = new RasDialer();
     RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
     allUsersPhoneBook.Open();
     if (allUsersPhoneBook.Entries.Contains(delVpnName))
     {
         allUsersPhoneBook.Entries.Remove(delVpnName);
     }
 }
Пример #31
0
        public void OwnerTest()
        {
            string name = "Test Entry";
            RasPhoneBook expected = new RasPhoneBook();

            RasEntry target = new RasEntry(name);
            target.Owner = expected;

            RasPhoneBook actual = target.Owner;

            Assert.AreEqual(expected, actual);
        }
Пример #32
0
        public void RenameInvalidEntryNameTest()
        {
            string name = "Test Entry";
            string newEntryName = ".\\Test*!";
            RasPhoneBook pbk = new RasPhoneBook();

            RasEntry target = new RasEntry(name);
            target.Owner = pbk;

            Mock<IRasHelper> mock = new Mock<IRasHelper>();
            RasHelper.Instance = mock.Object;

            mock.Setup(o => o.IsValidEntryName(pbk, newEntryName)).Returns(false);

            target.Rename(newEntryName);
        }
Пример #33
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);
         dialer.EntryName = updateVPNname;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
     }
 }
Пример #34
0
        private void LoadEntryNamesComboBox()
        {
            this.EntryNamesComboBox.Items.Clear();
            this.EntryNamesComboBox.Items.Add(new ComboBoxItem("Select one..."));

            using (RasPhoneBook pbk = new RasPhoneBook())
            {
                pbk.Open(this.PhoneBookTextBox.Text);

                foreach (RasEntry entry in pbk.Entries)
                {
                    this.EntryNamesComboBox.Items.Add(new ComboBoxItem(entry.Name, entry.Owner.Path));
                }                
            }

            this.EntryNamesComboBox.SelectedIndex = 0;
            this.EntryNamesComboBox.Enabled = true;
        }
Пример #35
0
        //This creates the M5 phonebook with all the necessary parameters in it
        private static void CreateRas(string phonebookPath)
        {
            DotRas.RasPhoneBook pb = new DotRas.RasPhoneBook();
            pb.Open(phonebookPath);
            RasDevice rasDevice = RasDevice.GetDevices().Where(P => P.DeviceType == RasDeviceType.Modem && P.Name.ToUpper().StartsWith("M5-")).FirstOrDefault();

            if (rasDevice == null)
            {
                return;
            }

            RasEntry entry = pb.Entries.Where(p => p.Name == "M5_1").FirstOrDefault();

            if (entry == null)
            {
                entry = RasEntry.CreateDialUpEntry("M5_1", "0", rasDevice);
            }

            entry.FramingProtocol = RasFramingProtocol.Ppp;
            entry.EncryptionType  = RasEncryptionType.None;
            entry.FrameSize       = 0;

            entry.Options.DisableLcpExtensions    = true;
            entry.Options.DisableNbtOverIP        = true;
            entry.Options.DoNotNegotiateMultilink = true;
            entry.Options.DoNotUseRasCredentials  = true;
            entry.Options.Internet            = false;
            entry.Options.IPHeaderCompression = false;
            entry.Options.ModemLights         = true;
            entry.Options.NetworkLogOn        = false;

            entry.Options.PreviewDomain       = false;
            entry.Options.PreviewPhoneNumber  = false;
            entry.Options.PreviewUserPassword = false;
            entry.Options.PromoteAlternates   = false;

            entry.Options.ReconnectIfDropped   = false;
            entry.Options.RemoteDefaultGateway = false;

            entry.Options.RequireChap                = false;
            entry.Options.RequireDataEncryption      = false;
            entry.Options.RequireEap                 = false;
            entry.Options.RequireEncryptedPassword   = false;
            entry.Options.RequireMSChap              = false;
            entry.Options.RequireMSChap2             = false;
            entry.Options.RequireMSEncryptedPassword = false;
            entry.Options.RequirePap                 = false;
            entry.Options.RequireSpap                = false;
            entry.Options.RequireWin95MSChap         = false;

            entry.Options.SecureClientForMSNet = true;
            entry.Options.SecureFileAndPrint   = true;
            entry.Options.SecureLocalFiles     = true;

            entry.Options.SharedPhoneNumbers  = false;
            entry.Options.SharePhoneNumbers   = false;
            entry.Options.ShowDialingProgress = false;

            entry.Options.SoftwareCompression = false;
            entry.Options.TerminalAfterDial   = false;
            entry.Options.TerminalBeforeDial  = false;

            entry.Options.UseCountryAndAreaCodes  = false;
            entry.Options.UseGlobalDeviceSettings = false;
            entry.Options.UseLogOnCredentials     = false;
            entry.Options.UsePreSharedKey         = false;

            if (pb.Entries.Contains(entry.Name))
            {
                entry.Update();
            }
            else
            {
                pb.Entries.Add(entry);
            }
        }
Пример #36
0
        //Dialup
        private Error CreaVPNxTel()
        {
            Error cxnErr = new Error();

            string telDefault = TransacManager.ProtoConfig.CONFIG.Telefono;// "08006665807";
            string prefijo = TransacManager.ProtoConfig.CONFIG.CxnTelPrefijo;// "11000";
            string separador = "w";
            if (String.IsNullOrEmpty(prefijo))
            {
                prefijo = "";
                separador = "";
            }
            string modemDefault = TransacManager.ProtoConfig.CONFIG.CxnTelNombreModem;// "Conexant USB CX93010 ACF Modem";
            string user = TransacManager.ProtoConfig.CONFIG.CxnTelUser;// "bmtp";
            string pass = TransacManager.ProtoConfig.CONFIG.CxnTelPass;// "bmtp";
            uint timeout = TransacManager.ProtoConfig.CONFIG.CxnTelTimeout;

            string nombre1, nombre2, nombre3, port1, port2, port3, tel1, tel2, tel3;

            Conexion cxn = new Conexion();

                string rdo = cxn.Leer_XMLprn(out nombre1, out nombre2, out nombre3, out port1, out  port2, out port3, out tel1, out tel2, out tel3, TransacManager.ProtoConfig.CONFIG);
                string[] tel = new string[4];

                if (rdo == null)
                {
                    tel[0] = tel1;
                    tel[1] = tel2;
                    tel[2] = tel3;
                    tel[3] = telDefault;
                }
                else
                    tel[0] = telDefault;

                string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

                using (RasPhoneBook pbk = new RasPhoneBook())
                {
                    pbk.Open(path);

                    // Find the device that will be used to dial the connection.
                    RasDevice device = RasDevice.GetDevices().Where(u => u.Name == modemDefault && u.DeviceType == RasDeviceType.Modem).First();

                    RasEntry entry;

                    ICollection<RasConnection> conecciones = RasConnection.GetActiveConnections();

                    if (conecciones.Count > 0)
                    {
                        RasConnection conn1 = conecciones.Where(o => o.EntryName == "BMTP Dial up").First();
                        conn1.HangUp();
                    }

                    pbk.Entries.Clear();

                    try
                    {
                        entry = RasEntry.CreateDialUpEntry("BMTP Dial up", prefijo + separador + tel[0], device);

                        if (rdo == null)
                        {
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[1]);
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[2]);
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + telDefault);
                            LogBMTP.LogMessage("Se leyó PRN. Telefonos alternativos cargados.", lvlLogCxn, TimeStampLog);
                        }
                        else
                        {
                            LogBMTP.LogMessage("No hay PRN. Intentará conectar con número telefónico por defecto.", lvlLogCxn, TimeStampLog);
                        }

                        //entry.Options.ModemLights = true;
                        //entry.Options.ShowDialingProgress = true;
                        //entry.Options.TerminalBeforeDial = true;
                        //entry.Options.TerminalAfterDial = true;

                        pbk.Entries.Add(entry);

                        using (RasDialer dialer = new RasDialer())
                        {
                            dialer.Dispose();
                            dialer.EntryName = "BMTP Dial up";
                            dialer.PhoneBookPath = path;
                            dialer.Credentials = new NetworkCredential(user, pass);

                            dialer.Timeout = (int)timeout;
                            dialer.Options.DisableReconnect = false;
                            dialer.Options.SetModemSpeaker = true;

                            dialer.Dial();
                        }
                    }
                    catch (Exception e)
                    {
                        pbk.Entries.Clear();
                        LogBMTP.LogMessage(e.ToString(), lvlLogExcepciones, TimeStampLog);

                        cxnErr.CodError = (int)ErrComunicacion.CXN_TELEFONOex;
                        cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación por telefono.";
                        cxnErr.Estado = 0;
                        LogBMTP.LogMessage("Excepción: " + cxnErr.CodError + " " + cxnErr.Descripcion, lvlLogExcepciones, TimeStampLog);
                        LogBMTP.LogMessage("Excepción: " + e.ToString(), lvlLogExcepciones, TimeStampLog);
                    }
                }

                return cxnErr;
        }
Пример #37
0
        public void GetCredentials1ServerPreSharedKeyTest()
        {
            RasPhoneBook pbk = new RasPhoneBook();

            RasEntry target = new RasEntry("Test Entry");
            target.Owner = pbk;

            NetworkCredential expected = new NetworkCredential(string.Empty, "********", string.Empty);

            Mock<IRasHelper> mock = new Mock<IRasHelper>();
            RasHelper.Instance = mock.Object;

            mock.Setup(o => o.GetCredentials(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<NativeMethods.RASCM>())).Returns(expected);

            NetworkCredential actual = target.GetCredentials(RasPreSharedKey.Server);

            Assert.AreEqual(expected, actual);
        }
Пример #38
0
        public void ClearCredentials1ServerPreSharedKeyTest()
        {
            RasPhoneBook pbk = new RasPhoneBook();

            RasEntry target = new RasEntry("Test Entry");
            target.Owner = pbk;

            Mock<IRasHelper> mock = new Mock<IRasHelper>();
            RasHelper.Instance = mock.Object;

            mock.Setup(o => o.SetCredentials(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<NativeMethods.RASCREDENTIALS>(), true)).Returns(true);

            bool result = target.ClearCredentials(RasPreSharedKey.Server);

            Assert.IsTrue(result);
        }
        private static Dictionary<Guid, string> GetRASIdNameDictionary()
        {
            var phonebook = new RasPhoneBook();
            phonebook.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));

            var dictionary = new Dictionary<Guid, string>();
            foreach (var entry in phonebook.Entries)
            {
                dictionary[entry.Id] = entry.Name;
            }

            return dictionary;
        }
Пример #40
0
        public override bool Connect()
        {
            this.connected = false;

            try
            {
                this.rasProperties = new RasProperties(this.ParentForm, this);

                DirectoryInfo directoryInfo = (new FileInfo(this.GetType().Assembly.Location)).Directory;

                if ((directoryInfo == null || directoryInfo.Exists == false) && string.IsNullOrEmpty(this.PhonebookPath))
                {
                    rasProperties.Error("The phonebook path hasn't been set. Aborting RAS connection.");
                    return this.connected = false;
                }

                this.Embed(this.rasProperties);

                // The 'RasDevice.GetDeviceByName([string], [RasDeviceType])' method is obsolete as of DotRas (ChangeSet 93435):
                RasEntry entry = RasEntry.CreateVpnEntry(this.Favorite.Name, this.Favorite.ServerName,
                                                         RasVpnStrategy.Default, (from d in RasDevice.GetDevices()
                                                                                  where
                                                                                      d.DeviceType == RasDeviceType.Vpn &&
                                                                                      d.Name.ToUpper()
                                                                                       .Contains("(PPTP)")
                                                                                  select d).FirstOrDefault());

                // Create the Ras phonebook or upen it under the below mentioned path.
                string phonebookPath = this.PhonebookPath ?? Path.Combine(directoryInfo.FullName, "rasphone.pbk");

                this.rasPhoneBook = new RasPhoneBook();
                this.rasPhoneBook.Open(phonebookPath);

                this.rasProperties.RasEntry = entry;

                // Check if the entry hasn't been added.
                if (!this.rasPhoneBook.Entries.Contains(entry.Name))
                {
                    this.rasPhoneBook.Entries.Add(entry);
                }

                this.rasDialer = new RasDialer
                                     {
                                         PhoneBookPath = phonebookPath,
                                         // Set the credentials later ...
                                         Credentials = null,
                                         // Initialize with default values (same as the designer would do)
                                         EapOptions = new RasEapOptions(false, false, false),
                                         // Initialize with default values (same as the designer would do)
                                         Options = new RasDialOptions(false, false, false, false, false, false, false, false, false, false, false),
                                         EntryName = this.Favorite.Name
                                     };

                this.rasDialer.Error += this.rasDialer_Error;
                this.rasDialer.DialCompleted += this.rasDialer_DialCompleted;
                this.rasDialer.StateChanged += this.rasDialer_StateChanged;

                // Set the ras dialer credentials and checks if setting the credentials has been
                // successful; if not NULL will be set to the ras dealer credentials and in that
                // case we'll load the RAS connection from the phone book.
                if ((this.rasDialer.Credentials = this.Favorite.Credential) == null)
                {
					rasProperties.Warn("Terminals has no credentials, showing dial dialog ...");

                    RasDialDialog rasDialDialog = new RasDialDialog
                                                      {
                                                          PhoneBookPath = phonebookPath,
                                                          EntryName = entry.Name
                                                      };

                    if (rasDialDialog.ShowDialog() == DialogResult.OK)
                    {
						rasProperties.Info(string.Format("{0} {1}", "Thank you for providing the credentials." + "Using the Terminals credentials, dialing ..."));
                        return this.connected = true;
                    }

                    rasProperties.Error("Terminating RAS connection, either credentials haven't been supplied or error connecting to the target.");
                    return this.connected = false;
                }

				rasProperties.Info("Using the Terminals credentials, dialing ...");
                this.rasDialer.Dial();

                return this.connected = true;
            }
            catch (Exception ex)
            {
				rasProperties.Error(string.Format("Terminals  was unable to create the {0} connection.", this.Favorite.Protocol), ex);
                return this.connected = false;
            }
        }
Пример #41
0
        public void UpdateCredentialsTest()
        {
            string name = "Test Entry";
            NetworkCredential credentials = new NetworkCredential("Test", "User");

            RasPhoneBook pbk = new RasPhoneBook();

            RasEntry target = new RasEntry(name);
            target.Owner = pbk;

            Mock<IRasHelper> mock = new Mock<IRasHelper>();
            RasHelper.Instance = mock.Object;

            mock.Setup(o => o.SetCredentials(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<NativeMethods.RASCREDENTIALS>(), false)).Returns(true);

            bool result = target.UpdateCredentials(credentials);

            Assert.IsTrue(result);
        }
Пример #42
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 = null;

                foreach (RasDevice dev in RasDevice.GetDevices())
                {
                    if (dev.DeviceType == RasDeviceType.PPPoE)
                    {
                        device = dev;
                        break;
                    }
                }
              //  = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
                RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device);    //建立宽带连接Entry
                entry.PhoneNumber = " ";
                allUsersPhoneBook.Entries.Add(entry);
            }
        }