public DialCompletedEventArgs(RasHandle handle, Exception error, bool cancelled, bool timedOut, bool connected, object userState)
     : base(error, cancelled, userState)
 {
     this.Handle = handle;
     this.TimedOut = timedOut;
     this.Connected = connected;
 }
Esempio n. 2
0
 /*
  * When RasDialer has finished its connection attempt
  */
 private void RasDialer_DialCompleted(object sender, DialCompletedEventArgs e)
 {
     if (e.Cancelled) // The conneciton was cancelled
     {
         StatusTxt.Text = "Cancelled";
     }
     else if (e.TimedOut) // Connection timed out
     {
         StatusTxt.Text = "Connection Timed out";
     }
     else if (e.Error != null) // Other error
     {
         RasHandle handle = null;
         StatusTxt.Text               = "Error";
         State                        = false;
         CountriesList.Enabled        = true;
         PicBtnSwitch.BackgroundImage = global::VPN.Properties.Resources.SwitchOffBlk;
         Debug.WriteLine(e.Error);
         Disconnect();
         RemoveConnection();
     }
     else if (e.Connected) // If connected
     {
         StatusTxt.Text = STATCONNECT;
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Occurs when the user clicks the Dial button.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param>
        private void DialButton_Click(object sender, EventArgs e)
        {
            StatusTextBox.Clear();

            // This button will be used to dial the connection.
            Dialer.EntryName     = EntryName;
            Dialer.PhoneBookPath = PHONE_BOOK_PATH;

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

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                // Begin dialing the connection; this will raise events from the dialer instance.
                handle = Dialer.DialAsync();

                // Enable the disconnect button for use later.
                DisconnectButton.Enabled = true;
            }
            catch (Exception ex)
            {
                StatusTextBox.AppendText(ex.ToString());
            }
        }
Esempio n. 4
0
        private void bConnect_Click(object sender, EventArgs e)
        {
            string sServerip = tServerIP.Text;
            string sUsername = tUsername.Text;
            string sPassword = tUserkey.Text;

            this.tMessage.Clear();
            createVpnEntry(sServerip);

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

            try
            {
                this.Dialer.Credentials = new NetworkCredential(sUsername, sPassword);
                this.handle = this.Dialer.DialAsync();
                this.tMessage.AppendText("正在尝试连接...\r\n");

            }
            catch (Exception ex)
            {
                this.tMessage.AppendText(ex.ToString());
            }

        }
Esempio n. 5
0
        private void f_Vpnconfiger_Load(object sender, EventArgs e)                                                         //Bij het laden van het programma. Hier wordt onder andere gecheckt
        {                                                                                                                   //wat er in de config file staat en vult die gegevens in in de textboxen.
            if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
            {
                MessageBox.Show("The vpnclient is already active! Open the application via the system tray (icon at the bottom right).");
                this.Close();
            }

            tKey.Text      = Presharedkey;
            tUsername.Text = Username;
            tPassword.Text = Password;

            book.openPhoneBook();

            if (book.contains(Vpnname))
            {
                dialerclass.setEntryName(dialer, Vpnname);
                dialerclass.setPhoneBookPath(dialer);
                dialerclass.setCredentials(dialer, credentials);
                dialerclass.setTimeout(dialer, 1000);
                connectionHandler = dialerclass.Dial(dialer);

                connection = RasConnection.GetActiveConnectionByHandle(connectionHandler);                                    //vult de variabel 'connection' met een RasConnection als er een connectie actief is.
                dialerclass.connectionState(tray, notify, watcher, connectionHandler, this);                                  //Dit zorgt er voor dat er een balonmelding komt als de verbinding is verbroken met de server.

                if (dialerclass.checkIfConnectionExist(connection) == true)                                                   //Als er een connectie is worden de buttons, labels en textboxes geënabled/gedisabeld.
                {
                    lStatusstate.Text      = "Active";
                    lStatusstate.BackColor = System.Drawing.Color.Green;
                    bConnect.Enabled       = false;
                    bDisconnect.Enabled    = true;
                    bReset.Enabled         = false;
                    tKey.Enabled           = false;
                    tUsername.Enabled      = false;
                    tPassword.Enabled      = false;
                    connectItem.Enabled    = false;
                    disconnectItem.Enabled = true;
                    exitItem.Enabled       = false;
                }
                else                                                                                                           //Zo niet dan gebeurt het tegenovergestelde met de buttons, labels en tekxtboxes.
                {
                    lStatusstate.Text      = "Not active";
                    lStatusstate.BackColor = System.Drawing.Color.Red;
                    bConnect.Enabled       = true;
                    bDisconnect.Enabled    = false;
                    bReset.Enabled         = true;
                    tKey.Enabled           = true;
                    tUsername.Enabled      = true;
                    tPassword.Enabled      = true;
                    connectItem.Enabled    = true;
                    disconnectItem.Enabled = false;
                    exitItem.Enabled       = true;
                }
            }
            else
            {
                bConnect.Enabled    = true;
                bDisconnect.Enabled = false;
            }
        }
Esempio n. 6
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. 7
0
        public bool Dial()
        {
            this.HangUp();
            //this.CreateADSL();

            this.isDialing = true;
            // This button will be used to dial the connection.
            this.rasDialer.EntryName     = this.ADSLItem.EntryName;
            this.rasDialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            //MS 5 Mins
            this.rasDialer.Timeout = this.Timeout;

            try
            {
                // Set the credentials the dialer should use.
                this.rasDialer.Credentials = new NetworkCredential(this.ADSLItem.User, this.ADSLItem.Password);
                this.rasDialer.AllowUseStoredCredentials = true;
                //this.rasDialer.
                // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                // Begin dialing the connection; this will raise events from the dialer instance.
                RasHandle rasHandle = this.rasDialer.Dial();
                bool      b         = !rasHandle.IsInvalid;
                return(b);
            }
            catch (Exception ex)
            {
                LogManager.ErrorWithCallback(string.Format("-> ADSL拨号异常:{0}", ex.ToString()));
                this.isDialing = false;
            }
            return(false);
        }
Esempio n. 8
0
        /// <summary>
        /// Occurs when the user clicks the Dial button.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param>
        private void DialButton_Click(object sender, EventArgs e)
        {
            this.StatusTextBox.Clear();

            // This button will be used to dial the connection.
            this.Dialer.EntryName = EntryName;
            this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

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

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                // Begin dialing the connection; this will raise events from the dialer instance.
                this.handle = this.Dialer.DialAsync();

                // Enable the disconnect button for use later.
                this.DisconnectButton.Enabled = true;
            }
            catch (Exception ex)
            {
                this.StatusTextBox.AppendText(ex.ToString());
            }
        }
Esempio n. 9
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. 10
0
        /// <summary>
        /// ADSL链接
        /// </summary>
        /// <param name="strConnName">连接名称</param>
        public bool Connect()
        {
            try
            {
                // CreateOrUpdatePPPOE(strConnName);
                RasDialer dialer = new RasDialer();
                dialer.EntryName   = ConstParameter.EntryName;
                dialer.PhoneNumber = " ";
                dialer.AllowUseStoredCredentials = true;
                dialer.PhoneBookPath             = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                dialer.Credentials = new NetworkCredential(
                    CommonParameter.ConfigParam.adsl_info.username,
                    CommonParameter.ConfigParam.adsl_info.password);
                dialer.Timeout = 1000;
                RasHandle myras = dialer.Dial();
                if (!myras.IsInvalid)
                {
                    CommonFunction.WriteLogInFile("RasDialer Success! ", LogType.RunLog);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                CommonFunction.WriteLogInFile("RasDialer error!  error is :" + ex.ToString(), LogType.RunLog);
            }

            return(false);
        }
Esempio n. 11
0
 public void Dial(string ip, string user, string pwd)
 {
     Log.debug(TAG, "Dial ip:" + ip + ", user:" + user);
     CreateOrUpdateVPNEntry(ip);
     dialer.Credentials = new NetworkCredential(user, pwd);
     handle             = dialer.Dial();
 }
Esempio n. 12
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. 13
0
        void Dial()
        {
            this.Dialer.EntryName     = EntryName;
            this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            try
            {
                if (this.Dialer.IsBusy)
                {
                    return;
                }
                // Set the credentials the dialer should use.
                this.Dialer.Credentials = new NetworkCredential("14ab1", "735435");

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                // Begin dialing the connection; this will raise events from the dialer instance.
                this.handle = this.Dialer.Dial();
            }
            catch (Exception ex)
            {
                LogUtil.Write(ex.ToString());

                if (ex.Message.Contains("已经拨了这个连接"))
                {
                    System.Diagnostics.Process.Start(AppDomain.CurrentDomain.BaseDirectory + "系统重启.bat");
                }
            }
        }
Esempio n. 14
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();
            }
        }
        // Token: 0x06000096 RID: 150 RVA: 0x000060EC File Offset: 0x000042EC
        public RasHandle ConnectVPNbyPriority(RasDialer myDialer, RasPhoneBook myPB, string server, string sVPNPrefix, string sLogin, string sPass, string sPath)
        {
            int       windowsVersion = this.GetWindowsVersion();
            RasHandle result         = null;

            if (windowsVersion == this.VER_XP || windowsVersion == this.VER_VISTA)
            {
                myPB = this.SetPhoneBookPPTP(server, myPB, sVPNPrefix);
            }
            else if (windowsVersion == this.VER_W7 || windowsVersion == this.VER_W8)
            {
                myPB = this.SetPhoneBookPPTP(server, myPB, sVPNPrefix);
            }
            myDialer.EntryName                 = sVPNPrefix;
            myDialer.PhoneBookPath             = sPath;
            myDialer.AllowUseStoredCredentials = true;
            try
            {
                myDialer.Credentials = new NetworkCredential(sLogin, sPass);
                result = myDialer.DialAsync();
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Esempio n. 16
0
        private void f_Vpnconfiger_Load(object sender, EventArgs e)
        {
            book.openPhoneBook();

            if (book.contains(Vpnname))
            {
                dialerclass.setEntryName(dialer, Vpnname);
                dialerclass.setPhoneBookPath(dialer);
                dialerclass.setCredentials(dialer, credentials);
                dialerclass.setTimeout(dialer, 1000);
                connectionHandler = dialerclass.Dial(dialer);

                connection = RasConnection.GetActiveConnectionByHandle(connectionHandler);

                if (dialerclass.checkIfConnectionExist(connection) == true)
                {
                    lStatusstate.Text   = "Connected";
                    bConnect.Enabled    = false;
                    bDisconnect.Enabled = true;
                }
                else
                {
                    lStatusstate.Text   = "Disconnected";
                    bConnect.Enabled    = true;
                    bDisconnect.Enabled = false;
                }
            }
        }
Esempio n. 17
0
 public void Diale(string username, string key, string connectName)
 {
     try
     {
         RasDialer dialer = new RasDialer();
         dialer.EntryName   = connectName;
         dialer.PhoneNumber = " ";
         dialer.AllowUseStoredCredentials = true;
         dialer.PhoneBookPath             = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
         dialer.Credentials = new System.Net.NetworkCredential(username, key);
         dialer.Timeout     = 500;
         RasHandle myras = dialer.Dial();
         while (myras.IsInvalid)
         {
             //lb_status.Content = "拨号失败";
             OnDialeFailure?.Invoke();
         }
         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();
             OnDialeSuccess?.Invoke("获得IP: " + ipaddr.IPAddress.ToString());
             //dial.IsEnabled = false;
             //hangup.IsEnabled = true;
         }
     }
     catch (Exception e)
     {
         //lb_status.Content = "拨号出现异常";
         OnDialeExcep?.Invoke();
     }
 }
Esempio n. 18
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());
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DotRas.StateChangedEventArgs"/> class.
 /// </summary>
 /// <param name="callbackId">The application defined value that was specified during dialing.</param>
 /// <param name="subEntryId">The one-based index for the phone book entry associated with this connection.</param>
 /// <param name="handle">The handle of the connection.</param>
 /// <param name="state">The state the remote access connection is about to enter.</param>
 /// <param name="errorCode">The error code (if any) that occurred.</param>
 /// <param name="errorMessage">The error message of the <paramref name="errorCode"/> that occurred.</param>
 /// <param name="extendedErrorCode">The extended error code (if any) that occurred.</param>
 internal StateChangedEventArgs(IntPtr callbackId, int subEntryId, RasHandle handle, RasConnectionState state, int errorCode, string errorMessage, int extendedErrorCode)
 {
     this.CallbackId = callbackId;
     this.SubEntryId = subEntryId;
     this.Handle = handle;
     this.State = state;
     this.ErrorCode = errorCode;
     this.ErrorMessage = errorMessage;
     this.ExtendedErrorCode = extendedErrorCode;
 }
Esempio n. 20
0
 public void Dispose()
 {
     serverIP     = null;
     adapterName  = null;
     userName     = null;
     passWord     = null;
     vpnProtocol  = null;
     preSharedKey = null;
     dialer       = null;
     handle       = null;
 }
Esempio n. 21
0
        public void HandleTest()
        {
            RasHandle expected = new RasHandle(new IntPtr(1), false);

            RasConnection target = new RasConnection();
            target.Handle = expected;

            RasHandle actual = target.Handle;

            Assert.AreEqual(expected, actual);
        }
Esempio n. 22
0
        public void HandleTest()
        {
            var expected = new RasHandle(new IntPtr(1), false);

            var target = new RasConnection();

            target.Handle = expected;

            var actual = target.Handle;

            Assert.AreEqual(expected, actual);
        }
Esempio n. 23
0
        private void login()
        {
            try
            {
                string username = tb_username.Text.Replace("\\r", "\r").Replace("\\n", "\n");
                username = "******" + username;
                string    password = pb_password.Password.ToString();
                RasDialer dialer   = new RasDialer();
                dialer.EntryName   = "gdut drcom";
                dialer.PhoneNumber = " ";
                dialer.AllowUseStoredCredentials = true;
                dialer.PhoneBookPath             = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
                dialer.Credentials = new System.Net.NetworkCredential(username, password);
                dialer.Timeout     = 500;
                RasHandle myras = null;
                if (username.Length != 0 && password.Length != 0)
                {
                    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();

                    ProcessStartInfo startinfo = new ProcessStartInfo();
                    //startinfo.RedirectStandardOutput = true;
                    //startinfo.RedirectStandardError = true;
                    startinfo.FileName        = ".\\gdut-drcom.exe";
                    startinfo.Arguments       = "-c gdut-drcom.conf";
                    startinfo.UseShellExecute = false;
                    startinfo.CreateNoWindow  = true;

                    process.StartInfo = startinfo;
                    process.Start();

                    dial.IsEnabled = false;
                    remember_checkbox.IsEnabled = false;
                    autolog_checkbox.IsEnabled  = false;
                    hangup.IsEnabled            = true;
                }
            }
            catch (Exception)
            {
                lb_status.Content = "拨号出现异常";
            }
        }
        // Token: 0x06000091 RID: 145 RVA: 0x00005DAC File Offset: 0x00003FAC
        public RasHandle ConnectVPN(RasDialer myDialer, RasPhoneBook myPB, ServerRouting lstServerRouting, string sVPNPrefix, string sLogin, string sPass, string sPath, string sSharedKey)
        {
            RasHandle result = null;
            bool      flag   = false;
            string    text;
            string    text2;
            string    server;

            if (lstServerRouting.SetNextAutoTry(out text, out text2, out server))
            {
                string text3 = text2;
                if (text3 != null)
                {
                    if (!(text3 == "PPTP"))
                    {
                        if (!(text3 == "L2TP"))
                        {
                            if (text3 == "SSTP")
                            {
                                myPB = this.SetPhoneBookSSTP(server, myPB, sVPNPrefix);
                                flag = true;
                            }
                        }
                        else
                        {
                            myPB = this.SetPhoneBookL2TP(text, myPB, sVPNPrefix, sSharedKey);
                            flag = true;
                        }
                    }
                    else
                    {
                        myPB = this.SetPhoneBookPPTP(text, myPB, sVPNPrefix);
                        flag = true;
                    }
                }
                if (flag && text.Length > 0)
                {
                    myDialer.EntryName                 = sVPNPrefix;
                    myDialer.PhoneBookPath             = sPath;
                    myDialer.AllowUseStoredCredentials = true;
                    try
                    {
                        myDialer.Credentials = new NetworkCredential(sLogin, sPass);
                        result = myDialer.DialAsync();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return(result);
        }
Esempio n. 25
0
 public void dialVPN()
 {
     try
     {
         RasDialer dialer = new RasDialer();
         dialer.EntryName     = "UCLan Network";
         dialer.PhoneBookPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Network\Connections\Pbk\rasphone.pbk");
         RasHandle connection = dialer.Dial();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Esempio n. 26
0
        public void GetSubEntryHandleTest()
        {
            var expected = new RasHandle(new IntPtr(1), true);

            var mock = new Mock <IRasHelper>();

            RasHelper.Instance = mock.Object;

            mock.Setup(o => o.GetSubEntryHandle(It.IsAny <RasHandle>(), It.IsAny <int>())).Returns(expected);

            var target = new RasConnection();
            var actual = target.GetSubEntryHandle(1);

            Assert.AreSame(expected, actual);
        }
Esempio n. 27
0
 private void DialVpn(string serverDesc)
 {
     OnClientMessageEvent("正在连接" + serverDesc + "...");
     this.Dialer.EntryName     = serverDesc;
     this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
     try
     {
         this.Dialer.Credentials = new NetworkCredential(this.userName, this.passWord);
         this.connectionHandle   = this.Dialer.DialAsync();
     }
     catch (Exception ex)
     {
         OnClientExceptionEvent(ex);
         return;
     }
 }
Esempio n. 28
0
        /// <summary>
        /// Connect
        /// </summary>
        /// <param name="connectName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void Connect(string connectName, string userName, string password)
        {
            //关闭现有连接
            IReadOnlyCollection <RasConnection> conns = RasConnection.GetActiveConnections();

            if (conns.Count != 0)
            {
                foreach (var conn in conns)
                {
                    conn.HangUp();
                }
            }

            RasPhoneBook rasPhoneBook = new RasPhoneBook();
            string       path         = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            rasPhoneBook.Open(path);


            //创建一个新的PPPOE连接
            IReadOnlyCollection <RasDevice> rasDevices = RasDevice.GetDevices();
            RasDevice device = rasDevices.First(d => d.DeviceType == RasDeviceType.PPPoE);
            var       entry  = RasEntry.CreateBroadbandEntry(connectName, device);

            entry.PhoneNumber = userName;
            //如果不存在该名字的用户名和密码的连接,则Add 存在则更新
            if (!rasPhoneBook.Entries.Contains(connectName))
            {
                rasPhoneBook.Entries.Add(entry);
            }
            else
            {
                rasPhoneBook.Entries[connectName].Update();
            }

            RasDialer dialer = new RasDialer
            {
                EntryName   = connectName,
                PhoneNumber = userName,
                AllowUseStoredCredentials = true,
                PhoneBookPath             = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers),
                Credentials = new NetworkCredential(userName, password),
                Timeout     = 1000 * 10
            };

            RasHandle rasHandle = dialer.Dial();
        }
Esempio n. 29
0
        /// <summary>
        /// Protected implementation of Dispose pattern.
        /// </summary>
        /// <param name="disposing">
        ///  Indicates whether the method call comes from a Dispose method (its value is true)
        ///  or from a finalizer (its value is false).
        /// </param>
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_dialer != null)
                {
                    _dialer.Dispose();
                    _dialer = null;
                }

                if (_handle != null)
                {
                    _handle.Dispose();
                    _handle = null;
                }
            }
        }
Esempio n. 30
0
 private void Disconnect()
 {
     if (_dialer.IsBusy)
     {
         _dialer.DialAsyncCancel();
     }
     else if (_handle != null)
     {
         var activeConnectionByHandle = RasConnection.GetActiveConnections().FirstOrDefault(c => c.Handle == _handle);
         if (activeConnectionByHandle != null)
         {
             activeConnectionByHandle.HangUp();
         }
         _handle     = null;
         IsConnected = false;
     }
 }
Esempio n. 31
0
        private void Connect()
        {
            var rasPhoneBook = new RasPhoneBook();

            rasPhoneBook.Open(PhoneBookPath);
            if (!rasPhoneBook.Entries.Contains(VpnName))
            {
                var vpnDevice = RasDevice.GetDevices().FirstOrDefault(d => d.DeviceType == RasDeviceType.Vpn && d.Name.ToLower(CultureInfo.CurrentCulture).Contains("(PPTP)".ToLower(CultureInfo.CurrentCulture)));
                var rasEntry  = RasEntry.CreateVpnEntry(VpnName, VpnServer, RasVpnStrategy.PptpOnly, vpnDevice, false);
                rasEntry.Options.ShowDialingProgress = false;
                rasPhoneBook.Entries.Add(rasEntry);
            }
            _dialer.EntryName     = VpnName;
            _dialer.PhoneBookPath = PhoneBookPath;
            _dialer.Credentials   = _credentials;
            _handle = _dialer.DialAsync();
        }
Esempio n. 32
0
        public void bDisconnect_Click(object sender, EventArgs e)
        {
            dialerclass.setEntryName(dialer, Vpnname);
            dialerclass.setPhoneBookPath(dialer);
            dialerclass.setCredentials(dialer, credentials);
            dialerclass.setTimeout(dialer, 1000);

            connectionHandler = dialerclass.Dial(dialer);

            connection = RasConnection.GetActiveConnectionByHandle(connectionHandler);

            if (dialerclass.hangup(dialer, connection))
            {
                lStatusstate.Text   = "Disconnected";
                bConnect.Enabled    = true;
                bDisconnect.Enabled = false;
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Attempts to establish an internet connection with RAS.
        /// </summary>
        private void TryRasConnection()
        {
            var selectedProfile = _view.SelectedProfile;

            if (selectedProfile.Equals(string.Empty))
            {
                _view.UpdateToolStripStatus("Profile not selected");
                return;
            }

            /*
             * Config the dialer
             * EntryName is the name of the dial-up conn on Windows.
             * PhoneBookPath is the path to Windows phone book, where the conns are stored.
             * Both needed.
             * */
            _dialer.EntryName     = selectedProfile;
            _dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

            try
            {
                _handle = _dialer.DialAsync();

                Task.Run(() =>
                {
                    while (_dialer.IsBusy)
                    {
                        // The button will show 'cancel' while the conn is been established
                        _view.UpdateUIWhenDialing();
                        Task.Delay(1000);
                    }
                });

                // Save selected modem and profile on settings
                Settings.Default.LastUsedModem  = _view.SelectedModem;
                Settings.Default.DefaultProfile = selectedProfile;
                Settings.Default.Save();
            }
            catch (Exception ex)
            {
                _view.UpdateToolStripStatus(ex.Message);
            }
        }
Esempio n. 34
0
        static private void OpenConnectLocal(BaseProxyServer ps, bool async)
        {
            CreateDialerAndBeginWatch();//if not created yet
            //http://www.dotnetobject.com/Thread-Connecting-VPN-using-C

            dialer.EntryName     = ps.GetConnectionName();
            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
            try
            {
                try
                {
                    RasConnection conn = RasConnection.GetActiveConnectionByName(ps.GetConnectionName(), dialer.PhoneBookPath);
                    if (conn != null)
                    {
                        conn.HangUp();
                    }
                }
                catch (Exception)
                {
                    //no connection present
                }
                if (!string.IsNullOrEmpty(ps.GetProxyProvider().VPNLogin))
                {
                    System.Net.NetworkCredential cred = new System.Net.NetworkCredential(ps.GetProxyProvider().VPNLogin, ps.GetProxyProvider().VPNPassword);
                    dialer.Credentials = cred;
                }
                //dialer.Dial();//alt DialAsync()
                if (async)
                {
                    handle = dialer.DialAsync();
                }
                else
                {
                    handle = dialer.Dial();
                    NetConnUtils.CurrentProxyServer = ps;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 35
0
        public static void ClassInitialize(TestContext context)
        {
            entryName     = Guid.NewGuid().ToString();
            phonebookPath = Path.GetTempFileName();

            RasPhoneBook pbk = RasPhoneBook.Open(phonebookPath);

            entryId = TestUtilities.CreateValidVpnEntry(pbk, entryName);

            using (RasDialer dialer = new RasDialer())
            {
                dialer.EntryName     = entryName;
                dialer.PhoneBookPath = phonebookPath;
                dialer.Credentials   = TestUtilities.GetValidCredentials();

                handle = dialer.Dial();
            }

            target = RasConnection.GetActiveConnections().Where(o => o.EntryId == entryId).FirstOrDefault();
        }
Esempio n. 36
0
        public void Connect()
        {
            try
            {
                RD.EntryName     = _VpnName;
                RD.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            }
            catch (Exception ex)
            {
            }

            try
            {
                RD.Credentials = new NetworkCredential(_UserName, _PassWord);
                Handle         = RD.DialAsync();
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 37
0
        public static void ClassInitialize(TestContext context)
        {
            entryName = Guid.NewGuid().ToString();
            phonebookPath = Path.GetTempFileName();

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

            entryId = TestUtilities.CreateValidVpnEntry(pbk, entryName);

            using (RasDialer dialer = new RasDialer())
            {
                dialer.EntryName = entryName;
                dialer.PhoneBookPath = phonebookPath;
                dialer.Credentials = TestUtilities.GetValidCredentials();

                handle = dialer.Dial();
            }

            target = RasConnection.GetActiveConnectionById(entryId);
        }
Esempio n. 38
0
        /// <summary>
        /// Notifies the asynchronous operation in progress the operation has completed.
        /// </summary>
        /// <param name="error">Any error that occurred during the asynchronous operation.</param>
        /// <param name="cancelled"><b>true</b> if the asynchronous operation was cancelled, otherwise <b>false</b>.</param>
        /// <param name="timedOut"><b>true</b> if the operation timed out, otherwise <b>false</b>.</param>
        /// <param name="connected"><b>true</b> if the connection attempt successfully connected, otherwise <b>false</b>.</param>
        private void PostCompleted(Exception error, bool cancelled, bool timedOut, bool connected)
        {
            lock (this.syncRoot)
            {
                if (connected)
                {
                    // The client has connected successfully, attempt to update the credentials.
                    this.SaveCredentialsToPhoneBook();
                }

                this.ReleaseEapIdentity();
                this.IsBusy = false;

                if (this.asyncOp != null)
                {
                    this.asyncOp.PostOperationCompleted(this.dialCompletedCallback, new DME.Dialer.DialCompletedEventArgs(this.handle, error, cancelled, timedOut, connected, null));

                    this.asyncOp = null;
                    this.handle = null;
                    this.timer = null;
                }
            }
        }
Esempio n. 39
0
        private bool RasDialCallback(IntPtr callbackId, int subEntryId, IntPtr dangerousHandle, int message, RasConnectionState state, int errorCode, int extendedErrorCode)
        {
            bool retval = true;

            lock (this.syncRoot)
            {
                RasHandle connectionHandle = null;

                try
                {
                    connectionHandle = new RasHandle(dangerousHandle, subEntryId > 1);

                    if (!this.IsBusy)
                    {
                        // The connection is no longer being dialed, stop receiving notifications for this connection attempt.
                        retval = false;
                    }
                    else
                    {
                        string errorMessage = null;
                        if (errorCode != NativeMethods.SUCCESS)
                        {
                            errorMessage = RasHelper.Instance.GetRasErrorString(errorCode);
                        }

                        DME.Dialer.StateChangedEventArgs e = new DME.Dialer.StateChangedEventArgs(callbackId, subEntryId, connectionHandle, state, errorCode, errorMessage, extendedErrorCode);
                        this.OnStateChanged(e);

                        if (errorCode != NativeMethods.SUCCESS)
                        {
                            this.Abort();
                            this.PostCompleted(new RasDialException(errorCode, extendedErrorCode), false, false, false);

                            retval = false;
                        }
                        else if (state == RasConnectionState.Connected)
                        {
                            this.PostCompleted(null, false, false, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.OnError(new System.IO.ErrorEventArgs(ex));
                }
                finally
                {
                    if (connectionHandle != null)
                    {
                        connectionHandle.Dispose();
                    }
                }
             }

            return retval;
        }
Esempio n. 40
0
        /// <summary>
        /// Performs the dialing operation.
        /// </summary>
        /// <param name="asynchronous"><b>true</b> if the dialing operation should be asynchronous, otherwise <b>false</b>.</param>
        /// <returns>The handle of the connection.</returns>
        /// <exception cref="System.InvalidOperationException">A phone number or an entry name with phone book path is required to dial.</exception>
        private RasHandle InternalDial(bool asynchronous)
        {
            if (string.IsNullOrEmpty(this.PhoneNumber) && (string.IsNullOrEmpty(this.EntryName) || string.IsNullOrEmpty(this.PhoneBookPath)))
            {
                ThrowHelper.ThrowInvalidOperationException(Resources.Exception_PhoneNumberOrEntryNameRequired);
            }

            lock (this.syncRoot)
            {
                // NOTE: The synchronization object MUST be locked prior to testing of the component is already busy.
                // WARNING! Ensure no exceptions are thrown because existing dial attempts are already in progress. Doing so leaves the
                // connection open and cannot be closed if the application is terminated.
                if (!this.IsBusy)
                {
                    this.IsBusy = true;

                    try
                    {
                        NativeMethods.RASDIALPARAMS parameters = this.BuildDialParams();
                        NativeMethods.RASDIALEXTENSIONS extensions = this.BuildDialExtensions();

                        if (!string.IsNullOrEmpty(this.EntryName))
                        {
                            byte[] data = null;

                            if (this.eapUserData != null)
                            {
                                data = this.eapUserData;
                            }
                            else
                            {
                                data = RasHelper.Instance.GetEapUserData(IntPtr.Zero, this.PhoneBookPath, this.EntryName);
                            }

                            if (data != null)
                            {
                                this.eapDataAddress = Marshal.AllocHGlobal(data.Length);
                                Marshal.Copy(data, 0, this.eapDataAddress, data.Length);

                                extensions.eapInfo.eapData = this.eapDataAddress;
                                extensions.eapInfo.sizeOfEapData = data.Length;
                            }
                        }

                        NativeMethods.RasDialFunc2 callback = null;
                        if (asynchronous)
                        {
                            callback = this.rasDialCallback;

                            this.asyncOp = AsyncOperationManager.CreateOperation(null);

                            if (this.timer != null)
                            {
                                // Dispose of any existing timer if the component is being reused.
                                this.timer.Dispose();
                                this.timer = null;
                            }

                            if (this.Timeout != System.Threading.Timeout.Infinite)
                            {
                                // A timeout has been requested, create the timer used to handle the connection timeout.
                                this.timer = new Timer(this.timeoutCallback, null, this.Timeout, System.Threading.Timeout.Infinite);
                            }
                        }

                        this.handle = RasHelper.Instance.Dial(this.PhoneBookPath, parameters, extensions, callback, this.GetRasEapOptions());

                        if (!asynchronous)
                        {
                            this.SaveCredentialsToPhoneBook();
                            this.ReleaseEapIdentity();

                            // The synchronous dialing operation has completed, reset the dialing flag so the component can be reused.
                            this.IsBusy = false;
                        }
                    }
                    catch (Exception)
                    {
                        // An exception was thrown when the component was attempting to dial a connection. Release the EAP identity and reset the dialing flag so the component can be reused.
                        this.ReleaseEapIdentity();
                        this.IsBusy = false;

                        throw;
                    }
                }
            }

            return this.handle;
        }
Esempio n. 41
0
        public void GetActiveConnectionByHandleNotFoundTest()
        {
            RasHandle handle = new RasHandle(new IntPtr(1), false);

            RasConnection expected = null;

            ReadOnlyCollection<RasConnection> connections = new ReadOnlyCollection<RasConnection>(
                new RasConnection[] { new RasConnection() { Handle = new RasHandle(new IntPtr(2), false) } });

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

            mock.Setup(o => o.GetActiveConnections()).Returns(connections);

            RasConnection actual = RasConnection.GetActiveConnectionByHandle(handle);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 42
0
        /// <summary>
        /// Retrieves accumulated statistics for the specified link in a RAS multilink connection.
        /// </summary>
        /// <param name="handle">The handle to the connection.</param>
        /// <param name="subEntryId">The one-based index that corresponds to the link for which to retrieve statistics.</param>
        /// <returns>A <see cref="DotRas.RasLinkStatistics"/> structure containing connection statistics.</returns>
        /// <exception cref="System.ArgumentException"><paramref name="subEntryId"/> must be greater than zero.</exception>
        /// <exception cref="DotRas.InvalidHandleException"><paramref name="handle"/> is a null reference (<b>Nothing</b> in Visual Basic) or an invalid handle.</exception>
        public RasLinkStatistics GetLinkStatistics(RasHandle handle, int subEntryId)
        {
            if (Utilities.IsHandleInvalidOrClosed(handle))
            {
                ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
            }

            if (subEntryId <= 0)
            {
                ThrowHelper.ThrowArgumentException("subEntryId", Resources.Argument_ValueCannotBeLessThanOrEqualToZero);
            }

            RasLinkStatistics retval = null;

            int size = Marshal.SizeOf(typeof(NativeMethods.RAS_STATS));

            NativeMethods.RAS_STATS stats = new NativeMethods.RAS_STATS();
            stats.size = size;

            IntPtr lpRasLinkStatistics = IntPtr.Zero;
            try
            {
                lpRasLinkStatistics = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(stats, lpRasLinkStatistics, true);

                int ret = SafeNativeMethods.Instance.GetLinkStatistics(handle, subEntryId, lpRasLinkStatistics);
                if (ret == NativeMethods.SUCCESS)
                {
                    stats = Utilities.PtrToStructure<NativeMethods.RAS_STATS>(lpRasLinkStatistics);

                    retval = new RasLinkStatistics(
                        stats.bytesTransmitted,
                        stats.bytesReceived,
                        stats.framesTransmitted,
                        stats.framesReceived,
                        stats.crcError,
                        stats.timeoutError,
                        stats.alignmentError,
                        stats.hardwareOverrunError,
                        stats.framingError,
                        stats.bufferOverrunError,
                        stats.compressionRatioIn,
                        stats.compressionRatioOut,
                        stats.linkSpeed,
                        TimeSpan.FromMilliseconds(stats.connectionDuration));
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (lpRasLinkStatistics != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpRasLinkStatistics);
                }
            }

            return retval;
        }
Esempio n. 43
0
        /// <summary>
        /// Retrieves the connection status for the handle specified.
        /// </summary>
        /// <param name="handle">The remote access connection handle to retrieve.</param>
        /// <returns>A <see cref="DotRas.RasConnectionStatus"/> object containing connection status information.</returns>
        /// <exception cref="DotRas.InvalidHandleException"><paramref name="handle"/> is not a valid handle.</exception>
        public RasConnectionStatus GetConnectionStatus(RasHandle handle)
        {
            RasConnectionStatus retval = null;

            IntPtr lpRasConnStatus = IntPtr.Zero;
            try
            {
                int size = Marshal.SizeOf(typeof(NativeMethods.RASCONNSTATUS));

                NativeMethods.RASCONNSTATUS status = new NativeMethods.RASCONNSTATUS();
                status.size = size;

                lpRasConnStatus = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(status, lpRasConnStatus, true);

                int ret = SafeNativeMethods.Instance.GetConnectStatus(handle, lpRasConnStatus);
                if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else if (ret == NativeMethods.SUCCESS)
                {
                    status = Utilities.PtrToStructure<NativeMethods.RASCONNSTATUS>(lpRasConnStatus);

                    string errorMessage = null;
                    if (status.errorCode != NativeMethods.SUCCESS)
                    {
                        errorMessage = RasHelper.Instance.GetRasErrorString(status.errorCode);
                    }

                    retval = new RasConnectionStatus();
                    retval.ConnectionState = status.connectionState;
                    retval.ErrorCode = status.errorCode;
                    retval.ErrorMessage = errorMessage;
                    retval.PhoneNumber = status.phoneNumber;

                    if (!string.IsNullOrEmpty(status.deviceName) && !string.IsNullOrEmpty(status.deviceType))
                    {
                        retval.Device = RasDevice.Create(status.deviceName, status.deviceType);
                    }

#if (WIN7 || WIN8)
                    IPAddressConverter converter = new IPAddressConverter();

                    retval.LocalEndPoint = (IPAddress)converter.ConvertFrom(status.localEndPoint);
                    retval.RemoteEndPoint = (IPAddress)converter.ConvertFrom(status.remoteEndPoint);
                    retval.ConnectionSubState = status.connectionSubState;
#endif
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (lpRasConnStatus != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpRasConnStatus);
                }
            }

            return retval;
        }
Esempio n. 44
0
        /// <summary>
        /// Clears any accumulated statistics for the specified remote access connection.
        /// </summary>
        /// <param name="handle">The handle to the connection.</param>
        /// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns>
        public bool ClearConnectionStatistics(RasHandle handle)
        {
            bool retval = false;

            try
            {
                int ret = SafeNativeMethods.Instance.ClearConnectionStatistics(handle);
                if (ret == NativeMethods.SUCCESS)
                {
                    retval = true;
                }
                else if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }

            return retval;
        }
Esempio n. 45
0
        /// <summary>
        /// Updates the tunnel endpoints of an Internet Key Exchange (IKEv2) connection.
        /// </summary>
        /// <param name="handle">The handle to the connection.</param>
        /// <param name="updateData">Pointer to a <see cref="NativeMethods.RASUPDATECONN"/> structure that contains the new tunnel endpoints for the connection.</param>
        /// <returns>If the function succeeds, the return value is zero.</returns>
        public int UpdateConnection(RasHandle handle, IntPtr updateData)
        {
            PInvokeCallTraceEvent evt = new PInvokeCallTraceEvent(NativeMethods.RasApi32Dll, "RasUpdateConnection");
            evt.Data.Add("handle", handle);
            evt.Data.Add("updateData", updateData);

            int result = 0;

            try
            {
                result = UnsafeNativeMethods.RasUpdateConnection(handle, updateData);
                evt.ResultCode = result;
            }
            finally
            {
                DiagnosticTrace.Default.TraceEvent(TraceEventType.Verbose, evt);
            }

            return result;
        }
Esempio n. 46
0
        public object GetProjectionInfo(RasHandle handle, NativeMethods.RASPROJECTION projection)
        {
            if (Utilities.IsHandleInvalidOrClosed(handle))
            {
                ThrowHelper.ThrowArgumentException("handle", Resources.Argument_InvalidHandle);
            }

            int size = 0;

            object retval = null;
            object structure = null;

            switch (projection)
            {
                case NativeMethods.RASPROJECTION.Amb:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASAMB));

                    NativeMethods.RASAMB amb = new NativeMethods.RASAMB();
                    amb.size = size;

                    structure = amb;
                    break;

                case NativeMethods.RASPROJECTION.Ccp:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPCCP));

                    NativeMethods.RASPPPCCP ccp = new NativeMethods.RASPPPCCP();
                    ccp.size = size;

                    structure = ccp;
                    break;

                case NativeMethods.RASPROJECTION.IP:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIP));

                    NativeMethods.RASPPPIP ip = new NativeMethods.RASPPPIP();
                    ip.size = size;

                    structure = ip;
                    break;

                case NativeMethods.RASPROJECTION.Ipx:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIPX));

                    NativeMethods.RASPPPIPX ipx = new NativeMethods.RASPPPIPX();
                    ipx.size = size;

                    structure = ipx;
                    break;

                case NativeMethods.RASPROJECTION.Lcp:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPLCP));

                    NativeMethods.RASPPPLCP lcp = new NativeMethods.RASPPPLCP();
                    lcp.size = size;

                    structure = lcp;
                    break;

                case NativeMethods.RASPROJECTION.Nbf:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPNBF));

                    NativeMethods.RASPPPNBF nbf = new NativeMethods.RASPPPNBF();
                    nbf.size = size;

                    structure = nbf;
                    break;

#if (WIN2K8 || WIN7 || WIN8)

                case NativeMethods.RASPROJECTION.IPv6:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASPPPIPV6));

                    NativeMethods.RASPPPIPV6 ipv6 = new NativeMethods.RASPPPIPV6();
                    ipv6.size = size;

                    structure = ipv6;
                    break;

#endif
                case NativeMethods.RASPROJECTION.Slip:
                    size = Marshal.SizeOf(typeof(NativeMethods.RASSLIP));

                    NativeMethods.RASSLIP slip = new NativeMethods.RASSLIP();
                    slip.size = size;

                    structure = slip;
                    break;
            }

            IntPtr lpCb = new IntPtr(size);

            IntPtr lpProjection = IntPtr.Zero;
            try
            {
                lpProjection = Marshal.AllocHGlobal(lpCb);
                Marshal.StructureToPtr(structure, lpProjection, true);

                int ret = SafeNativeMethods.Instance.GetProjectionInfo(handle, projection, lpProjection, ref lpCb);
                if (ret == NativeMethods.SUCCESS)
                {
                    IPAddressConverter converter = new IPAddressConverter();

                    switch (projection)
                    {
                        case NativeMethods.RASPROJECTION.Amb:
                            NativeMethods.RASAMB amb = Utilities.PtrToStructure<NativeMethods.RASAMB>(lpProjection);

                            retval = new RasAmbInfo(
                                amb.errorCode,
                                amb.netBiosError,
                                amb.lana);

                            break;

                        case NativeMethods.RASPROJECTION.Ccp:
                            NativeMethods.RASPPPCCP ccp = Utilities.PtrToStructure<NativeMethods.RASPPPCCP>(lpProjection);

                            retval = new RasCcpInfo(
                                ccp.errorCode,
                                ccp.compressionAlgorithm,
                                new RasCompressionOptions(ccp.options),
                                ccp.serverCompressionAlgorithm,
                                new RasCompressionOptions(ccp.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.IP:
                            NativeMethods.RASPPPIP ip = Utilities.PtrToStructure<NativeMethods.RASPPPIP>(lpProjection);

                            retval = new RasIPInfo(
                                ip.errorCode,
                                (IPAddress)converter.ConvertFrom(ip.ipAddress),
                                (IPAddress)converter.ConvertFrom(ip.serverIPAddress),
                                new RasIPOptions(ip.options),
                                new RasIPOptions(ip.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.Ipx:
                            NativeMethods.RASPPPIPX ipx = Utilities.PtrToStructure<NativeMethods.RASPPPIPX>(lpProjection);

                            retval = new RasIpxInfo(
                                ipx.errorCode,
                                (IPAddress)converter.ConvertFrom(ipx.ipxAddress));

                            break;

                        case NativeMethods.RASPROJECTION.Lcp:
                            NativeMethods.RASPPPLCP lcp = Utilities.PtrToStructure<NativeMethods.RASPPPLCP>(lpProjection);

                            retval = new RasLcpInfo(
                                lcp.bundled,
                                lcp.errorCode,
                                lcp.authenticationProtocol,
                                lcp.authenticationData,
                                lcp.eapTypeId,
                                lcp.serverAuthenticationProtocol,
                                lcp.serverAuthenticationData,
                                lcp.serverEapTypeId,
                                lcp.multilink,
                                lcp.terminateReason,
                                lcp.serverTerminateReason,
                                lcp.replyMessage,
                                new RasLcpOptions(lcp.options),
                                new RasLcpOptions(lcp.serverOptions));

                            break;

                        case NativeMethods.RASPROJECTION.Nbf:
                            NativeMethods.RASPPPNBF nbf = Utilities.PtrToStructure<NativeMethods.RASPPPNBF>(lpProjection);

                            retval = new RasNbfInfo(
                                nbf.errorCode,
                                nbf.netBiosErrorCode,
                                nbf.netBiosErrorMessage,
                                nbf.workstationName,
                                nbf.lana);

                            break;

                        case NativeMethods.RASPROJECTION.Slip:
                            NativeMethods.RASSLIP slip = Utilities.PtrToStructure<NativeMethods.RASSLIP>(lpProjection);

                            retval = new RasSlipInfo(
                                slip.errorCode,
                                (IPAddress)converter.ConvertFrom(slip.ipAddress));

                            break;

#if (WIN2K8 || WIN7 || WIN8)
                        case NativeMethods.RASPROJECTION.IPv6:
                            NativeMethods.RASPPPIPV6 ipv6 = Utilities.PtrToStructure<NativeMethods.RASPPPIPV6>(lpProjection);

                            retval = new RasIPv6Info(
                                ipv6.errorCode,
                                Utilities.ConvertBytesToInt64(ipv6.localInterfaceIdentifier, 0),
                                Utilities.ConvertBytesToInt64(ipv6.peerInterfaceIdentifier, 0),
                                Utilities.ConvertBytesToInt16(ipv6.localCompressionProtocol, 0),
                                Utilities.ConvertBytesToInt16(ipv6.peerCompressionProtocol, 0));

                            break;
#endif
                    }
                }
                else if (ret != NativeMethods.ERROR_INVALID_PARAMETER && ret != NativeMethods.ERROR_PROTOCOL_NOT_CONFIGURED)
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (lpProjection != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpProjection);
                }
            }

            return retval;
        }
Esempio n. 47
0
        public object GetProjectionInfoEx(RasHandle handle)
        {
            object retval = null;

            int size = Marshal.SizeOf(typeof(NativeMethods.RAS_PROJECTION_INFO));

            IntPtr lpdwSize = new IntPtr(size);
            bool retry = false;

            do
            {
                NativeMethods.RAS_PROJECTION_INFO projectionInfo = new NativeMethods.RAS_PROJECTION_INFO();
                projectionInfo.version = GetCurrentApiVersion();

                IntPtr pRasProjection = IntPtr.Zero;
                try
                {
                    pRasProjection = Marshal.AllocHGlobal(lpdwSize);
                    Marshal.StructureToPtr(projectionInfo, pRasProjection, true);

                    int ret = SafeNativeMethods.Instance.GetProjectionInfoEx(handle, pRasProjection, ref lpdwSize);
                    if (ret == NativeMethods.ERROR_BUFFER_TOO_SMALL)
                    {
                        retry = true;
                    }
                    else if (ret == NativeMethods.SUCCESS)
                    {
                        projectionInfo = Utilities.PtrToStructure<NativeMethods.RAS_PROJECTION_INFO>(pRasProjection);

                        // Use the object located at the end of the structure since the union will cause portability issues on 64-bit platforms.
                        IntPtr pInfo = new IntPtr(pRasProjection.ToInt64() + size);

                        switch (projectionInfo.type)
                        {
                            case NativeMethods.RASPROJECTION_INFO_TYPE.Ppp:
                                NativeMethods.RASPPP_PROJECTION_INFO ppp = Utilities.PtrToStructure<NativeMethods.RASPPP_PROJECTION_INFO>(pInfo);

                                ReadOnlyCollection<byte> interfaceIdentifier = null;
                                if (ppp.interfaceIdentifier != null && ppp.interfaceIdentifier.Length > 0)
                                {
                                    interfaceIdentifier = new ReadOnlyCollection<byte>(new List<byte>(ppp.interfaceIdentifier));
                                }

                                ReadOnlyCollection<byte> serverInterfaceIdentifier = null;
                                if (ppp.serverInterfaceIdentifier != null && ppp.serverInterfaceIdentifier.Length > 0)
                                {
                                    serverInterfaceIdentifier = new ReadOnlyCollection<byte>(new List<byte>(ppp.serverInterfaceIdentifier));
                                }

                                retval = new RasPppInfo(
                                    ppp.ipv4NegotiationError,
                                    new IPAddress(ppp.ipv4Address.addr),
                                    new IPAddress(ppp.ipv4ServerAddress.addr),
                                    ppp.ipv4Options,
                                    ppp.ipv4ServerOptions,
                                    ppp.ipv6NegotiationError,
                                    interfaceIdentifier,
                                    serverInterfaceIdentifier,
                                    ppp.bundled,
                                    ppp.multilink,
                                    ppp.authenticationProtocol,
                                    ppp.authenticationData,
                                    ppp.serverAuthenticationProtocol,
                                    ppp.serverAuthenticationData,
                                    ppp.eapTypeId,
                                    ppp.serverEapTypeId,
                                    new RasLcpOptions(ppp.lcpOptions),
                                    new RasLcpOptions(ppp.serverLcpOptions),
                                    ppp.ccpCompressionAlgorithm,
                                    ppp.serverCcpCompressionAlgorithm,
                                    new RasCompressionOptions(ppp.ccpOptions),
                                    new RasCompressionOptions(ppp.serverCcpOptions));

                                break;

                            case NativeMethods.RASPROJECTION_INFO_TYPE.IkeV2:
                                NativeMethods.RASIKEV2_PROJECTION_INFO ikev2 = Utilities.PtrToStructure<NativeMethods.RASIKEV2_PROJECTION_INFO>(pInfo);

                                RasIkeV2Options ikev2Options = new RasIkeV2Options();
                                Utilities.SetRasIkeV2Options(ikev2Options, ikev2.options);

                                retval = new RasIkeV2Info(
                                    ikev2.ipv4NegotiationError,
                                    new IPAddress(ikev2.ipv4Address.addr),
                                    new IPAddress(ikev2.ipv4ServerAddress.addr),
                                    ikev2.ipv6NegotiationError,
                                    new IPAddress(ikev2.ipv6Address.addr),
                                    new IPAddress(ikev2.ipv6ServerAddress.addr),
                                    ikev2.prefixLength,
                                    ikev2.authenticationProtocol,
                                    ikev2.eapTypeId,
                                    ikev2Options,
                                    ikev2.encryptionMethod,
                                    Utilities.CreateIPv4AddressCollection(ikev2.ipv4ServerAddresses, ikev2.numIPv4ServerAddresses),
                                    Utilities.CreateIPv6AddressCollection(ikev2.ipv6ServerAddresses, ikev2.numIPv6ServerAddresses));

                                break;
                        }

                        retry = false;
                    }
                    else
                    {
                        ThrowHelper.ThrowRasException(ret);
                    }
                }
                catch (EntryPointNotFoundException)
                {
                    ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
                }
                finally
                {
                    if (pRasProjection != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pRasProjection);
                    }
                }
            }
            while (retry);

            return retval;
        }
Esempio n. 48
0
        private void ConnectionStateChanged(object obj, bool timedOut)
        {
            lock (this.lockObject)
            {
                if (this.EnableRaisingEvents)
                {
                    try
                    {
                        // Retrieve the active connections to compare against the last state that was checked.
                        ReadOnlyCollection<RasConnection> connections = RasConnection.GetActiveConnections();
                        RasConnection connection = null;

                        switch (((RasConnectionWatcherStateObject)obj).ChangeType)
                        {
                            case NativeMethods.RASCN.Connection:
                                connection = FindEntry(connections, this._lastState);
                                if (connection != null)
                                {
                                    this.OnConnected(new RasConnectionEventArgs(connection));
                                }

                                this._lastState = connections;

                                break;

                            case NativeMethods.RASCN.Disconnection:
                                // The handle has not been set or it's invalid, the item that has disconnected will need to be
                                // determined.
                                connection = FindEntry(this._lastState, connections);
                                if (connection != null)
                                {
                                    this.OnDisconnected(new RasConnectionEventArgs(connection));
                                }

                                if (this.Handle != null)
                                {
                                    // The handle that was being monitored has been disconnected.
                                    this.Handle = null;
                                }

                                this._lastState = connections;

                                break;

                            case NativeMethods.RASCN.BandwidthAdded:
                                if (this.Handle != null && !this.Handle.IsInvalid)
                                {
                                    this.OnBandwidthAdded(EventArgs.Empty);
                                }

                                break;

                            case NativeMethods.RASCN.BandwidthRemoved:
                                if (this.Handle != null && !this.Handle.IsInvalid)
                                {
                                    this.OnBandwidthRemoved(EventArgs.Empty);
                                }

                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.OnError(new System.IO.ErrorEventArgs(ex));
                    }
                }
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="DotRas.RasDialer"/> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing"><b>true</b> to release both managed and unmanaged resources; <b>false</b> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.IsBusy)
                {
                    // The component is currently dialing a connection, abort the connection attempt.
                    this.Abort();

                    this.handle = null;
                    this.asyncOp = null;
                }

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

                this.ReleaseEapIdentity();
                this.Credentials = null;

                this.dialCompletedCallback = null;
                this.rasDialCallback = null;
                this.timeoutCallback = null;
            }

            base.Dispose(disposing);
        }
Esempio n. 50
0
 /// <summary>
 /// 连接
 /// </summary>
 public void Connection()
 {
     this._Dialer.EntryName = _DialerName;
     this._Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
     this._Dialer.Credentials = new NetworkCredential(_UserName, _Password);
     this._RasHandle = this._Dialer.DialAsync();
     Check my = check;
     IAsyncResult asyncResult = my.BeginInvoke(null, my);
 }
Esempio n. 51
0
        public static RasConnection GetActiveConnectionByHandle(RasHandle handle)
        {
            if (handle == null)
            {
                ThrowHelper.ThrowArgumentNullException("handle");
            }

            RasConnection retval = null;

            foreach (RasConnection connection in GetActiveConnections())
            {
                if (connection.Handle == handle)
                {
                    retval = connection;
                    break;
                }
            }

            return retval;
        }
Esempio n. 52
0
        /// <summary>
        /// Updates the tunnel endpoints of an Internet Key Exchange (IKEv2) connection.
        /// </summary>
        /// <param name="handle">The handle of the connection.</param>
        /// <param name="interfaceIndex">The new interface index of the endpoint.</param>
        /// <param name="localEndPoint">The new local client endpoint of the connection.</param>
        /// <param name="remoteEndPoint">The new remote server endpoint of the connection.</param>
        public void UpdateConnection(RasHandle handle, int interfaceIndex, IPAddress localEndPoint, IPAddress remoteEndPoint)
        {
            int size = Marshal.SizeOf(typeof(NativeMethods.RASUPDATECONN));

            IntPtr pRasUpdateConn = IntPtr.Zero;
            try
            {
                IPAddressConverter converter = new IPAddressConverter();

                NativeMethods.RASUPDATECONN updateConn = new NativeMethods.RASUPDATECONN();
                updateConn.version = GetCurrentApiVersion();
                updateConn.size = size;
                updateConn.interfaceIndex = interfaceIndex;
                updateConn.localEndPoint = (NativeMethods.RASTUNNELENDPOINT)converter.ConvertTo(localEndPoint, typeof(NativeMethods.RASTUNNELENDPOINT));
                updateConn.remoteEndPoint = (NativeMethods.RASTUNNELENDPOINT)converter.ConvertTo(remoteEndPoint, typeof(NativeMethods.RASTUNNELENDPOINT));

                pRasUpdateConn = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(updateConn, pRasUpdateConn, true);

                int ret = UnsafeNativeMethods.Instance.UpdateConnection(handle, pRasUpdateConn);
                if (ret == NativeMethods.ERROR_INVALID_PARAMETER)
                {
                    ThrowHelper.ThrowInvalidOperationException(Resources.Exception_InvalidIkeV2Handle);
                }
                else if (ret != NativeMethods.SUCCESS)
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (pRasUpdateConn != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pRasUpdateConn);
                }
            }
        }
Esempio n. 53
0
 private static extern int RasUpdateConnection(
     RasHandle hRasConn,
     IntPtr lpRasUpdateConn);
Esempio n. 54
0
        /// <summary>
        /// Clears any accumulated statistics for the specified link in a remote access multilink connection.
        /// </summary>
        /// <param name="handle">The handle to the connection.</param>
        /// <param name="subEntryId">The subentry index that corresponds to the link for which to clear statistics.</param>
        /// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns>
        /// <exception cref="System.ArgumentException"><paramref name="subEntryId"/> must be greater than zero.</exception>
        public bool ClearLinkStatistics(RasHandle handle, int subEntryId)
        {
            if (subEntryId <= 0)
            {
                ThrowHelper.ThrowArgumentException("subEntryId", Resources.Argument_ValueCannotBeLessThanOrEqualToZero);
            }

            bool retval = false;

            try
            {
                int ret = SafeNativeMethods.Instance.ClearLinkStatistics(handle, subEntryId);
                if (ret == NativeMethods.SUCCESS)
                {
                    retval = true;
                }
                else if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }

            return retval;
        }
Esempio n. 55
0
        /// <summary>
        /// Indicates whether a connection is currently active.
        /// </summary>
        /// <param name="handle">The handle to check.</param>
        /// <returns><b>true</b> if the connection is active, otherwise <b>false</b>.</returns>
        public bool IsConnectionActive(RasHandle handle)
        {
            bool retval = false;

            int size = Marshal.SizeOf(typeof(NativeMethods.RASCONNSTATUS));

            IntPtr lpRasConnStatus = IntPtr.Zero;
            try
            {
                NativeMethods.RASCONNSTATUS status = new NativeMethods.RASCONNSTATUS();
                status.size = size;

                lpRasConnStatus = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(status, lpRasConnStatus, true);

                retval = SafeNativeMethods.Instance.GetConnectStatus(handle, lpRasConnStatus) == NativeMethods.SUCCESS;
            }
            finally
            {
                if (lpRasConnStatus != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpRasConnStatus);
                }
            }

            return retval;
        }
Esempio n. 56
0
        /// <summary>
        /// Retrieves a connection handle for a subentry of a multilink connection.
        /// </summary>
        /// <param name="handle">The handle of the connection.</param>
        /// <param name="subEntryId">The one-based index of the subentry to whose handle to retrieve.</param>
        /// <returns>The handle of the subentry if available, otherwise a null reference (<b>Nothing</b> in Visual Basic).</returns>
        /// <exception cref="System.ArgumentException"><paramref name="subEntryId"/> cannot be less than or equal to zero.</exception>
        /// <exception cref="System.ArgumentNullException"><paramref name="handle"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        public RasHandle GetSubEntryHandle(RasHandle handle, int subEntryId)
        {
            if (Utilities.IsHandleInvalidOrClosed(handle))
            {
                ThrowHelper.ThrowArgumentNullException("handle");
            }

            if (subEntryId <= 0)
            {
                ThrowHelper.ThrowArgumentException("subEntryId", Resources.Argument_ValueCannotBeLessThanOrEqualToZero);
            }

            RasHandle retval = null;

            try
            {
                IntPtr tempHandle = IntPtr.Zero;
                int ret = SafeNativeMethods.Instance.GetSubEntryHandle(handle, subEntryId, out tempHandle);
                if (ret == NativeMethods.SUCCESS)
                {
                    retval = new RasHandle(tempHandle, subEntryId > 1);
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }

            return retval;
        }
Esempio n. 57
0
        /// <summary>
        /// Terminates a remote access connection.
        /// </summary>
        /// <param name="handle">The remote access connection handle to terminate.</param>
        /// <param name="pollingInterval">The length of time, in milliseconds, the thread must be paused while polling whether the connection has terminated.</param>
        /// <exception cref="System.ArgumentNullException"><paramref name="handle"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="pollingInterval"/> must be greater than or equal to zero.</exception>
        /// <exception cref="DotRas.InvalidHandleException"><paramref name="handle"/> is not a valid handle.</exception>
        public void HangUp(RasHandle handle, int pollingInterval)
        {
            if (handle == null)
            {
                ThrowHelper.ThrowArgumentNullException("handle");
            }

            if (pollingInterval < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException("pollingInterval", pollingInterval, Resources.Argument_ValueCannotBeLessThanZero);
            }

            try
            {
                int ret = SafeNativeMethods.Instance.HangUp(handle);
                if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else if (ret == NativeMethods.SUCCESS)
                {
                    while (RasHelper.Instance.IsConnectionActive(handle))
                    {
                        if (pollingInterval > 0)
                        {
                            // The caller has specified a polling interval, pause the calling thread while the connection is being terminated.
                            Thread.Sleep(pollingInterval);
                        }
                    }

                    // ATTENTION! This required pause comes from the Windows SDK. Failure to perform this pause may cause the state machine to leave 
                    // the port open which will require the machine to be rebooted to release the port.
                    Thread.Sleep(1000);

                    // Mark the handle as invalid to prevent it from being used elsewhere in the assembly.
                    handle.SetHandleAsInvalid();
                }
                else if (ret != NativeMethods.ERROR_NO_CONNECTION)
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
        }
Esempio n. 58
0
        /// <summary>
        /// Retrieves the network access protection (NAP) status for a remote access connection.
        /// </summary>
        /// <param name="handle">The handle of the connection.</param>
        /// <returns>A <see cref="DotRas.RasNapStatus"/> object containing the NAP status.</returns>
        public RasNapStatus GetNapStatus(RasHandle handle)
        {
            if (Utilities.IsHandleInvalidOrClosed(handle))
            {
                ThrowHelper.ThrowArgumentException("handle", Resources.Argument_InvalidHandle);
            }

            RasNapStatus retval = null;

            int size = Marshal.SizeOf(typeof(NativeMethods.RASNAPSTATE));

            NativeMethods.RASNAPSTATE napState = new NativeMethods.RASNAPSTATE();
            napState.size = size;

            IntPtr pNapState = IntPtr.Zero;
            try
            {
                pNapState = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(napState, pNapState, true);

                int ret = SafeNativeMethods.Instance.GetNapStatus(handle, pNapState);
                if (ret == NativeMethods.SUCCESS)
                {
                    napState = Utilities.PtrToStructure<NativeMethods.RASNAPSTATE>(pNapState);

                    long fileTime = napState.probationTime.dwHighDateTime << 0x20 | napState.probationTime.dwLowDateTime;
                    
                    retval = new RasNapStatus(
                        napState.isolationState,
                        DateTime.FromFileTime(fileTime));
                }
                else if (ret == NativeMethods.ERROR_INVALID_HANDLE)
                {
                    ThrowHelper.ThrowInvalidHandleException(handle, "handle", Resources.Argument_InvalidHandle);
                }
                else if (ret == NativeMethods.ERROR_NOT_NAP_CAPABLE)
                {
                    ThrowHelper.ThrowInvalidOperationException(Resources.Exception_HandleNotNapCapable);
                }
                else
                {
                    ThrowHelper.ThrowRasException(ret);
                }
            }
            catch (EntryPointNotFoundException)
            {
                ThrowHelper.ThrowNotSupportedException(Resources.Exception_NotSupportedOnPlatform);
            }
            finally
            {
                if (pNapState != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pNapState);
                }
            }

            return retval;
        }
Esempio n. 59
0
        public void GetSubEntryHandleTest()
        {
            RasHandle expected = new RasHandle(new IntPtr(1), true);

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

            mock.Setup(o => o.GetSubEntryHandle(It.IsAny<RasHandle>(), It.IsAny<int>())).Returns(expected);

            RasConnection target = new RasConnection();
            RasHandle actual = target.GetSubEntryHandle(1);

            Assert.AreSame(expected, actual);
        }
Esempio n. 60
0
        private void Register(NativeMethods.RASCN changeType, RasHandle handle)
        {
            AutoResetEvent waitObject = new AutoResetEvent(false);

            int ret = SafeNativeMethods.Instance.RegisterConnectionNotification(handle, waitObject.SafeWaitHandle, changeType);
            if (ret == NativeMethods.SUCCESS)
            {
                RasConnectionWatcherStateObject stateObject = new RasConnectionWatcherStateObject(changeType);

                stateObject.WaitObject = waitObject;
                stateObject.WaitHandle = ThreadPool.RegisterWaitForSingleObject(waitObject, new WaitOrTimerCallback(this.ConnectionStateChanged), stateObject, Timeout.Infinite, false);

                this._stateObjects.Add(stateObject);
            }
        }