public virtual SessionLock GetLock()
        {
            var sessionToken = new SessionLock(this);

            sessionToken.Take();
            return(sessionToken);
        }
        private void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            switch (e.Reason)
            {
            case Microsoft.Win32.SessionSwitchReason.SessionLock:
                SessionLock?.Invoke(this, EventArgs.Empty);
                break;

            case Microsoft.Win32.SessionSwitchReason.SessionUnlock:
                SessionUnlock?.Invoke(this, EventArgs.Empty);
                break;
            }
        }
        bool IWndMessageProcessor.ProcessMessage(Message m)
        {
            bool result = true;

            if (m.Msg == WM.WTSSESSION_CHANGE)
            {
                var wParams = (int)m.WParam;
                if (wParams == WtsApi32.WTS.SESSION_LOCK)
                {
                    SessionLock?.Invoke();
                }
                else if (wParams == WtsApi32.WTS.SESSION_UNLOCK)
                {
                    SessionUnlock?.Invoke();
                }
                else
                {
                }

                logger.Debug("WTSSESSION_CHANGE: " + wParams);
            }

            return(result);
        }
        public async Task StartLockWorkStationAsync()
        {
            _imminentLocking = true;
            var viewModel = GetViewModel();

            Show();
            var token = _cancellationTokenSource.Token;

            for (int i = 1000; i >= 0; i--)
            {
                viewModel.CentiSeconds = i;
                viewModel.Seconds      = i / 100;

                try
                {
                    await Task.Delay(10, token);
                }
                catch (TaskCanceledException)
                {
                    Hide();
                    _imminentLocking = false;
                    return;
                }

                if (token.IsCancellationRequested)
                {
                    Hide();
                    _imminentLocking = false;
                    return;
                }
            }

            Hide();
            SessionLock.LockSession();
            _imminentLocking = false;
        }
        /// <summary>
        /// Creates a new <c>SystemEventNotifier</c> instance and sets up some
        /// required resources.
        /// </summary>
        /// <param name="maxIdleSeconds">The maximum system idle time in seconds before the
        /// <c>Idle</c> event is being raised.</param>
        public SystemEventNotifier(int maxIdleSeconds = 60 * 15)
        {
            Log.Information($"Instanciating System Event Notifier");
            _cts = new CancellationTokenSource();
            _ct  = _cts.Token;

            this._maxIdleSeconds = maxIdleSeconds;

            //Subscribe to an apple notification fired when the screen is locked
            ((NSDistributedNotificationCenter)NSDistributedNotificationCenter.DefaultCenter).AddObserver(new NSString("com.apple.screenIsLocked"), (obj) =>
            {
                Log.Information("Detected session lock");
                SessionLock?.Invoke(this, new SystemEventArgs("Session Lock"));
            });

            //Subscribe to an apple notification fired when the screen saver starts
            ((NSDistributedNotificationCenter)NSDistributedNotificationCenter.DefaultCenter).AddObserver(new NSString("com.apple.screensaver.didstart"), (obj) =>
            {
                Log.Information("Detected Screen Saver");
                Screensaver?.Invoke(this, new SystemEventArgs("Screensaver"));
            });


            //Subscribe to an apple notification fired when the System goes to Sleep
            NSWorkspace.Notifications.ObserveWillSleep((s, e) =>
            {
                Log.Information("Detected Standy");
                Standby?.Invoke(this, new SystemEventArgs("Stand By"));
            });


            //Subscribe to an apple notification fired when the System goes to power off / reboot
            NSWorkspace.Notifications.ObserveWillPowerOff((s, e) =>
            {
                Log.Information("Detected PowerOff / Reboot");
                ShutdownOrRestart?.Invoke(this, new SystemEventArgs("System ShutDown / Reboot"));
            });



            //Subscribe to an apple notification fired when the System goes to Log off the current User
            NSWorkspace.Notifications.ObserveSessionDidResignActive((s, e) =>
            {
                Log.Information("Detected PowerOff / Reboot");
                SessionLogoff?.Invoke(this, new SystemEventArgs("Session Log Off"));
            });


            // Start a task to poll Idle Time Global Environment Variable
            _pollTask = new Task(() =>
            {
                Log.Information("SystemEventNotifier polling task started");
                Thread.Sleep(POLL_INTERVAL); //Sleep at first to give Mac Delegate time
                while (!_ct.IsCancellationRequested)
                {
                    // Check system idle time
                    TimeSpan idletime = AppDelegate.CheckIdleTime();
                    Log.Debug("Idle time: {IdleTime}", idletime.ToString());
                    if (idletime.TotalSeconds > _maxIdleSeconds)
                    {
                        if (!_idleDetected)
                        {
                            Idle?.Invoke(this, new SystemEventArgs("Idle Timeout"));
                            Log.Information("Detected idle timeout");
                            _idleDetected = true;
                        }
                    }
                    else
                    {
                        if (_idleDetected)
                        {
                            _idleDetected = false;
                        }
                    }

                    Thread.Sleep(POLL_INTERVAL);
                }

                Log.Information("SystemEventNotifier polling task ending");
            }, _ct);

            _pollTask.Start();
            Log.Information($"System Event Notifier was Innitialized Successfully");
        }
Example #6
0
        public async Task <IRestResponse> RequestAsync(Uri uri, Method method, object body, string contentType, int timeout)
        {
            var           connectionClosedRetryCounter = 0;
            IRestResponse response = null;

retry:
            while (connectionClosedRetryCounter < DEFAULT_REQUEST_RETRY_ATTEMPTS)
            {
                var request = CreateRequest(uri, method, body, contentType, timeout);

                var client  = CreateClient();
                var oldAuth = client.DefaultParameters.FirstOrDefault(x => x.Name == XAuthToken)?.Value as string;

                response = await client.ExecuteAsync(request);

                if (response.ResponseStatus == ResponseStatus.Error &&
                    response.ErrorException is WebException &&
                    ((WebException)response.ErrorException).Status == WebExceptionStatus.KeepAliveFailure)
                {
                    //retry
                    connectionClosedRetryCounter++;
                    Logger.LogWarning("Request failed due underlying connection closed URL={0}", uri);
                    goto retry;
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    RestErrorHelper.LogRestWarn(Logger, response, string.Format("Unauthenticated when using authToken={0}", SessionToken));

                    var authenticated = false;
                    try
                    {
                        await SessionLock.WaitAsync();

                        if (SessionToken == null || oldAuth == SessionToken)
                        {
                            authenticated = await AuthenticateAsync(response);
                        }
                        else
                        {
                            authenticated = true;
                        }
                    }
                    finally
                    {
                        SessionLock.Release();
                    }

                    if (authenticated)
                    {
                        connectionClosedRetryCounter++;
                        goto retry;
                    }
                    else
                    {
                        throw new NotAuthenticatedException(string.Format("Not Authenticated for url={0}", uri));
                    }
                }

                connectionClosedRetryCounter = DEFAULT_REQUEST_RETRY_ATTEMPTS;
            }

            return(response);
        }
 private void LockButton_Click(object sender, RoutedEventArgs e)
 {
     Interlocked.Exchange(ref _cancellationTokenSource, new CancellationTokenSource()).Cancel();
     SessionLock.LockSession();
 }
        public IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
        {
            Log.Debug("SystemEventNotifier WndProc: MSG={Msg}, wParam={wParam}, lParam={lParam}",
                      ((UnmanagedMethods.WindowsMessage)msg).ToString(),
                      ((UnmanagedMethods.WindowsMessage)wParam.ToInt32()).ToString(),
                      ((UnmanagedMethods.WindowsMessage)lParam.ToInt32()).ToString());

            switch (msg)
            {
            case (uint)UnmanagedMethods.WindowsMessage.WM_WTSSESSION_CHANGE:
                switch (wParam.ToInt32())
                {
                case UnmanagedMethods.WTS_SESSION_LOGOFF:
                    SessionLogoff?.Invoke(this, new SystemEventArgs("Session Logoff"));
                    Log.Information("Detected session logoff");
                    break;

                case UnmanagedMethods.WTS_SESSION_LOCK:
                    SessionLock?.Invoke(this, new SystemEventArgs("Session Lock"));
                    Log.Information("Detected session lock");
                    break;
                }
                break;

            case (uint)UnmanagedMethods.WindowsMessage.WM_ENDSESSION:

                // If the session is being ended, the wParam parameter is TRUE;
                // the session can end any time after all applications have returned
                // from processing this message. Otherwise, it is FALSE.
                if (wParam.ToInt32() == 0)
                {
                    break;
                }

                switch (lParam.ToInt32())
                {
                case 0:         //Shutdown or restart
                    ShutdownOrRestart?.Invoke(this, new SystemEventArgs("System Shutdown/Restart"));
                    Log.Information("Detected system shutdown/restart");
                    break;

                case UnmanagedMethods.ENDSESSION_LOGOFF:
                case UnmanagedMethods.ENDSESSION_CLOSEAPP:
                case UnmanagedMethods.ENDSESSION_CRITICAL:
                    SessionLogoff?.Invoke(this, new SystemEventArgs("Session Ending"));
                    Log.Information("Detected end of session");
                    break;
                }
                break;

            case (uint)UnmanagedMethods.WindowsMessage.WM_POWERBROADCAST:

                switch (wParam.ToInt32())
                {
                case UnmanagedMethods.PBT_APMSUSPEND:
                case UnmanagedMethods.PBT_APMSTANDBY:
                    Standby?.Invoke(this, new SystemEventArgs("Standby"));
                    Log.Information("Detected entering sleep mode");
                    break;
                }
                break;

            default:
                break;
            }
            return(IntPtr.Zero);
        }