Beispiel #1
0
        public Program()
        {
            dialer = new RasDialer();

            watcher = new RasConnectionWatcher();
            watcher.Disconnected += OnConnectionDisconnected;
        }
 private void InitializeConnectionWatcher()
 {
     _rasConnectionWatcher                     = new RasConnectionWatcher();
     _rasConnectionWatcher.Connected          += _rasConnectionWatcher_Connected;
     _rasConnectionWatcher.Disconnected       += _rasConnectionWatcher_Disconnected;
     _rasConnectionWatcher.EnableRaisingEvents = true;
 }
Beispiel #3
0
        private void BeginConnect()
        {
            string sServerip = tServerIP.Text;
            string sUsername = tUsername.Text;
            string sPassword = tUserkey.Text;

            sEntryName = tVpnName.Text;

            if (!CreateVpnEntry(sServerip))
            {
                return;
            }

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

            try
            {
                this.Dialer.Credentials = new NetworkCredential(sUsername, sPassword);
                var handle = this.Dialer.DialAsync();
                DoMessage(string.Format("{0} 正在尝试连接...", DateTime.Now.ToString()));

                // 连接状态监控
                connWatcher                     = new RasConnectionWatcher();
                connWatcher.Handle              = handle;
                connWatcher.Disconnected       += ConnWatcher_Disconnected;
                connWatcher.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                this.tMessage.AppendText(ex.ToString());
            }
        }
Beispiel #4
0
        private bool disposedValue = false; // To detect redundant calls

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

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

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

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

                disposedValue = true;
            }
        }
Beispiel #5
0
        public MyCustomApplicationContext()
        {
            MainForm = new Form
            {
                ShowInTaskbar = false,
                WindowState   = FormWindowState.Minimized
            };

            _watcher               = new RasConnectionWatcher();
            _watcher.Connected    += OnConnection;
            _watcher.Disconnected += OnDisconnected;
            _watcher.Start();

            _checkIcon = Image.FromFile("check.png");
            _offIcon   = IconFromImage(Image.FromFile("off.png"));
            _onIcon    = IconFromImage(Image.FromFile("on.png"));

            _trayIcon = new NotifyIcon
            {
                Visible          = true,
                ContextMenuStrip = new ContextMenuStrip()
            };

            UpdateTrayIcon();
        }
Beispiel #6
0
        public void RaisesTheErrorEventWhenAnErrorOccursWithinDisconnectedEvent()
        {
            Action <RasConnectionEventArgs> onDisconnectedCallback = null;
            bool executed = false;

            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.Subscribe(It.IsAny <RasNotificationContext>())).Callback <RasNotificationContext>(context =>
            {
                onDisconnectedCallback = context.OnDisconnectedCallback;
            });

            var target = new RasConnectionWatcher(api.Object);

            target.Disconnected += (sender, e) => { throw new TestException(); };
            target.Error        += (sender, e) =>
            {
                executed = true;
            };

            target.Start();

            Assert.IsNotNull(onDisconnectedCallback);

            var eventData = new Mock <RasConnectionEventArgs>();

            onDisconnectedCallback(eventData.Object);

            Assert.True(executed, "The error event was not executed as expected.");
        }
Beispiel #7
0
 public VpnKeeperService()
 {
     this.shutdownEvent = new ManualResetEvent(false);
     this.connWatcher   = new RasConnectionWatcher();
     this.connWatcher.EnableRaisingEvents = true;
     this.connWatcher.Disconnected       += (s, args) => { this.DialUp(); };
 }
Beispiel #8
0
        public void OnDisconnectedCallbackMustRaiseTheDisconnectedEvent()
        {
            var executed = false;

            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.Subscribe(It.IsAny <RasNotificationContext>())).Callback <RasNotificationContext>(c =>
            {
                Assert.Throws <ArgumentNullException>(() => c.OnDisconnectedCallback(null));
                c.OnDisconnectedCallback(new RasConnectionEventArgs(new RasConnectionInformation(
                                                                        new IntPtr(1),
                                                                        "Test",
                                                                        "",
                                                                        Guid.NewGuid(),
                                                                        Guid.NewGuid())));
            });

            var target = new RasConnectionWatcher(api.Object);

            target.Disconnected += (sender, e) =>
            {
                executed = true;
            };

            target.Start();

            Assert.True(executed);
        }
Beispiel #9
0
        public void DisposeWillDisposeTheApi()
        {
            var api = new Mock <IRasConnectionNotification>();

            var target = new RasConnectionWatcher(api.Object);

            target.Dispose();

            api.Verify(o => o.Dispose(), Times.Once);
        }
Beispiel #10
0
        public void ThrowsAnExceptionWhenStopAfterDisposed()
        {
            var api = new Mock <IRasConnectionNotification>();

            var target = new RasConnectionWatcher(api.Object);

            target.Dispose();

            Assert.Throws <ObjectDisposedException>(() => target.Stop());
        }
Beispiel #11
0
        public void ReturnsFalseWhenIsNotActive()
        {
            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.IsActive).Returns(false);

            var target = new RasConnectionWatcher(api.Object);

            Assert.False(target.IsActive);
        }
Beispiel #12
0
        public void StopWillResetTheApi()
        {
            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.IsActive).Returns(true);

            var target = new RasConnectionWatcher(api.Object);

            target.Stop();

            api.Verify(o => o.Reset(), Times.Once);
        }
        public void connectionState(NotifyTray trayIcon, NotifyIcon notify, RasConnectionWatcher watcher, RasHandle handle, Form mainform)
        {
            watcher.Handle = handle;

            /*watcher.Connected += (sender, e) =>
             * {
             *  trayIcon.showBalloon(notifyIcon, "Uw privacy is nu beschermt!", "Mocht de verbinding met onze server om onbekende redenen opeens beëindigen, dan krijgt u via deze weg een melding, zodat u opnieuw kunt verbinden.");
             * };*/

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //BAD PRACTICE:////////////////////////////////////////////////////////////////////////////BAD PRACTICE//////////////////////////////////////////////////////////////////////////////////BAD PRACTICE//
            //BELOW:///////////////////////////////////////////////////////////////////////////////////BELOW:////////////////////////////////////////////////////////////////////////////////////////BELOW:///////

            watcher.Disconnected += (sender, e) =>
            {
                mainform.Show();
                mainform.WindowState = FormWindowState.Normal;

                //trayIcon.showBalloon(notify, "Uw privacy is NIET meer beschermt!", "De verbinding met de server is zojuist verbroken! Maak opnieuw verbinding. (eenmaal klikken op het icoon rechts onderin om de software te openen of rechtermuisknop en kies uit het menu 'verbinden'.)");
                f_Vpnconfiger.lStatusstate.Text      = "Not active";
                f_Vpnconfiger.lStatusstate.BackColor = System.Drawing.Color.Red;
                f_Vpnconfiger.tKey.Enabled           = true;
                f_Vpnconfiger.tUsername.Enabled      = true;
                f_Vpnconfiger.tPassword.Enabled      = true;
                f_Vpnconfiger.bConnect.Enabled       = true;
                f_Vpnconfiger.bDisconnect.Enabled    = false;
                f_Vpnconfiger.bReset.Enabled         = true;
                f_Vpnconfiger.connectItem.Enabled    = true;
                f_Vpnconfiger.disconnectItem.Enabled = false;
                f_Vpnconfiger.exitItem.Enabled       = true;

                mainform.Show();
                mainform.WindowState = FormWindowState.Normal;
            };

            watcher.Connected += (sender, e) =>
            {
                f_Vpnconfiger.connection             = RasConnection.GetActiveConnectionByHandle(handle);           //Update de connectiestatus.
                f_Vpnconfiger.lStatusstate.Text      = "Active";
                f_Vpnconfiger.lStatusstate.BackColor = System.Drawing.Color.Green;
                f_Vpnconfiger.tKey.Enabled           = false;
                f_Vpnconfiger.tUsername.Enabled      = false;
                f_Vpnconfiger.tPassword.Enabled      = false;
                f_Vpnconfiger.bConnect.Enabled       = false;
                f_Vpnconfiger.bDisconnect.Enabled    = true;
                f_Vpnconfiger.bReset.Enabled         = false;
                f_Vpnconfiger.connectItem.Enabled    = false;
                f_Vpnconfiger.disconnectItem.Enabled = true;
                f_Vpnconfiger.exitItem.Enabled       = false;
            };

            watcher.EnableRaisingEvents = true;
        }
Beispiel #14
0
        public void ThrowsAnExceptionWhenConnectionChangedAfterDisposed()
        {
            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.IsActive).Returns(true);

            var connection = new Mock <IRasConnection>();

            var target = new RasConnectionWatcher(api.Object);

            target.Dispose();

            Assert.Throws <ObjectDisposedException>(() => target.Connection = connection.Object);
        }
Beispiel #15
0
 public TinyVpnClient()
 {
     this.macAdd             = "";
     this.userName           = "******";
     this.passWord           = "******";
     this.expiringDate       = "";
     this.subscriptiontype   = "";
     this.flagConnected      = false;
     this.watcher            = new RasConnectionWatcher();
     this.disconnected       = true;
     this.ipaddressCounter   = 0;
     this.initialized        = false;
     this.publicIpAddress    = "";
     this.kryptotelurl       = "http://vpn.51sync.com";
     this.kryptotelurlbackup = "http://vpn.51sync.com";
     this.vpnoneclickurl     = "http://vpn.51sync.com";
 }
Beispiel #16
0
        public void StartWillSubscribeWithoutAConnection()
        {
            var api = new Mock <IRasConnectionNotification>();

            api.Setup(o => o.Subscribe(It.IsAny <RasNotificationContext>())).Callback <RasNotificationContext>(c =>
            {
                Assert.IsNull(c.Connection);
                Assert.IsNotNull(c.OnConnectedCallback);
                Assert.IsNotNull(c.OnDisconnectedCallback);
            });

            var target = new RasConnectionWatcher(api.Object);

            target.Start();

            api.Verify(o => o.Subscribe(It.IsAny <RasNotificationContext>()), Times.Once);
        }
Beispiel #17
0
        /// <summary>
        /// Binds to existing IPSec VPN connection.
        /// </summary>
        private void VpnConnectionBind()
        {
            this._rasDialer            = new RasDialer();
            this._rasConnectionWatcher = new RasConnectionWatcher();

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

            this._rasConnectionWatcher.Handle        = null;
            this._rasConnectionWatcher.Disconnected += _rasConnectionWatcher_Disconnected;
            this._rasConnectionWatcher.Connected    += _rasConnectionWatcher_Connected;
            this._rasConnectionWatcher.Error        += _rasConnectionWatcher_Error;
        }
Beispiel #18
0
        public void RestartsTheWatcherWhenChangedWhileActive()
        {
            var connection = new Mock <RasConnection>();

            var api = new Mock <IRasConnectionNotification>();

            api.SetupSequence(o => o.IsActive)
            .Returns(false)
            .Returns(true)
            .Returns(true)
            .Returns(false);

            var target = new RasConnectionWatcher(api.Object);

            target.Start();

            target.Connection = connection.Object;

            api.Verify(o => o.Subscribe(It.IsAny <RasNotificationContext>()), Times.Exactly(2));
            api.Verify(o => o.Reset(), Times.Once);
        }
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainPresenter"/> class.
        /// </summary>
        /// <param name="view">The view<see cref="IMainView"/>.</param>
        public MainPresenter(IMainView view)
        {
            _dialer = new RasDialer();
            _dialer.StateChanged  += Dialer_StateChanged;
            _dialer.DialCompleted += Dialer_DialCompleted;

            var watcher = new RasConnectionWatcher();

            watcher.Disconnected       += Watcher_Disconnected;
            watcher.EnableRaisingEvents = true;

            _statisticsTimer          = new Timer();
            _saveStatsTimer           = new Timer();
            _statisticsTimer.Interval = 1000;
            _statisticsTimer.Elapsed += StatisticsTimer_Elapsed;
            _saveStatsTimer.Interval  = 10000;
            _saveStatsTimer.Elapsed  += SaveStatsTimer_Elapsed;

            _statisticsTimer.Start();
            _saveStatsTimer.Start();

            if (view != null)
            {
                _view = view;

                view.LoadForm                  += View_Load;
                view.AppClosing                += View_AppClosing;
                view.RefreshDevicesClicked     += View_RefreshDevicesClicked;
                view.ApplyModeClicked          += View_ApplyModeClicked;
                view.ConnectionClicked         += View_ConnectionClicked;
                view.ResetSessionClicked       += View_ResetSessionClicked;
                view.ResetClicked              += View_ResetClicked;
                view.OpenDeviceInfoFormClicked += View_OpenDeviceInfoFormClicked;
                view.SelectedDeviceChanged     += View_SelectedDeviceChanged;
            }
        }
Beispiel #20
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            //declarations
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\RAS AutoDial\\Default\\", true);

            watcher = new RasConnectionWatcher();
            MainForm.CheckForIllegalCrossThreadCalls = false;

            //load config file
            PersistentSettings.Instance.Load("redialer.config");
            chkAutoStart.Checked = bool.Parse(PersistentSettings.Instance.GetValue("AutoStart", "false"));
            chkAutoDial.Checked  = bool.Parse(PersistentSettings.Instance.GetValue("AutoDial", "false"));
            chkNoBytes.Checked   = bool.Parse(PersistentSettings.Instance.GetValue("NoBytes", "false"));
            chkHosted.Checked    = bool.Parse(PersistentSettings.Instance.GetValue("RestartHostedNetwork", "false"));

            txtUserName.Text = PersistentSettings.Instance.GetValue("Username", "");
            txtPassword.Text = PersistentSettings.Instance.GetValue("Password", "");

            // get list of connections
            try
            {
                RasPhoneBook pbk = new RasPhoneBook();
                pbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                isPPPOE = new int[pbk.Entries.Count];
                int i = 0;
                foreach (RasEntry entry in pbk.Entries)
                {
                    if (entry.DialMode == DotRas.RasDialMode.None)
                    {
                        isPPPOE[i] = 1;
                    }
                    else
                    {
                        isPPPOE[i] = 0;
                    }

                    i++;
                    detectedList.Items.Add(entry.Name);
                }
            }
            catch (Exception er)
            {
                appendLog(er.Message);
            }

            //detect default connection
            try
            {
                for (int i = 0; i < detectedList.Items.Count; i++)
                {
                    if (rkApp != null)
                    {
                        if (detectedList.Items[i].ToString() == rkApp.GetValue("DefaultInternet").ToString())
                        {
                            detectedList.SelectedIndex = i;
                            break;
                        }
                    }
                    else
                    {
                        appendLog("Unable to detect Default connection.");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                appendLog(ex.Message);
            }
            //Auto dial
            if (chkAutoDial.Checked == true)
            {
                startButton_Click(sender, e);
            }
        }