Пример #1
0
        protected override void OnStop()
        {
            if (background_DeviceDetector != null)
            {
                background_DeviceDetector.CancelAsync();
                background_DeviceDetector.Dispose();
            }

            if (background_DeviceReader != null)
            {
                background_DeviceReader.CancelAsync();
                background_DeviceReader.Dispose();
            }

            if (background_CommandServer != null)
            {
                background_CommandServer.CancelAsync();
                background_CommandServer.Dispose();
            }

            watcher.EventArrived -= USBwatcher_EventArrived;
            watcher.Dispose();

            EventLog.WriteEntry("The service was stopped successfully.", EventLogEntryType.Information);
        }
Пример #2
0
        public override void Run(object sender, DoWorkEventArgs ev)
        {
            try
            {
                while (true)
                {
                    bool   satisfaction = false;
                    string vsn          = "";

                    watcher.EventArrived +=
                        new EventArrivedEventHandler(
                            (send, eve) =>
                    {
                        if (((ManagementBaseObject)eve.NewEvent["TargetInstance"])["Description"].ToString() == "Removable Disk")
                        {
                            satisfaction = true;
                            vsn          = ((ManagementBaseObject)eve.NewEvent["TargetInstance"])["VolumeSerialNumber"].ToString();
                        }
                    });

                    watcher.Start();
                    WaitHandle wh = new ManualResetEvent(false);

                    while (!satisfaction)
                    {
                        if ((sender as BackgroundWorker).CancellationPending == true)
                        {
                            ev.Cancel = true;
                            Dispose();
                            return;
                        }
                        wh.WaitOne(5000);
                    }
                    ;

                    watcher.Stop();

                    var eventsWithCallbacks = EventToCallbackMapping.Where(x => (x.Key as USBInsertionEvent).VolumeSerialNumber.Equals(vsn));

                    // Execute callbacks
                    foreach (var eventWithCallback in eventsWithCallbacks)
                    {
                        foreach (var callback in eventWithCallback.Value)
                        {
                            callback.Invoke();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                watcher.Dispose();
                throw ex;
            }
        }
Пример #3
0
        public Task WaitForAsync(string name, CancellationToken cancellationToken)
        {
            _logger.WriteLine("Attempting {0} wait.", IsEfficient ? "efficient" : "inefficient");

            var taskSource = new TaskCompletionSource <object>();
            var query      = IsEfficient
                      ? new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = '" + name + "'")
                      : new EventQuery("SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 0.5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name LIKE '" + name + "'");

            ManagementEventWatcher watcher = null;

            try {
                watcher = new ManagementEventWatcher(query);
                cancellationToken.Register(() => {
                    _logger.WriteLine("Received Cancel while waiting for '{0}'.", name);
                    watcher.Stop();
                    watcher.Dispose();
                    taskSource.TrySetCanceled();
                });
                watcher.EventArrived += (sender, e) => {
                    _logger.WriteLine("Received process start event for '{0}'.", name);
                    watcher.Stop();
                    watcher.Dispose();
                    taskSource.TrySetResult(null);
                };

                try {
                    watcher.Start();
                }
                catch (ManagementException) {
                    if (!IsEfficient)
                    {
                        throw;
                    }

                    watcher.Dispose();
                    IsEfficient = false;
                    return(WaitForAsync(name, cancellationToken));
                }
            }
            catch (Exception) {
                if (watcher != null)
                {
                    watcher.Dispose();
                }
                throw;
            }

            return(taskSource.Task);
        }
Пример #4
0
 public void Deactivate()
 {
     Settings.Log?.Debug(nameof(Deactivate));
     try
     {
         IsRunning = false;
         _ProcessStartEvent.EventArrived -= new EventArrivedEventHandler(ProcessStartEventArrived);
         _ProcessStartEvent.Dispose();
     }
     catch (Exception ex)
     {
         Settings.Log?.Error(ex.Message, ex);
     }
 }
Пример #5
0
 internal static void StopUpdater()
 {
     addWatcher.Stop();
     addWatcher.Dispose();
     removeWatcher.Stop();
     removeWatcher.Dispose();
 }
Пример #6
0
        public static void Main(string[] args)
        {
            nomPat = ConfigurationManager.AppSettings["RepSource"];
            Console.WriteLine(string.Format("Source du fichier .pat = {0}", nomPat));
            if (!System.IO.File.Exists(nomPat))
            {
                Console.WriteLine("Attention, le fichier n'existe pas, chosissez en un autre");
            }

            Console.WriteLine();
            Console.WriteLine("Menu : Q = Quitter, F = Choisir fichier");
            Console.WriteLine();
            Console.WriteLine("Insérer la clé USB et le fichier y sera copié");
            Console.WriteLine("Retirer la clé USB une fois la copie effectuée");

            watcher = new ManagementEventWatcher();
            var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");

            watcher.EventArrived += watcher_EventArrived;
            watcher.Query         = query;
            watcher.Start();

            watcherOut = new ManagementEventWatcher();
            query      = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
            watcherOut.EventArrived += watcher_EventArrived2;
            watcherOut.Query         = query;
            watcherOut.Start();

            while (true)
            {
                string rep = Console.ReadLine();
                if (!string.IsNullOrEmpty(rep) && rep.ToUpper().StartsWith("F"))
                {
                    OpenFileDialog fld = new OpenFileDialog();
                    fld.AddExtension    = true;
                    fld.CheckFileExists = true;
                    fld.DefaultExt      = "*.pat";
                    fld.Filter          = "fichier pat files (*.pat)|*.pat|All files (*.*)|*.*";
                    if (fld.ShowDialog() == DialogResult.OK)
                    {
                        if (System.IO.File.Exists(fld.FileName))
                        {
                            Console.WriteLine("Le fichier {0} sera celui copié à partir de maintenant");
                            nomPat = fld.FileName;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(rep) && rep.ToUpper().StartsWith("Q"))
                {
                    watcher.Stop();
                    watcher.Dispose();
                    watcher = null;

                    watcherOut.Stop();
                    watcherOut.Dispose();
                    watcherOut = null;
                    break;
                }
            }
        }
Пример #7
0
 public static void Detach()
 {
     SystemEvents.PowerModeChanged       -= PowerModeChanged;
     SystemEvents.DisplaySettingsChanged -= DisplaySettingsChanged;
     usbEventWatcher?.Stop();
     usbEventWatcher?.Dispose();
 }
Пример #8
0
 void ServiceControl_Disposed(object sender, EventArgs e)
 {
     watcherCreate.Stop();
     watcherDelete.Stop();
     watcherCreate.Dispose();
     watcherDelete.Dispose();
 }
Пример #9
0
        /// <summary>
        /// Stop the UsbAdapter and release the allocated resources
        /// </summary>
        public void Dispose()
        {
            StopWatcher();

            foreach (var usbPenComm in usbPenComms)
            {
                usbPenComm.Authenticated     -= PenComm_Authenticated;
                usbPenComm.ConnectionRefused -= PenComm_ConnectionRefused;
                usbPenComm.Disconnected      -= PenComm_Disconnected;
                usbPenComm.Dispose();
            }

            usbPenComms.Clear();

            if (_plugInWatcher != null)
            {
                try
                {
                    _plugInWatcher.Dispose();
                    _plugInWatcher = null;
                }
                catch (Exception) { }
            }

            if (_unPlugWatcher != null)
            {
                try
                {
                    _unPlugWatcher.Dispose();
                    _unPlugWatcher = null;
                }
                catch (Exception) { }
            }
        }
Пример #10
0
 private void MenuItem_OnClick(object sender, RoutedEventArgs e)
 {
     _managementEventWatcher.Stop();
     _managementEventWatcher.Dispose();
     NotificationIcon.Dispose();
     Application.Current.Shutdown(0);
 }
Пример #11
0
 void ProcessesControl_Disposed(object sender, EventArgs e)
 {
     watcherCreate.Stop();
     watcherDelete.Stop();
     watcherCreate.Dispose();
     watcherDelete.Dispose();
 }
        /// Dispose
        #region Dispose

        /// <summary>
        /// Disposes data
        /// </summary>
        public void Dispose()
        {
            // get rid of event watcher
            if (_eventWatcher != null)
            {
                try
                {
                    _eventWatcher.EventArrived -= mewPrintJobs_JobArrived;
                    _eventWatcher.Stop();

                    _eventWatcher.Dispose();
                    _eventWatcher = null;
                }
                catch (Exception ex)
                {
                    WPFNotifier.DebugError(ex);
                }
            }

            // get rid of management scope
            if (managementScope != null)
            {
                try
                {
                    managementScope = null;
                }
                catch (Exception ex)
                {
                    WPFNotifier.DebugError(ex);
                }
            }
        }
Пример #13
0
        public void Dispose()
        {
            Trace_n($"Disposing ‹{GetType().Name}›...", "");

            if (_watchr == null)
            {
                return;
            }
            _watchr.Stop();
            _watchr.Dispose();

            foreach (var h in _handlrs)
            {
                try
                {
                    if (h.OnAutomationEvent != null)
                    {
                        Automation.RemoveAutomationEventHandler(h.EventID, h.Element, h.OnAutomationEvent);
                    }

                    if (h.OnFocusChanged != null)
                    {
                        Automation.RemoveAutomationFocusChangedEventHandler(h.OnFocusChanged);
                    }

                    if (h.OnStructureChanged != null)
                    {
                        Automation.RemoveStructureChangedEventHandler(h.Element, h.OnStructureChanged);
                    }
                }
                catch { }
            }
        }
Пример #14
0
        protected virtual void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (disposing)
            {
                // Free any other managed objects here.
                try
                {
                    if (_watcher is not null)
                    {
                        _watcher.EventArrived -= OnEventArrived;
                        _watcher.Stop();                         // This may throw InvalidCastException.
                        _watcher.Dispose();
                    }
                }
                catch (InvalidCastException)
                {
                }
            }

            // Free any unmanaged objects here.
            _isDisposed = true;
        }
Пример #15
0
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (RemoveWatcher != null)
                {
                    RemoveWatcher.Stop();
                    RemoveWatcher.Dispose();
                }

                if (InsertWatcher != null)
                {
                    InsertWatcher.Stop();
                    InsertWatcher.Dispose();
                }

                SystemEvents.PowerModeChanged -= OnPowerChange;
            }
            catch (Exception exc)
            {
                LogManager.Write(exc.Message);
            }

            tmrIdle.Enabled = false;

            foreach (var timer in _timers)
            {
                timer.Value.Enabled = false;
                timer.Value.Tick   -= timer_Tick;
            }

            _timers.Clear();
        }
Пример #16
0
 public static void StopMonitorLeagueStart()
 {
     _gameWatch.EventArrived
         -= new EventArrivedEventHandler(Form1.gameWatch_EventArrived);
     _gameWatch.Stop();
     _gameWatch.Dispose();
 }
Пример #17
0
 public static void StopMonitorClientStart()
 {
     _clientWatch.EventArrived
         -= new EventArrivedEventHandler(Form1.clientWatch_EventArrived);
     _clientWatch.Stop();
     _clientWatch.Dispose();
 }
Пример #18
0
        private void VolumeWatcher_Stopped(object sender, StoppedEventArgs e)
        {
            volumeWatcher.Dispose();

            serviceIsRunning = false;
            serviceEvent.Set();
        }
 protected override void OnDispose()
 {
     _connectEventWatcher?.Dispose();
     _connectEventWatcher = null;
     _disconnectEventWatcher?.Dispose();
     _disconnectEventWatcher = null;
 }
Пример #20
0
        /// <summary>
        /// Delegate method that asynchronously monitors semi-sync WMI services creation.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void ServiceCreationWatcherStartSemiSyncDoWork(object sender, DoWorkEventArgs e)
        {
            if (!(sender is BackgroundWorker worker))
            {
                return;
            }

            if (worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            Exception throwException = null;

            try
            {
                var eventCount = 0;
                var scope      = e.Argument as ManagementScope;
                _wmiAsyncCreationWatcher = _wmiAsyncCreationWatcher ?? new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(WmiQueriesTimeoutInSeconds), WMI_QUERIES_WHERE_CLAUSE));
                while (!worker.CancellationPending)
                {
                    var remoteService = _wmiAsyncCreationWatcher.WaitForNextEvent();
                    if (remoteService != null)
                    {
                        worker.ReportProgress(++eventCount, remoteService);
                    }
                }
            }
            catch (Exception ex)
            {
                throwException = ex;
            }

            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }

            try
            {
                if (_wmiAsyncCreationWatcher != null)
                {
                    _wmiAsyncCreationWatcher.Stop();
                    _wmiAsyncCreationWatcher.Dispose();
                }

                _wmiAsyncCreationWatcher = null;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            if (throwException != null)
            {
                throw throwException;
            }
        }
Пример #21
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _watcher.Stop();
         _watcher.Dispose();
     }
 }
Пример #22
0
        public void StopMonitoring()
        {
            _startWatch.Stop();
            _stopWatch.Stop();

            _startWatch.Dispose();
            _stopWatch.Dispose();
        }
Пример #23
0
 /// <summary>
 /// Stops the monitoring.
 /// </summary>
 internal void StopMonitoring()
 {
     if (_usbInsertWatcher != null)
     {
         _usbInsertWatcher.EventArrived -= UsbInsertWatcher_EventArrived;
         _usbInsertWatcher.Dispose();
         _usbInsertWatcher = null;
         Trace.TraceInformation("{0}.StartMonitoring: Win32_SerialPort insert watcher disposed", CLASSNAME);
     }
     if (_usbRemovalWatcher != null)
     {
         _usbRemovalWatcher.EventArrived -= UsbRemovalWatcher_EventArrived;
         _usbRemovalWatcher.Dispose();
         _usbRemovalWatcher = null;
         Trace.TraceInformation("{0}.StartMonitoring: Win32_SerialPort removal watcher disposed", CLASSNAME);
     }
 }
Пример #24
0
 protected virtual void Finish()
 {
     try {
         ev.Stop();
         ev.Dispose();
     }
     catch {}
 }
Пример #25
0
 public void Dispose()
 {
     if (MonitorWatcher != null)
     {
         StopMonitorWatch();
         MonitorWatcher.Dispose();
     }
 }
        public new void Dispose()
        {
            watcher.Dispose();
            newPidQ.Dispose();
            ctsStop.Dispose();

            base.Dispose();
        }
Пример #27
0
 public static void Stop()
 {
     if (_watcherDevices != null)
     {
         _watcherDevices.Stop();
         _watcherDevices.Dispose();
     }
 }
Пример #28
0
 public void Stop()
 {
     if (_watcher != null)
     {
         _watcher.Stop();
         _watcher.Dispose();
     }
 }
Пример #29
0
        protected void OnStop()
        {
            //eLog.WriteEntry("In OnStop");

            lDisplay.ResetAllSongInfo();

            if (sWatcher != null) // Removes any watchers that are opened when Kodi is closed
            {
                sWatcher.Dispose();
            }
            if (eWatcher != null)
            {
                eWatcher.Dispose();
            }

            lDisplay.Disable();
        }
Пример #30
0
 /// <summary>
 /// Освобождает используемые ресурсы
 /// </summary>
 public void Dispose()
 {
     _mewDiskDriveToPartitionCreation?.Stop();
     _mewDiskDriveToPartitionCreation?.Dispose();
     _mewDiskDriveToPartitionDeletion?.Stop();
     _mewDiskDriveToPartitionDeletion?.Dispose();
     _isDisposed = true;
 }