Example #1
0
        public void RegisterStart(string text, Action callback)
        {
            Trace.WriteLine($"ProcessWatcher RegisterStart {text}");
            text = text.ToLower();
            WatcherInfo info = _info.ContainsKey(text) ? _info[text] : new WatcherInfo();

            info.StartCallbacks.Add(callback);

            try
            {
                bool didSignal    = false;
                var  runningProcs = Process.GetProcessesByName(text);
                foreach (var proc in runningProcs)
                {
                    didSignal = didSignal || FoundNewRelevantProcess(proc);
                }

                if (runningProcs.Any() && !didSignal)
                {
                    // We were already watching so we didn't signal but the process is running.
                    callback();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }
        private void ParseWatcherInfo(byte[] Content)
        {
            try
            {
                watcherinfo winfo = null;
                using (Stream stream = new MemoryStream(Content))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(watcherinfo));
                    winfo = serializer.Deserialize(stream) as watcherinfo;
                    if (winfo.watcherlist != null)
                    {
                        if (String.Equals("full", winfo.state.ToString(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            this.watchers.Clear();
                        }

                        foreach (watcherlist wlist in winfo.watcherlist)
                        {
                            if (wlist.watcher == null || wlist.watcher.Length == 0)
                            {
                                continue;
                            }
                            foreach (watcher w in wlist.watcher)
                            {
                                WatcherInfo watcherInfo = this.watchers.FirstOrDefault(x =>
                                                                                       String.Equals(x.Resource, wlist.resource) && String.Equals(x.WatcherId, w.id));
                                bool isNew = (watcherInfo == null);
                                if (isNew)
                                {
                                    watcherInfo                  = new WatcherInfo();
                                    watcherInfo.Resource         = wlist.resource;
                                    watcherInfo.Package          = wlist.package;
                                    watcherInfo.WatcherId        = w.id;
                                    watcherInfo.WatcherUriString = w.Value;
                                }

                                watcherInfo.WatcherDisplayName        = w.displayname;
                                watcherInfo.WatcherDurationSubscribed = (int)((w.durationsubscribedSpecified) ? w.durationsubscribed : 0);
                                watcherInfo.WatcherEvent      = w.@event;
                                watcherInfo.WatcherExpiration = (int)((w.expirationSpecified) ? w.expiration : 0);
                                watcherInfo.WatcherStatus     = w.status;

                                if (isNew)
                                {
                                    this.watchers.Add(watcherInfo);
                                }
                            }
                        }
                    }
                }

                // Remove terminated registration
                this.watchers.RemoveAll(x =>
                                        x.WatcherStatus == watcherStatus.terminated);
            }
            catch (Exception ex)
            {
                LOG.Error(ex);
            }
        }
Example #3
0
        static WatcherInfo CreateWatcher(Config config, SessionState sessionState)
        {
            string solSourceDir = Util.GetSolSourcePath(config, sessionState);
            var    cancelToken  = new CancellationTokenSource();
            var    updateEvent  = new ManualResetEventSlim();

            var watcher = new FileSystemWatcher(solSourceDir, "*.sol")
            {
                IncludeSubdirectories = true,
                EnableRaisingEvents   = true,
                NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.CreationTime
            };

            watcher.Changed += (s, e) => updateEvent.Set();
            watcher.Created += (s, e) => updateEvent.Set();
            watcher.Deleted += (s, e) => updateEvent.Set();
            watcher.Renamed += (s, e) => updateEvent.Set();

            var watcherInfo = new WatcherInfo
            {
                CancelToken  = cancelToken,
                UpdateEvent  = updateEvent,
                Watcher      = watcher,
                SessionState = sessionState
            };

            watcherInfo.WatcherThread = new Thread(BlockingWatchDirectory);
            watcherInfo.WatcherThread.Start(watcherInfo);

            return(watcherInfo);
        }
Example #4
0
        /// <summary>
        /// Load the internal cache table with information about watched fields
        /// </summary>
        /// <param name="modelType"></param>
        public static WatcherInfo LoadWatcherInfo(Type modelType)
        {
            WatcherInfo winfo;

            lock (WatcherInfoPerTypeLock)
            {
                if (!WatcherInfoPerType.TryGetValue(modelType, out winfo))
                {
                    var fields            = modelType.Fields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                    var fieldsWithWatches = from field in fields
                                            let att = field.GetCustomAttribute(typeof(Watchable), true) as Watchable
                                                      where att != null
                                                      select new { Field = field, WatcherType = att.WatcherType };
                    foreach (var f in fieldsWithWatches)
                    {
                        var field = f.Field;
                        ValidateWatcherType(field);
                        var isStruct = field.FieldType.IsValueType && !field.FieldType.IsPrimitive && !field.FieldType.IsEnum;
                        if (isStruct)
                        {
                            if (winfo == null)
                            {
                                winfo = new WatcherInfo();
                            }
                            winfo.Fields.Add(new WatcherInfo.FieldInfoAndWatcherInfo()
                            {
                                field = field, watcher = (IDeltaWatcher)Activator.CreateInstance(f.WatcherType)
                            });
                        }
                    }

                    var props = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                    var propertiesWithWatches = from p in props
                                                let att = p.GetCustomAttributes(typeof(Watchable), true).FirstOrDefault() as Watchable
                                                          where att != null
                                                          select new { Property = p, WatcherType = att.WatcherType };
                    foreach (var p in propertiesWithWatches)
                    {
                        var prop = p.Property;
                        ValidateWatcherType(prop);
                        if (winfo == null)
                        {
                            winfo = new WatcherInfo();
                        }
                        winfo.Properties.Add(new WatcherInfo.PropertyInfoAndWatcherInfo()
                        {
                            property = prop, watcher = (IDeltaWatcher)Activator.CreateInstance(p.WatcherType)
                        });
                    }
                    if (winfo == null)
                    {
                        winfo = NOINFO;
                    }

                    WatcherInfoPerType.Add(modelType, winfo);
                }
            }
            return(winfo);
        }
Example #5
0
 public WatchedInfoEx(WatcherInfo winfo, object watchedObject)
 {
     if (winfo.Fields.Count > 0)
     {
         watchedFieldsMark = new List <byte[]>(winfo.Fields.Count);
         foreach (var f in winfo.Fields)
         {
             watchedFieldsMark.Add(f.watcher.GetAsBytes(f.field.GetValue(watchedObject)));
         }
     }
     if (winfo.Properties.Count > 0)
     {
         watchedPropertiesMark = new List <byte[]>(winfo.Properties.Count);
         foreach (var p in winfo.Properties)
         {
             watchedPropertiesMark.Add(p.watcher.GetAsBytes(p.property.GetValue(watchedObject)));
         }
     }
 }
Example #6
0
        public void RegisterStop(string text, Action callback)
        {
            Trace.WriteLine($"ProcessWatcher RegisterStop {text}");
            text = text.ToLower();
            WatcherInfo info = _info.ContainsKey(text) ? _info[text] : _info[text] = new WatcherInfo();

            info.StopCallbacks.Add(callback);

            try
            {
                var runningProcs = Process.GetProcessesByName(text);
                foreach (var proc in runningProcs)
                {
                    FoundNewRelevantProcess(proc);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }
Example #7
0
            public bool ShouldMarkAsDirty(WatcherInfo winfo, object watchedObject)
            {
                if (watchedFieldsMark != null)
                {
                    int index = 0;
                    foreach (var mark in watchedFieldsMark)
                    {
                        var currentField = winfo.Fields[index];
                        var currentBytes = currentField.watcher.GetAsBytes(currentField.field.GetValue(watchedObject));
                        for (int i = 0; i < currentBytes.Length; i++)
                        {
                            if (currentBytes[i] != mark[i])
                            {
                                return(true);
                            }
                        }
                        index++;
                    }
                }

                if (watchedPropertiesMark != null)
                {
                    int index = 0;
                    foreach (var mark in watchedPropertiesMark)
                    {
                        var currentProperty = winfo.Properties[index];
                        var currentBytes    = currentProperty.watcher.GetAsBytes(currentProperty.property.GetValue(watchedObject));
                        for (int i = 0; i < currentBytes.Length; i++)
                        {
                            if (currentBytes[i] != mark[i])
                            {
                                return(true);
                            }
                        }
                        index++;
                    }
                }
                return(false);
            }
Example #8
0
        protected override void EndProcessing()
        {
            var    config       = this.ReadConfig();
            string solSourceDir = Util.GetSolSourcePath(config, SessionState);

            if (!Directory.Exists(solSourceDir))
            {
                Console.WriteLine($"Creating source directory at '{solSourceDir}'");
                Directory.CreateDirectory(solSourceDir);
            }

            lock (_syncRoot)
            {
                if (_watcher != null)
                {
                    var current = Path.GetFullPath(_watcher.Watcher.Path);

                    if (current == solSourceDir)
                    {
                        Console.WriteLine($"Source directory already being watched: {solSourceDir}");
                    }
                    else
                    {
                        Console.WriteLine($"Updating source file watcher from '{current}' to '{solSourceDir}'");
                        _watcher.Watcher.Path = solSourceDir;
                    }
                }
                else
                {
                    Console.WriteLine($"Watching for file changes in source directory: {solSourceDir}");
                    _watcher = CreateWatcher(config, SessionState);
                }
            }

            base.EndProcessing();
        }
Example #9
0
        private void ParseWatcherInfo(byte[] Content)
        {
            try
            {
                watcherinfo winfo = null;
                using (Stream stream = new MemoryStream(Content))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(watcherinfo));
                    winfo = serializer.Deserialize(stream) as watcherinfo;
                    if (winfo.watcherlist != null)
                    {
                        if (String.Equals("full", winfo.state.ToString(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            this.watchers.Clear();
                        }

                        foreach (watcherlist wlist in winfo.watcherlist)
                        {
                            if (wlist.watcher == null || wlist.watcher.Length == 0)
                            {
                                continue;
                            }
                            foreach (watcher w in wlist.watcher)
                            {
                                WatcherInfo watcherInfo = this.watchers.FirstOrDefault(x =>
                                    String.Equals(x.Resource, wlist.resource) && String.Equals(x.WatcherId, w.id));
                                bool isNew = (watcherInfo == null);
                                if (isNew)
                                {
                                    watcherInfo = new WatcherInfo();
                                    watcherInfo.Resource = wlist.resource;
                                    watcherInfo.Package = wlist.package;
                                    watcherInfo.WatcherId = w.id;
                                    watcherInfo.WatcherUriString = w.Value;
                                }

                                watcherInfo.WatcherDisplayName = w.displayname;
                                watcherInfo.WatcherDurationSubscribed = (int)((w.durationsubscribedSpecified) ? w.durationsubscribed : 0);
                                watcherInfo.WatcherEvent = w.@event;
                                watcherInfo.WatcherExpiration = (int)((w.expirationSpecified) ? w.expiration : 0);
                                watcherInfo.WatcherStatus = w.status;

                                if (isNew)
                                {
                                    this.watchers.Add(watcherInfo);
                                }
                            }
                        }
                    }
                }

                // Remove terminated registration
                this.watchers.RemoveAll(x =>
                    x.WatcherStatus == watcherStatus.terminated);
            }
            catch (Exception ex)
            {
                LOG.Error(ex);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WatcherEx" /> class.
 /// </summary>
 /// <param name="info">The information.</param>
 public WatcherEx(WatcherInfo info)
     : base(info)
 {
 }
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 /// <param name="info">The information.</param>
 protected BaseWatcher(WatcherInfo info)
 {
     Argument.IsNotNull(info);
     _watcherInfo = info;
     Initialize();
 }
Example #12
0
 public QueueWatcher(WatcherInfo info) : base(info)
 {
 }
Example #13
0
        private void OpenExtension(string p)
        {
            //folderTreeView1.Nodes.Add(p);
            pathCurrentExtension = Path.Combine(folderWithExt, p);
            FS.CreateFoldersPsysicallyUnlessThere(pathCurrentExtension);
            // new WatcherEx(DBSouboru.msdnAspx, "*.cs");
            WatcherInfo info = new WatcherInfo();
            info.ChangesFilters = NotifyFilters.Size;
            //NotifyFilters.FileName |
            //NotifyFilters.DirectoryName ;

            info.IncludeSubFolders = true;
            info.WatchesFilters = WatcherChangeTypes.All;

            info.WatchForDisposed = false;
            info.WatchForError = false;
            info.WatchPath = pathCurrentExtension;
            info.BufferKBytes = 8;
            info.FileFilter = "*.*";
            //-Mus� to b�t men�� interval aby se zm�ny na disk stihli ulo�it a nezobrazovalo to furt ten dialog
            info.MonitorPathInterval = searchInterval / 4;
            fswe = new WatcherEx(info);

            //FileSystemWatcherEx fswe = new FileSystemWatcherEx(pathCurrentExtension);
            //fswe.Created += new FileSystemEventHandler(fswe_Created);
            //fswe.Deleted += new FileSystemEventHandler(fswe_Deleted);
            //fswe.EventPathAvailability += new PathAvailabilityHandler(fswe_EventPathAvailability);
            //fswe.Changed += new FileSystemEventHandler(fswe_Changed);
            //fswe.Renamed += new RenamedEventHandler(fswe_Renamed);

            //FileSystemWatcherEx fswe = new FileSystemWatcherEx(pathCurrentExtension);
            fswe.Created += new FileSystemEventHandler(fswe_Created);
            fswe.Deleted += new FileSystemEventHandler(fswe_Deleted);
            fswe.PathAvailability += new PathAvailabilityHandler(fswe_EventPathAvailability);
            fswe.ChangedSize += new FileSystemEventHandler(fswe_Changed);
            fswe.Renamed += new RenamedEventHandler(fswe_Renamed);

            //fswe.EventPathAvailability += new WatcherExEventHandler(fswe_EventPathAvailability);
            //fswe.EventChangedDirectoryName += new WatcherExEventHandler(fswe_EventChangedDirectoryName);
            //fswe.EventChangedFileName += new WatcherExEventHandler(fswe_EventChangedFileName);
            //fswe.EventCreated += new WatcherExEventHandler(fswe_EventCreated);
            //fswe.EventDeleted += new WatcherExEventHandler(fswe_EventDeleted);
            //fswe.EventRenamed += new WatcherExEventHandler(fswe_EventRenamed);
            //fswe.EventChangedSize += new WatcherExEventHandler(fswe_EventChangedSize);

            //folderTreeView1.DrillToFolder(path);
            //fswe.StartFolderMonitor();
            fswe.Start();

            ReloadFilesOfExtension();
            RA.WriteToKeyString(SettingsForm.LastExt, p);
            OnStatus("Extension " + p + " successfully loaded");
        }