/// <summary>
        /// Creates a dial-up connection in the windows list of connections.
        /// </summary>
        /// <param name="dialupConnectionName">The name of the dial-up connection to create.</param>
        /// <param name="phoneNumber">The phone number to be dialed when dialing the dial-up connection.</param>
        /// <param name="deviceType">The RAS (Remote Access Serice) device type. If null the default is used i.e.RasDeviceType.Modem</param>
        /// <param name="deviceName">The name of the RAS device. May not be null.</param>
        public void CreateDialupConnectionEntry(
            string dialupConnectionName,
            string phoneNumber,
            Nullable <RasDeviceType> deviceType,
            string deviceName)
        {
            _rasPhoneBook.Open();
            if (string.IsNullOrEmpty(dialupConnectionName))
            {
                throw new NullReferenceException("dialupConnectionName may not be null or empty when requesting for a dial-up connection to be created.");
            }
            if (string.IsNullOrEmpty(phoneNumber))
            {
                throw new NullReferenceException("phoneNumber may not be null or empty when requesting to for dial-up connection to be created.");
            }
            if (!deviceType.HasValue)
            {
                deviceType = RasDeviceType.Modem;
            }
            RasEntry entry = RasEntry.CreateDialUpEntry(
                dialupConnectionName,
                phoneNumber,
                RasDevice.GetDeviceByName(deviceName, deviceType.Value));

            _rasPhoneBook.Entries.Add(entry);
        }
Exemple #2
0
        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();
        }
Exemple #3
0
        private void createVpnEntry(string sVpnIp)
        {
            this.AllUsersPhoneBook.Open();

            if (this.AllUsersPhoneBook.Entries.Contains(sEntryName))
            {
                //todo
                this.AllUsersPhoneBook.Entries[sEntryName].PhoneNumber = sVpnIp;
            }
            else
            {
                try
                {
                    RasEntry entry = RasEntry.CreateVpnEntry(sEntryName, sVpnIp, RasVpnStrategy.L2tpOnly,
                                                             RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
                    entry.EncryptionType = RasEncryptionType.Optional;

                    this.AllUsersPhoneBook.Entries.Add(entry);
                }
                catch (Exception ex)
                {
                    tMessage.AppendText(ex.ToString());
                }
            }
        }
        /// <summary>
        /// Creates a VPN connection in the Windows list of connections.
        /// </summary>
        /// <param name="vpnConnectionName">The name of the VPN connection to create.</param>
        /// <param name="strategy">The VPN strategy to use. If null the default strategy is used.</param>
        /// <param name="deviceType">The RAS (Remote Access Serice) device type. If null the default is used i.e.RasDeviceType.Vpn</param>
        /// <param name="deviceName">The name of the RAS device. If null the default is used i.e. "(PPTP)".</param>
        public void CreateVPNConnectionEntry(
            string vpnConnectionName,
            Nullable <RasVpnStrategy> strategy,
            Nullable <RasDeviceType> deviceType,
            string deviceName)
        {
            _rasPhoneBook.Open();
            if (string.IsNullOrEmpty(vpnConnectionName))
            {
                throw new NullReferenceException("vpnConnectionName may not be null or empty when requesting for a VPN connection to be created.");
            }
            if (!strategy.HasValue)
            {
                strategy = RasVpnStrategy.Default;
            }
            if (!deviceType.HasValue)
            {
                deviceType = RasDeviceType.Vpn;
            }
            if (string.IsNullOrEmpty(deviceName))
            {
                deviceName = "(PPTP)";
            }
            RasEntry entry = RasEntry.CreateVpnEntry(
                vpnConnectionName,
                IPAddress.Loopback.ToString(),
                strategy.Value,
                RasDevice.GetDeviceByName(deviceName, deviceType.Value));

            _rasPhoneBook.Entries.Add(entry);
        }
Exemple #5
0
 /// <summary>
 /// create/update vpn entry
 /// </summary>
 /// <param name="name">name of the connection</param>
 /// <param name="ip">ip address of connection</param>
 public void SetEntry(string name, string ip)
 {
     // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
     this.AllUsersPhoneBook.Open(true);
     // check if this entry has already exist
     if (!this.AllUsersPhoneBook.Entries.Contains(name))
     {
         // create entry
         if (ip == "")
         {
             ip = IPAddress.Loopback.ToString();
         }
         // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
         // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
         RasEntry entry = RasEntry.CreateVpnEntry(name, ip, RasVpnStrategy.PptpFirst,
                                                  RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
         // Add the new entry to the phone book.
         this.AllUsersPhoneBook.Entries.Add(entry);
     }
     else if (ip != "")
     {
         // update entry
         this.AllUsersPhoneBook.Entries[name].PhoneNumber = ip;
         this.AllUsersPhoneBook.Entries[name].Device      = RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn);
         this.AllUsersPhoneBook.Entries[name].Update();
     }
 }
Exemple #6
0
        private void createVpnEntry(string sVpnIp)
        {
            AllUsersPhoneBook.Open(Dialer.PhoneBookPath);

            if (this.AllUsersPhoneBook.Entries.Contains(sEntryName))
            {
                //todo
                this.AllUsersPhoneBook.Entries[sEntryName].PhoneNumber = sVpnIp;
            }
            else
            {
                try
                {
                    RasEntry entry = RasEntry.CreateVpnEntry(sEntryName, sVpnIp, RasVpnStrategy.L2tpOnly,
#pragma warning disable CS0618 // 类型或成员已过时
                                                             device: RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
#pragma warning restore CS0618 // 类型或成员已过时
                    entry.EncryptionType = RasEncryptionType.Optional;

                    this.AllUsersPhoneBook.Entries.Add(entry);
                }
                catch (Exception ex)
                {
                    tMessage.AppendText(ex.ToString());
                }
            }
        }
Exemple #7
0
        private bool CreateVpn()
        {
            if (null == this.VPNItem)
            {
                return(false);
            }
            // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
            this.rasPhoneBook.Open();
            if (this.rasPhoneBook.Entries.Count > 0)
            {
                foreach (RasEntry rasEntry in this.rasPhoneBook.Entries)
                {
                    if (rasEntry.Name.Equals(this.VPNItem.EntryName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        LogManager.InfoWithCallback(string.Format("-> VPN 拨号新IP:{0}", this.VPNItem.IP));
                        rasEntry.PhoneNumber = this.VPNItem.IP;
                        return(false);
                    }
                }
            }

            // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
            // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
            RasEntry entry = RasEntry.CreateVpnEntry(this.VPNItem.EntryName, this.VPNItem.IP, RasVpnStrategy.Default,
                                                     RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

            //Must set to None
            entry.EncryptionType = RasEncryptionType.None;
            // entry.PrerequisiteEntryName
            // Add the new entry to the phone book.
            this.rasPhoneBook.Entries.Add(entry);
            return(true);
        }
Exemple #8
0
        public void GetDeviceByNameTest()
        {
            string        name       = RasDeviceTest.InvalidDeviceName;
            RasDeviceType deviceType = RasDeviceType.Vpn;

            RasDevice target = RasDevice.GetDeviceByName(name, deviceType);

            Assert.IsNotNull(target);
        }
Exemple #9
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnLogin_Click(object sender, EventArgs e)
        {
            string user = this.txtUser.Text;
            string pwd  = this.txtPwd.Text;

            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pwd))
            {
                return;
            }

            object selectItem = this.cmbPhoneNumber.SelectedItem;

            if (selectItem == null)
            {
                if (!string.IsNullOrEmpty(this.cmbPhoneNumber.Text))
                {
                    RasEntry newEntry = RasEntry.CreateVpnEntry(EntryName,
                                                                this.cmbPhoneNumber.Text, RasVpnStrategy.PptpOnly,
                                                                RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn), false);
                    AddRasEntry(newEntry);
                    AddEntry(newEntry);
                    selectItem = new ComboBoxItem {
                        Text = this.cmbPhoneNumber.Text, Val = EntryName
                    };
                }
                else
                {
                    return;
                }
            }
            ComboBoxItem item  = (ComboBoxItem)selectItem;
            RasEntry     entry = entryList.Single(s => s.Name.Equals(item.Val));

            if (entry == null)
            {
                return;
            }
            this.Dialer.EntryName     = entry.Name;
            this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            try
            {
                // Set the credentials the dialer should use.
                this.Dialer.Credentials = new NetworkCredential(user, pwd);

                // 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.btnLogout.Enabled = true;
            }
            catch (Exception ex)
            {
                this.AppendText(ex.ToString());
            }
        }
Exemple #10
0
 public void CreateConnection()
 {
     try
     {
         RPB.Open();
         Entry = RasEntry.CreateVpnEntry(_VpnName, _ServerIP, RasVpnStrategy.PptpOnly,
                                         RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
         RPB.Entries.Add(Entry);
     }
     catch (Exception ex)
     {
     }
 }
Exemple #11
0
        public void GetDeviceByNameCaseSensitiveTest()
        {
            string        name       = RasDeviceTest.ValidDeviceName;
            RasDeviceType deviceType = RasDeviceType.Vpn;

            RasDevice expected = RasDevice.Create(name, deviceType);
            RasDevice actual   = RasDevice.GetDeviceByName(name, deviceType, true);

            RasDeviceComparer comparer = new RasDeviceComparer();
            bool target = comparer.Compare(expected, actual) == 0;

            Assert.IsTrue(target);
        }
Exemple #12
0
        /// <summary>
        /// Occurs when the user clicks the Create Entry 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 CreateEntryButton_Click(object sender, EventArgs e)
        {
            // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
            this.AllUsersPhoneBook.Open();

            // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
            // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
            RasEntry entry = RasEntry.CreateVpnEntry(EntryName, IPAddress.Loopback.ToString(), RasVpnStrategy.Default,
                                                     RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

            // Add the new entry to the phone book.
            this.AllUsersPhoneBook.Entries.Add(entry);
        }
        //---------------------------------------------------------------------------------------
        int CreateDevice(int i)
        {
            PLog(phoneBook.Path, false);
            if (RasEntry.Exists(Globals.vpnIsim, phoneBook.Path))
            {
                PLog("Önceki Vpn Siliniyor...");
                DisconnectDevice();
                RemoveDevice();
            }

            RasEntry entry;

            if (Vpnlist[i].Protocol == "pptp")
            {
                entry = RasEntry.CreateVpnEntry(
                    Globals.vpnIsim,
                    Vpnlist[i].Ip,
                    RasVpnStrategy.PptpFirst,
#pragma warning disable CS0618 // 'RasDevice.GetDeviceByName(string, RasDeviceType)' is obsolete: 'This method will be removed in a future version, please use the GetDevices method to find the devices.'
                    RasDevice.GetDeviceByName(Vpnlist[i].Protocol, RasDeviceType.Vpn));
#pragma warning restore CS0618 // 'RasDevice.GetDeviceByName(string, RasDeviceType)' is obsolete: 'This method will be removed in a future version, please use the GetDevices method to find the devices.'
                this.phoneBook.Entries.Add(entry);
            }
            else
            {
                entry = RasEntry.CreateVpnEntry(
                    Globals.vpnIsim,
                    Vpnlist[i].Ip,
                    RasVpnStrategy.L2tpFirst,
#pragma warning disable CS0618 // 'RasDevice.GetDeviceByName(string, RasDeviceType)' is obsolete: 'This method will be removed in a future version, please use the GetDevices method to find the devices.'
                    RasDevice.GetDeviceByName(Vpnlist[i].Protocol, RasDeviceType.Vpn));
#pragma warning restore CS0618 // 'RasDevice.GetDeviceByName(string, RasDeviceType)' is obsolete: 'This method will be removed in a future version, please use the GetDevices method to find the devices.'
                entry.Options.UsePreSharedKey = true;
                this.phoneBook.Entries.Add(entry);

                foreach (RasEntry e in this.phoneBook.Entries)
                {
                    if (e.PhoneNumber == Vpnlist[i].Ip)
                    {
                        e.UpdateCredentials(RasPreSharedKey.Client, Vpnlist[i].xl2tp);
                    }
                }
            }


            PLog(this.phoneBook.Entries.Count + ". # IP:" + this.phoneBook.Entries[this.phoneBook.Entries.Count - 1].PhoneNumber);
            PLog("Vpn Created: " + Vpnlist[i].Protocol);
            return(1);
        }
Exemple #14
0
        public void GetDeviceByName1TestWithExactMatchOnly()
        {
            string        name           = RasDeviceTest.ValidDeviceName;
            RasDeviceType deviceType     = RasDeviceType.Vpn;
            bool          exactMatchOnly = true;

            RasDevice expected = RasDevice.Create(name, deviceType);

            RasDevice actual;

            actual = RasDevice.GetDeviceByName(name, deviceType, exactMatchOnly);

            RasDeviceComparer comparer = new RasDeviceComparer();
            bool target = comparer.Compare(expected, actual) == 0;

            Assert.IsTrue(target);
        }
Exemple #15
0
 private void btn_CreateRAS_Click(object sender, EventArgs e)
 {
     try
     {
         Userinfo userinfo = new Userinfo(tb_user.Text, tb_pwd.Text);
         this.AllUsersPhoneBook.Open();
         RasEntry entry = RasEntry.CreateVpnEntry(EntryName, IP, RasVpnStrategy.L2tpOnly,
                                                  RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
         entry.Options.DoNotNegotiateMultilink = false;  //多链路
         entry.EncryptionType = RasEncryptionType.None;  //允许未加密密码
         entry.Options.RequireEncryptedPassword = false;
         entry.NetworkProtocols.IPv6            = false; //取消IPV6服务
         entry.Options.CacheCredentials         = true;  //win8以上记住密码
         DialogResult result = MessageBox.Show("你确定要创建账号为 " + userinfo.User + " 密码为 " + userinfo.Pwd + " 的拨号程序吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
         if (result == DialogResult.No)
         {
             return;
         }
         foreach (RasEntry temp in this.AllUsersPhoneBook.Entries)
         {
             if (temp.Name == entry.Name)
             {
                 MessageBox.Show("创建失败,已经存在拨号连接 " + entry.Name, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 return;
             }
         }
         this.status.Text = "创建中...";
         this.AllUsersPhoneBook.Entries.Add(entry);
         if (tb_user.Text != "" && tb_pwd.Text != "")
         {
             NetworkCredential credential = new NetworkCredential(tb_user.Text, tb_pwd.Text);
             entry.UpdateCredentials(credential);
         }
         MessageBox.Show("创建成功!请点击右下角网络连接处的 " + entry.Name + " \n为您添加路由ing...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         btn_hzly_Click(this, new EventArgs());
         this.status.Text = "创建成功!";
     }
     catch
     {
         MessageBox.Show("创建失败,请设定防火墙允许!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         Process.GetCurrentProcess().Kill();
     }
 }
Exemple #16
0
        public void CreateConnection()
        {
            RasPhoneBook AllUsersPhoneBook = new RasPhoneBook();

            AllUsersPhoneBook.Open();

            // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
            // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
            RasEntry entry = RasEntry.CreateVpnEntry(_connectionentry, _Connectionhost, RasVpnStrategy.Default,
                                                     RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

            _Dialer.StateChanged += new EventHandler <StateChangedEventArgs>(ConnectionStateChanged);
            _Dialer.Error        += new EventHandler <ErrorEventArgs>(ErrorEvent);

            // Add the new entry to the phone book.
            if (!(AllUsersPhoneBook.Entries.Contains(_connectionentry)))
            {
                AllUsersPhoneBook.Entries.Add(entry);
            }
        }
Exemple #17
0
        private bool CreateADSL()
        {
            if (null == this.ADSLItem)
            {
                return(false);
            }
            // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
            this.rasPhoneBook.Open();
            if (this.rasPhoneBook.Entries.Count > 0)
            {
                foreach (RasEntry rasEntry in this.rasPhoneBook.Entries)
                {
                    if (rasEntry.Name.Equals(this.ADSLItem.EntryName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        //LogManager.InfoWithCallback(string.Format("-> ADSL 拨号新IP:{0}", this.ADSLItem.IP));
                        //rasEntry.PhoneNumber = this.ADSLItem.IP;
                        rasEntry.PhoneNumber = " ";
                        return(false);
                    }
                }
            }

            // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
            // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
            RasEntry entry = new RasEntry(this.ADSLItem.EntryName)
            {
                Device          = RasDevice.GetDeviceByName("(PPPOE)", RasDeviceType.PPPoE, false),
                FramingProtocol = RasFramingProtocol.Ppp,
                // entry.NetworkProtocols = RasNetworkProtocols;
                RedialCount = 3,
                RedialPause = 60,
                PhoneNumber = string.Empty,
                //Must set to None
                EncryptionType = RasEncryptionType.None
            };

            // entry.PrerequisiteEntryName
            // Add the new entry to the phone book.
            this.rasPhoneBook.Entries.Add(entry);
            return(true);
        }
Exemple #18
0
        private static void CreateOrUpdateVPNEntry(string ip, string user, string pwd)
        {
            RasEntry entry;

            if (!pb.Entries.Contains(VPNNAME))
            {
                entry = RasEntry.CreateVpnEntry(VPNNAME, ip, rasstart, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
                pb.Entries.Add(entry);
            }
            else
            {
                entry             = pb.Entries[VPNNAME];
                entry.PhoneNumber = ip;
                IPAddress _ip;
                IPAddress.TryParse(ip, out _ip);
                entry.IPAddress = _ip;
            }
            NetworkCredential nc = new NetworkCredential(user, pwd);

            entry.UpdateCredentials(nc);
            entry.Update();
        }
Exemple #19
0
        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);
        }
Exemple #20
0
        static public void CreateConnectionEntry(BaseProxyServer ps, ProxyProtocolTypeEnum protocolType)
        {
            if (!ps.IsProtocolAvailable(protocolType))
            {
                throw new ArgumentException("Protocol " + protocolType.ToString() + " not avilable");
            }

            //http://stackoverflow.com/questions/36213393/get-connection-status-vpn-using-dotras
            // File.WriteAllText("your rasphone.pbk  path","")//Add
            RasPhoneBook rasPhoneBook1    = new RasPhoneBook();
            string       rasPhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);//alt RasPhoneBookType.AllUsers

            rasPhoneBook1.Open(rasPhoneBookPath);

            string         deviceTypeStr = "(" + protocolType.ToString() + ")";
            RasVpnStrategy strategy      = (protocolType == ProxyProtocolTypeEnum.L2TP) ? RasVpnStrategy.L2tpOnly : RasVpnStrategy.PptpOnly;
            //alt
            //RasVpnStrategy strategy = RasVpnStrategy.Default;
            RasEntry entry = RasEntry.CreateVpnEntry(ps.GetConnectionName(), ps.Url,
                                                     strategy,
                                                     RasDevice.GetDeviceByName(deviceTypeStr, RasDeviceType.Vpn, false));

            entry.EncryptionType = ps.EncryptionType.ToEnum <RasEncryptionType>();
            if (protocolType == ProxyProtocolTypeEnum.L2TP && !string.IsNullOrEmpty(ps.GetProxyProvider().UserPresharedKey))
            {
                entry.Options.UsePreSharedKey = true;
            }
            rasPhoneBook1.Entries.Add(entry);
            if (protocolType == ProxyProtocolTypeEnum.L2TP && !string.IsNullOrEmpty(ps.GetProxyProvider().UserPresharedKey))
            {
                entry.UpdateCredentials(RasPreSharedKey.Client, ps.GetProxyProvider().UserPresharedKey);
            }

            if (!string.IsNullOrEmpty(ps.GetProxyProvider().VPNLogin))
            {
                //entry.UpdateCredentials(new System.Net.NetworkCredential(ps.JProxyProvider.VPNLogin, ps.JProxyProvider.VPNPassword), false);
            }
        }
Exemple #21
0
        public void VPN_Connect(string VPN_Name, string VPN_ID, string VPN_PW)
        {
            AllUsersPhoneBook = new RasPhoneBook();
            AllUsersPhoneBook.Open();

            if (AllUsersPhoneBook.Entries.Contains(EntryName))
            {
                AllUsersPhoneBook.Entries[EntryName].PhoneNumber = VPN_Name;
                AllUsersPhoneBook.Entries[EntryName].Update();
            }
            else
            {
                RasEntry entry = RasEntry.CreateVpnEntry(EntryName, VPN_Name, RasVpnStrategy.Default,
                                                         RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

                entry.EncryptionType = RasEncryptionType.None;

                AllUsersPhoneBook.Entries.Add(entry);
            }

            Dialer = new RasDialer();
            Dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(Dialer_DialCompleted);

            this.Dialer.EntryName     = EntryName;
            this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            try
            {
                this.Dialer.Credentials = new NetworkCredential(VPN_ID, VPN_PW);
                this.handle             = this.Dialer.DialAsync();
                VPN_Status = (int)status.Defalut;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemple #22
0
        public void addVpnConfiguration(string serverdescription, string servername)
        {
            this.AllUsersPhoneBook = new RasPhoneBook();
            this.AllUsersPhoneBook.Open(true);
            string          serverAddress = this.getipaddressbyname(servername);
            RasEntryOptions options       = new RasEntryOptions();

            options.PreviewDomain           = false;
            options.UsePreSharedKey         = true;
            options.ShowDialingProgress     = true;
            options.RemoteDefaultGateway    = true;
            options.DoNotNegotiateMultilink = true;
            options.UseLogOnCredentials     = true;
            //RasDevice deviceByName = RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn);
            RasDevice deviceByName = RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn);
            RasEntry  item;

            if (this.AllUsersPhoneBook.Entries.Contains(serverdescription))
            {
                //'entry' must have the PhoneNumber, DeviceType, DeviceName, FramingProtocol, and EntryType properties set as a minimum.
                item             = this.AllUsersPhoneBook.Entries[serverdescription];
                item.PhoneNumber = serverAddress;
                item.Device      = deviceByName;
                item.Options     = options;

                item.UpdateCredentials(RasPreSharedKey.Client, "51sync");
                item.Update();
            }
            else
            {
                item         = RasEntry.CreateVpnEntry(serverdescription, serverAddress, RasVpnStrategy.L2tpFirst, deviceByName);
                item.Options = options;
                this.AllUsersPhoneBook.Entries.Add(item);
                item.UpdateCredentials(RasPreSharedKey.Client, "51sync");
            }
        }
Exemple #23
0
        static void Main(string[] args)
        {
            //Do some UAC checks
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool             hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
            {
                RunElevated(Process.GetCurrentProcess().MainModule.FileName);
                return;
            }
            // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
            AllUsersPhoneBook.Open();

            string EntryName = System.Configuration.ConfigurationManager.AppSettings["DialupName"];

            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["host"]))
            {
                // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
                // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
                RasEntry entry = RasEntry.CreateVpnEntry(EntryName, System.Configuration.ConfigurationManager.AppSettings["host"], RasVpnStrategy.PptpFirst,
                                                         RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));


                // Add the new entry to the phone book.
                try
                {
                    AllUsersPhoneBook.Entries.Add(entry);
                }
                catch (System.ArgumentException err)
                {
                    int x = 0;
                    //Most likely, already exists.  Continue on and try connection.
                }
            }
            Dialer.EntryName      = EntryName;
            Dialer.PhoneBookPath  = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            Dialer.StateChanged  += new EventHandler <StateChangedEventArgs>(Dialer_StateChanged);
            Dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(Dialer_DialCompleted);

            try
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["User"]))
                {
                    Dialer.AllowUseStoredCredentials = true;
                }
                else
                {
                    // Set the credentials the dialer should use.
                    Dialer.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["User"],
                                                               System.Configuration.ConfigurationManager.AppSettings["pass"]);
                }

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.

                Dialer.Dial();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            foreach (string routeLine in System.Configuration.ConfigurationManager.AppSettings["route"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                string[] parts = routeLine.Split(" ".ToCharArray());
                AddRoute(parts[0], parts[1], parts[2]);
            }
        }
Exemple #24
0
        public Form1()
        {
            KillProcess();

            InitializeComponent();


            timer.Elapsed  += timer_Elapsed;
            timer.AutoReset = false;

            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);
            }



            if (File.Exists(kwPath))
            {
                using (StreamReader rd = new StreamReader(kwPath))
                {
                    string   txt = rd.ReadToEnd();
                    string[] arr = txt.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string item in arr)
                    {
                        string[] arrs = item.Split(',');
                        if (arrs.Length != 3)
                        {
                            continue;
                        }
                        Keyword keyword = new Keyword();
                        keyword.kw    = arrs[0];
                        keyword.url   = arrs[1];
                        keyword.total = int.Parse(arrs[2]);
                        list.Add(keyword);
                    }
                }
            }

            #region
            var action = new Action(delegate()
            {
                while (true)
                {
                    foreach (Keyword item in list)
                    {
                        try
                        {
                            while (true)
                            {
                                lock (isProcessOkObj)
                                {
                                    if (isProcessOk == false)
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                        continue;
                                    }
                                    this.textBox2.Text = string.Empty;
                                    ShowMsg("whileprocess");
                                    isProcessOk = false;
                                    break;
                                }
                            }
                            keyword = item;
                            if (keyword.showcount <= 0)
                            {
                                System.Threading.Thread.Sleep(1000);
                                continue;
                            }
                            System.Threading.Thread.Sleep(ran.Next(3, 9) * 1000);
#if !DEBUG
                            while (true)
                            {
                                lock (isConnObj)
                                {
                                    if (isConn == false)
                                    {
                                        ShowMsg("拨号中---" + keyword.kw);
                                        Dial();
                                        System.Threading.Thread.Sleep(1000);
                                        continue;
                                    }
                                    break;
                                }
                            }
#endif
                            if (this.InvokeRequired)
                            {
                                this.Invoke(new Action(delegate()
                                {
                                    if (wb != null && wb.IsDisposed == false)
                                    {
                                        ShowMsg("回收");
                                        wb.Dispose();
                                        wb = null;
                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                        IntPtr pHandle = GetCurrentProcess();
                                        SetProcessWorkingSetSize(pHandle, -1, -1);
                                    }
                                    wb = new WebBrowser();
                                    wb.ScriptErrorsSuppressed = true;
                                    wb.Navigating            += wb_Navigating;
                                    wb.DocumentCompleted     += wb_DocumentCompleted;

                                    wb.Navigate("https://www.baidu.com");
                                }));
                            }
                        }
                        catch (Exception ex)
                        {
                            ShowMsg(ex.Message);
                        }
                    }
                }
            });
            action.BeginInvoke(null, null);
            #endregion
        }
Exemple #25
0
        /// <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);
        }
 private void CreateOrUpdateVPNEntry(string ip)
 {
     Log.debug(TAG, "CreateOrUpdateVPNEntry ip:" + ip);
     try
     {
         RasEntry entry = null;
         if (allUsersPhoneBook.Entries.Contains(VPNNAME))
         {
             entry = allUsersPhoneBook.Entries[VPNNAME];
             entry.EncryptionType = RasEncryptionType.Optional;
             entry.PhoneNumber    = ip;
             IPAddress _ip;
             IPAddress.TryParse(ip, out _ip);
             entry.IPAddress = _ip;
             entry.Options.UsePreSharedKey = true;
             entry.UpdateCredentials(RasPreSharedKey.Client, "123456");
             entry.Update();
         }
         else
         {
             entry = RasEntry.CreateVpnEntry(VPNNAME, ip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
             entry.EncryptionType          = RasEncryptionType.Optional;
             entry.Options.UsePreSharedKey = true;
             allUsersPhoneBook.Entries.Add(entry);
             entry.UpdateCredentials(RasPreSharedKey.Client, "123456");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("创建VPN失败!error msg:" + ex.ToString());
         Log.debug(TAG, "CreateOrUpdateVPNEntry error:" + ex.ToString());
     }
 }
Exemple #27
0
 public void GetDeviceByNameNullNameExceptionTest()
 {
     RasDevice.GetDeviceByName(null, RasDeviceType.Vpn);
 }
Exemple #28
0
        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称,及IP)
        /// </summary>
        /// <param name="updateVPNname">更新vpn名称</param>
        /// <param name="updateVPNip">更新VPN地址</param>
        /// <returns>操作成功:true,操作失败:false</returns>
        public bool CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            bool     result    = true;
            DateTime startTime = DateTime.Now;
            string   msg       = string.Empty;

            try
            {
                RasDialer    dialer            = new RasDialer();
                RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
                allUsersPhoneBook.Open();

                // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
                if (allUsersPhoneBook.Entries.Contains(updateVPNname))
                {
                    allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                    ////不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
                    bool updateResult = allUsersPhoneBook.Entries[updateVPNname].Update();
                    msg = "更新VPN服务器通道为:" + updateVPNip;
                    if (updateResult)
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "成功", Color.Green, false);
                    }
                    else
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "失败", Color.Green, false);
                    }
                }
                else
                {
                    ////创建一个新VPN
                    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);
                    msg = "新建VPN通道:" + updateVPNip + "成功";
                    MessagePipe.ExcuteWriteMessageEvent(msg, Color.Green, false);
                }
            }
            catch (Exception ex)
            {
                result = false;
                MessagePipe.ExcuteWriteMessageEvent("更新或创建VPN通道异常:" + ex.Message.ToString(), Color.Green, true);
            }
            finally
            {
                ////记录交互日志
                string request = "VPN通道名称:" + updateVPNname + ";VPN账号:" + this.userName + ";VPN地址:" + updateVPNip;
                RecordLog.RecordInteractionLog(updateVPNname, "创建VPN通道", request, msg, DateTime.Now.Subtract(startTime), updateVPNip);
            }

            return(result);
        }
        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称,及IP)
        /// </summary>
        /// <param name="updateVPNname"></param>
        /// <param name="updateVPNip"></param>
        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);
            }
        }
Exemple #30
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;
            }
        }