Reopen connection inside windows service

May 30, 2014 at 10:15 AM
Here's my code:
public class VpnKeeperService : IService {
    private ManualResetEvent shutdownEvent;
    private Thread thread;
    private RasConnectionWatcher connectionWatcher;
    private RasHandle currentHandle;

    public VpnKeeperService() {
        this.shutdownEvent = new ManualResetEvent(false);
        this.connectionWatcher = new RasConnectionWatcher();
        this.connectionWatcher.Disconnected += onVpnDisconnected;
    }

    // redial

    void onVpnDisconnected(Object sender, RasConnectionEventArgs e) {
        this.DialUp();
    }

    void DialUp() {
        using(var phoneBook = new RasPhoneBook()) {
            var name = VpnConfig.GetConfig().ConnectionName;
            var user = VpnConfig.GetConfig().Username;
            var pass = VpnConfig.GetConfig().Password;
            var pbPath = VpnConfig.GetConfig().PhoneBookPath;

            phoneBook.Open(pbPath);

            var entry = phoneBook.Entries.FirstOrDefault(e => e.Name.Equals(name));
            if(entry != null) {
                var dialer = new RasDialer();
                dialer.EntryName = name;
                dialer.Credentials = new NetworkCredential(user, pass);
                dialer.PhoneBookPath = pbPath;

                this.connectionWatcher.Handle = dialer.Dial();
            }
        }
    }

    public void Start() {
        this.thread = new Thread(WorkerThreadFunc);
        this.thread.Name = "My Worker Thread";
        this.thread.IsBackground = true;
        this.thread.Start();
    }

    public void Stop() {
        this.shutdownEvent.Set();
        if(!this.thread.Join(3000)) this.thread.Abort();
    }

    private void WorkerThreadFunc() {
        this.DialUp();
        while(!this.shutdownEvent.WaitOne(0)) Thread.Sleep(1000);
    }
}
While it opens a connection on service start, it doesn't reopens it when I manually disconnect vpn. How to do it? Is it possible that it is related to multithreading in some way?
Coordinator
Jun 3, 2014 at 1:03 AM
It looks to me like you never set the EnableRaisingEvents property to true on the RasConnectionWatcher.
Jun 3, 2014 at 5:37 AM
jeff_winn wrote:
It looks to me like you never set the EnableRaisingEvents property to true on the RasConnectionWatcher.
Haha! It works! Thank you) God bless you!