Exemplo n.º 1
0
        //添加对一个目录的监视
        private void AddWatchingDirectory(object sender, EventArgs e)
        {
            string             watchedName = string.Empty;
            string             watchedFolder;
            string             backupFolder;
            WatcherChangeTypes changeTypes;
            bool enable;

            FBD.Description = "请选择需要进行监视的文件夹";
            if (FBD.ShowDialog() == DialogResult.OK)
            {
                //如果该目录已经存在于监视列表,则不再重新添加
                if (watcherList.Find(w => w.Path == FBD.SelectedPath) != null)
                {
                    MessageBox.Show("该目录已经于监视目录列表中");
                    return;
                }
                watchedFolder = FBD.SelectedPath;
                backupFolder  = SelectBackupFloder(watchedFolder);
                if (!string.IsNullOrEmpty(backupFolder))
                {
                    changeTypes = (WatcherChangeTypes.Changed | WatcherChangeTypes.Created | WatcherChangeTypes.Renamed);
                    enable      = false;
                    WatchInfo watch = new WatchInfo();
                    watch.BackupFolder  = backupFolder;
                    watch.ChangeTypes   = changeTypes;
                    watch.Enable        = enable;
                    watch.WatchedFolder = watchedFolder;
                    AddWatchItem(watch);
                    //添加一个监视项后触发OnWatchSettingChanged事件以便进行实时保存
                    this.OnWatchSettingChanged();
                }
            }
        }
        public void TestWatchFunctionNotFound()
        {
            var queryStringValue = "abc";
            var request          = new DefaultHttpRequest(new DefaultHttpContext())
            {
                Query = new QueryCollection
                        (
                    new System.Collections.Generic.Dictionary <string, StringValues>()
                {
                    { "model", queryStringValue }
                }
                        )
            };
            var       logger    = NullLoggerFactory.Instance.CreateLogger("Null Logger");
            WatchInfo watchInfo = new WatchInfo(new WatchRepository());
            var       response  = watchInfo.Run(request, logger);

            response.Wait();

            // Check that the response is an "OK" response
            Assert.IsAssignableFrom <NotFoundObjectResult>(response.Result);

            // Check that the contents of the response are the expected contents
            var result = (NotFoundObjectResult)response.Result;

            Assert.Equal("This model doesn't exist", result.Value);
        }
Exemplo n.º 3
0
 public WatchInternal(InotifyCallback callback, EventType mask, WatchInfo watchinfo)
 {
     this.callback      = callback;
     this.mask          = mask;
     this.watchinfo     = watchinfo;
     this.is_subscribed = true;
 }
Exemplo n.º 4
0
        /// <summary>
        /// Starts the current watch.
        /// If there is no current watch a new watch will be created and started.
        /// If the current watch is already running, a new watch will be created, started and added as a child,
        /// the current watch will be pushed on a stack and the created watch becomes the current watch.
        /// </summary>
        /// <param name="name">Name of the watch.</param>
        /// <param name="stopAndResetChilds">Flag for stopping and resetting all child watches of the current timer.</param>
        public void StartWatch(string name, bool stopAndResetChilds = false)
        {
            if ((TurnOff))
            {
                return;
            }

            if ((mStackTable.Count == 0))
            {
                mStackTable.Push(new WatchInfo(name, GetRoot()));
            }

            dynamic wInfo = (WatchInfo)mStackTable.Peek();

            if ((wInfo.IsRunning))
            {
                dynamic newWInfo = new WatchInfo(name, wInfo);
                mStackTable.Push(newWInfo);
                newWInfo.RestartWatch(stopAndResetChilds);
            }
            else
            {
                wInfo.RestartWatch(stopAndResetChilds);
            }
        }
Exemplo n.º 5
0
 public PendingMove(WatchInfo watched, string srcname, DateTime time, uint cookie)
 {
     Watch   = watched;
     SrcName = srcname;
     Time    = time;
     Cookie  = cookie;
 }
Exemplo n.º 6
0
        WatchWindowExpressionsSettingsImpl(ISettingsService settingsService)
        {
            this.settingsService = settingsService;
            watchSection         = settingsService.GetOrCreateSection(SETTINGS_GUID);
            infos = new WatchInfo[WatchWindowsHelper.NUMBER_OF_WATCH_WINDOWS];
            for (int i = 0; i < infos.Length; i++)
            {
                infos[i] = new WatchInfo(i);
            }

            var expressions = new List <string>();

            foreach (var sect in watchSection.SectionsWithName("Watch"))
            {
                var index = sect.Attribute <int?>("Index") ?? -1;
                if ((uint)index >= (uint)infos.Length)
                {
                    continue;
                }
                var info = infos[index];
                info.Section = sect;
                expressions.Clear();
                foreach (var exprSect in sect.SectionsWithName("Expression"))
                {
                    var expr = exprSect.Attribute <string>("Value");
                    if (expr == null)
                    {
                        continue;
                    }
                    expressions.Add(expr);
                }
                info.Expressions = expressions.ToArray();
            }
        }
        public IActionResult SubmitVideoSessionResult(JSONWrappers.VideoResult jsonResult)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    /* Fetching parameters from wrapper class */
                    ulong subjectID = Convert.ToUInt64(jsonResult.SubjectID);
                    IEnumerable <JSONWrappers.WatchInfo> jsonWatchSession = jsonResult.WatchSession;

                    List <WatchInfo> watchSession = new List <WatchInfo>(jsonWatchSession.Count());
                    foreach (JSONWrappers.WatchInfo info in jsonWatchSession)
                    {
                        watchSession.Add(WatchInfo.FromJSON(info));
                    }

                    VideosDataBase.SubmitVideoSessionResult(subjectID, watchSession);
                    m_Logger.LogInformation($"Submitted watch session result for subject with ID {subjectID}");
                    return(Ok(subjectID));
                }

                return(BadRequest(ModelState));
            }
            catch (Exception e)
            {
                m_Logger.LogError(e.Message);
                throw;
            }
        }
Exemplo n.º 8
0
        // Filter WatchInfo items when we do the Lookup.
        // We do the filtering here to avoid having to acquire
        // the watched_by_wd lock yet again.
        private static WatchInfo Lookup(int wd, EventType event_type)
        {
            lock (watched_by_wd) {
                WatchInfo watched;
                if (last_watched != null && last_watched.Wd == wd)
                {
                    watched = last_watched;
                }
                else
                {
                    watched = watched_by_wd [wd] as WatchInfo;
                    if (watched != null)
                    {
                        last_watched = watched;
                    }
                }

                if (watched != null && (watched.FilterMask & event_type) != 0)
                {
                    watched.FilterSeen |= event_type;
                    watched             = null;
                }

                return(watched);
            }
        }
Exemplo n.º 9
0
        // A directory we are watching has moved.  We need to fix up its path, and the path of
        // all of its subdirectories, their subdirectories, and so on.
        static private void HandleMove(string srcpath, string dstpath)
        {
            WatchInfo start = watched_by_path [srcpath] as WatchInfo;                   // not the same as src!

            if (start == null)
            {
                Console.WriteLine("Lookup failed for {0}", srcpath);
                return;
            }

            // Queue our starting point, then walk its subdirectories, invoking MoveWatch() on
            // each, repeating for their subdirectories.  The relationship between start, child
            // and dstpath is fickle and important.
            Queue queue = new Queue();

            queue.Enqueue(start);
            do
            {
                WatchInfo target = queue.Dequeue() as WatchInfo;
                for (int i = 0; i < target.Children.Count; i++)
                {
                    WatchInfo child = target.Children[i] as WatchInfo;
                    string    name  = Path.Combine(dstpath, child.Path.Substring(start.Path.Length + 1));
                    MoveWatch(child, name);
                    queue.Enqueue(child);
                }
            } while (queue.Count > 0);

            // Ultimately, fixup the original watch, too
            MoveWatch(start, dstpath);
        }
Exemplo n.º 10
0
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            //#warning 未有判断配置节中属性值拼写错误的情况
            List <WatchInfo> watches  = new List <WatchInfo>();
            XmlNodeList      nodeList = section.ChildNodes;

            foreach (XmlNode node in nodeList)
            {
                WatchInfo watch = new WatchInfo();
                //watch.Name = node.Attributes[N_Name].Value;
                watch.WatchedFolder = node.Attributes[N_WatchedFolder].Value;
                watch.BackupFolder  = node.Attributes[N_BackupFolder].Value;
                string             changeTypeVal    = node.Attributes[N_ChangeType].Value;
                string[]           changeTypeValArr = changeTypeVal.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                WatcherChangeTypes changeTypes      = (WatcherChangeTypes)Enum.Parse(typeof(WatcherChangeTypes), changeTypeValArr[0], true);
                for (int i = 1; i < changeTypeValArr.Length; i++)
                {
                    WatcherChangeTypes changeType = (WatcherChangeTypes)Enum.Parse(typeof(WatcherChangeTypes), changeTypeValArr[i], true);
                    changeTypes = (changeTypes | changeType);
                }
                watch.ChangeTypes = changeTypes;
                watch.Enable      = bool.Parse(node.Attributes[N_Enable].Value);
                watches.Add(watch);
            }
            return(watches);
        }
Exemplo n.º 11
0
        // Ensure our watch exists, meets all the subscribers requirements,
        // and isn't matching any other events that we don't care about.
        static private void CreateOrModifyWatch(WatchInfo watched)
        {
            EventType new_mask = base_mask;

            foreach (WatchInternal watch in watched.Subscribers)
            {
                new_mask |= watch.Mask;
            }

            if (watched.Wd >= 0 && watched.Mask == new_mask)
            {
                return;
            }

            // We rely on the behaviour that watching the same inode twice won't result
            // in the wd value changing.
            // (no need to worry about watched_by_wd being polluted with stale watches)

            int wd = -1;

            wd = inotify_glue_watch(inotify_fd, watched.Path, new_mask);
            if (wd < 0)
            {
                string msg = String.Format("Attempt to watch {0} failed!", watched.Path);
                throw new IOException(msg);
            }
            if (watched.Wd >= 0 && watched.Wd != wd)
            {
                string msg = String.Format("Watch handle changed unexpectedly!", watched.Path);
                throw new IOException(msg);
            }

            watched.Wd   = wd;
            watched.Mask = new_mask;
        }
        public void TestWatchFunctionFailureNoModel()
        {
            var queryStringValue = "abc";
            var request          = new DefaultHttpRequest(new DefaultHttpContext())
            {
                Query = new QueryCollection
                        (
                    new System.Collections.Generic.Dictionary <string, StringValues>()
                {
                    { "not-model", queryStringValue }
                }
                        )
            };

            var logger = NullLoggerFactory.Instance.CreateLogger("Null Logger");

            WatchInfo watchInfo = new WatchInfo(new WatchRepository());
            var       response  = watchInfo.Run(request, logger);

            response.Wait();

            // Check that the response is an "Bad" response
            Assert.IsAssignableFrom <BadRequestObjectResult>(response.Result);

            // Check that the contents of the response are the expected contents
            var result = (BadRequestObjectResult)response.Result;

            Assert.Equal("Please provide a watch model in the query string or in the request body", result.Value);
        }
Exemplo n.º 13
0
        public static StatusReport GetWatchInfo(string officeId, string date)
        {
            StatusReport sr        = new StatusReport();
            string       sqlString = "select 班次ID,巡更点ID,巡更序次,开始时间 from 基础_微信巡更 " +
                                     " where 当前组织ID = @当前组织ID and 工作日期 = @工作日期 order by ID desc";
            DataTable dt = SQLHelper.ExecuteQuery("wyt", sqlString, new SqlParameter("@当前组织ID", officeId),
                                                  new SqlParameter("@工作日期", date));

            if (dt.Rows.Count == 0)
            {
                sr.status = "Fail";
                sr.result = "未查询到任何数据";
                return(sr);
            }
            List <WatchInfo> watchInfoList = new List <WatchInfo>();

            foreach (DataRow dr in dt.Rows)
            {
                WatchInfo watchInfo = new WatchInfo();
                watchInfo.frequencyId = DataTypeHelper.GetIntValue(dr["班次ID"]);
                watchInfo.pointId     = DataTypeHelper.GetIntValue(dr["巡更点ID"]);
                watchInfo.watchTimes  = DataTypeHelper.GetIntValue(dr["巡更序次"]);
                watchInfo.startTime   = DataTypeHelper.GetDateStringValue(dr["开始时间"]);
                watchInfoList.Add(watchInfo);
            }
            sr.status = "Success";
            sr.result = "成功";
            sr.data   = watchInfoList.ToArray();
            return(sr);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets the root watch.
        /// </summary>
        /// <returns>The root watch.</returns>
        private WatchInfo GetRoot()
        {
            if (((mRootWatch == null)))
            {
                mRootWatch = new WatchInfo(ROOTNAME, null);
            }

            return(mRootWatch);
        }
Exemplo n.º 15
0
        public static Watch Subscribe(string path, InotifyCallback callback, EventType mask, EventType initial_filter)
        {
            WatchInternal watch;
            WatchInfo     watched;
            EventType     mask_orig = mask;

            if (!Path.IsPathRooted(path))
            {
                path = Path.GetFullPath(path);
            }

            bool is_directory = false;

            if (Directory.Exists(path))
            {
                is_directory = true;
            }
            else if (!File.Exists(path))
            {
                throw new IOException(path);
            }

            lock (watched_by_wd) {
                watched = watched_by_path [path] as WatchInfo;

                if (watched == null)
                {
                    // We need an entirely new WatchInfo object
                    watched             = new WatchInfo();
                    watched.Path        = path;
                    watched.IsDirectory = is_directory;
                    watched.Subscribers = new ArrayList();
                    watched.Children    = new ArrayList();
                    DirectoryInfo dir = new DirectoryInfo(path);
                    if (dir.Parent != null)
                    {
                        watched.Parent = watched_by_path [dir.Parent.ToString()] as WatchInfo;
                    }
                    if (watched.Parent != null)
                    {
                        watched.Parent.Children.Add(watched);
                    }
                    watched_by_path [watched.Path] = watched;
                }

                watched.FilterMask = initial_filter;
                watched.FilterSeen = 0;

                watch = new WatchInternal(callback, mask_orig, watched);
                watched.Subscribers.Add(watch);

                CreateOrModifyWatch(watched);
                watched_by_wd [watched.Wd] = watched;
            }

            return(watch);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Clears all watches.
        /// </summary>
        public void ClearAllWatches()
        {
            if ((TurnOff))
            {
                return;
            }

            mRootWatch = null;
            mStackTable.Clear();
        }
Exemplo n.º 17
0
            /// <summary>
            /// Creates a new instance of the WatchInfo class.
            /// </summary>
            public WatchInfo(string name, WatchInfo parent)
            {
                mName   = name;
                mWatch  = new Stopwatch();
                mParent = parent;

                if (((parent != null)))
                {
                    mParent.Childs.Add(this);
                }
            }
Exemplo n.º 18
0
        // Update the watched_by_path hash and the path stored inside the watch
        // in response to a move event.
        static private void MoveWatch(WatchInfo watch, string name)
        {
            watched_by_path.Remove(watch.Path);
            watch.Path = name;
            watched_by_path [watch.Path] = watch;

            if (Verbose)
            {
                Console.WriteLine("*** inotify: Moved Watch to {0}", watch.Path);
            }
        }
Exemplo n.º 19
0
        //对目前的监视项进行保存
        private void SaveRecords()
        {
            List <WatchInfo> watches = new List <WatchInfo>();

            foreach (XWXFileSystemWatcher w in watcherList)
            {
                WatchInfo watchInfo = new WatchInfo(w.Path, w.BackupFolder, w.WatchingChangeTypes, w.IncludeSubdirectories, w.EnableRaisingEvents);
                watches.Add(watchInfo);
            }
            serializationHandler.Serialize(watches);
        }
Exemplo n.º 20
0
 // The caller has to handle all locking itself
 private static void Forget(WatchInfo watched)
 {
     if (last_watched == watched)
     {
         last_watched = null;
     }
     if (watched.Parent != null)
     {
         watched.Parent.Children.Remove(watched);
     }
     watched_by_wd.Remove(watched.Wd);
     watched_by_path.Remove(watched.Path);
 }
Exemplo n.º 21
0
        void Save(WatchInfo info)
        {
            if (info.Section != null)
            {
                watchSection.RemoveSection(info.Section);
            }
            var sect = info.Section = watchSection.CreateSection("Watch");

            sect.Attribute("Index", info.WindowIndex);
            foreach (var expr in info.Expressions)
            {
                var exprSect = sect.CreateSection("Expression");
                exprSect.Attribute("Value", expr);
            }
        }
Exemplo n.º 22
0
        // Ensure our watch exists, meets all the subscribers requirements,
        // and isn't matching any other events that we don't care about.
        private static void CreateOrModifyWatch(WatchInfo watched)
        {
            EventType new_mask = base_mask;

            foreach (WatchInternal watch in watched.Subscribers)
            {
                new_mask |= watch.Mask;
            }

            if (watched.Wd >= 0 && watched.Mask == new_mask)
            {
                return;
            }

            //Log.Debug ("{0} inotify watch on {1}", watched.Wd >= 0 ? "Recreating" : "Creating", watched.Path);

            // We rely on the behaviour that watching the same inode twice won't result
            // in the wd value changing.
            // (no need to worry about watched_by_wd being polluted with stale watches)

            int wd = -1;

            wd = inotify_glue_watch(inotify_fd, watched.Path, new_mask);
            if (wd < 0)
            {
                Mono.Unix.Native.Errno errno = Mono.Unix.Native.NativeConvert.ToErrno(-wd);

                if (!watch_limit_error_displayed && errno == Mono.Unix.Native.Errno.ENOSPC)
                {
                    Log.Error("Maximum inotify watch limit hit adding watch to {0}.  Try adjusting /proc/sys/fs/inotify/max_user_watches", watched.Path);
                    watch_limit_error_displayed = true;
                }

                string msg = String.Format("Attempt to watch {0} failed: {1}", watched.Path, Mono.Unix.UnixMarshal.GetErrorDescription(errno));
                throw new IOException(msg);
            }

            if (watched.Wd >= 0 && watched.Wd != wd)
            {
                string msg = String.Format("Watch handle changed unexpectedly!", watched.Path);
                throw new IOException(msg);
            }

            watched.Wd   = wd;
            watched.Mask = new_mask;
        }
Exemplo n.º 23
0
        // A directory we are watching has moved.  We need to fix up its path, and the path of
        // all of its subdirectories, their subdirectories, and so on.
        private static void HandleMove(string srcpath, string dstparent, string dstname)
        {
            string dstpath = Path.Combine(dstparent, dstname);

            lock (watched_by_wd) {
                WatchInfo start = watched_by_path [srcpath] as WatchInfo;                       // not the same as src!
                if (start == null)
                {
                    Logger.Log.Warn("Lookup failed for {0}", srcpath);
                    return;
                }

                // Queue our starting point, then walk its subdirectories, invoking MoveWatch() on
                // each, repeating for their subdirectories.  The relationship between start, child
                // and dstpath is fickle and important.
                Queue queue = new Queue();
                queue.Enqueue(start);
                do
                {
                    WatchInfo target = queue.Dequeue() as WatchInfo;
                    for (int i = 0; i < target.Children.Count; i++)
                    {
                        WatchInfo child = target.Children[i] as WatchInfo;
                        Logger.Log.Debug("Moving watch on {0} from {1} to {2}", child.Path, srcpath, dstpath);
                        string name = Path.Combine(dstpath, child.Path.Substring(srcpath.Length + 1));
                        MoveWatch(child, name);
                        queue.Enqueue(child);
                    }
                } while (queue.Count > 0);

                // Ultimately, fixup the original watch, too
                MoveWatch(start, dstpath);
                if (start.Parent != null)
                {
                    start.Parent.Children.Remove(start);
                }
                start.Parent = watched_by_path [dstparent] as WatchInfo;
                if (start.Parent != null)
                {
                    start.Parent.Children.Add(start);
                }
            }
        }
Exemplo n.º 24
0
        static private void SendEvent(WatchInfo watched, string filename, string srcpath, EventType mask)
        {
            // Does the watch care about this event?
            if ((watched.Mask & mask) == 0)
            {
                return;
            }

            bool isDirectory = false;

            if ((mask & EventType.IsDirectory) != 0)
            {
                isDirectory = true;
            }

            if (Verbose)
            {
                Console.WriteLine("*** inotify: {0} {1} {2} {3} {4} {5}",
                                  mask, watched.Wd, watched.Path,
                                  filename != "" ? filename : "\"\"",
                                  isDirectory == true ? "(directory)" : "(file)",
                                  srcpath != null ? "(from " + srcpath + ")" : "");
            }

            if (watched.Subscribers == null)
            {
                return;
            }

            foreach (WatchInternal watch in watched.Subscribers)
            {
                try {
                    if (watch.Callback != null && (watch.Mask & mask) != 0)
                    {
                        watch.Callback(watch, watched.Path, filename, srcpath, mask);
                    }
                } catch (Exception e) {
                    Console.Error.WriteLine("Caught exception executing Inotify callbacks");
                    Console.Error.WriteLine(e);
                }
            }
        }
Exemplo n.º 25
0
        static private void Unsubscribe(WatchInfo watched, WatchInternal watch)
        {
            watched.Subscribers.Remove(watch);

            // Other subscribers might still be around
            if (watched.Subscribers.Count > 0)
            {
                // Minimize it
                CreateOrModifyWatch(watched);
                return;
            }

            int retval = inotify_glue_ignore(inotify_fd, watched.Wd);

            if (retval < 0)
            {
                string msg = String.Format("Attempt to ignore {0} failed!", watched.Path);
                throw new IOException(msg);
            }

            Forget(watched);
            return;
        }
Exemplo n.º 26
0
        private static void Unsubscribe(WatchInfo watched, WatchInternal watch)
        {
            watched.Subscribers.Remove(watch);

            // Other subscribers might still be around
            if (watched.Subscribers.Count > 0)
            {
                // Minimize it
                CreateOrModifyWatch(watched);
                return;
            }

            int retval = inotify_glue_ignore(inotify_fd, watched.Wd);

            if (retval < 0)
            {
                Mono.Unix.Native.Errno errno = Mono.Unix.Native.NativeConvert.ToErrno(-retval);
                string msg = String.Format("Attempt to ignore {0} failed: {1}", watched.Path, Mono.Unix.UnixMarshal.GetErrorDescription(errno));
                throw new IOException(msg);
            }

            Forget(watched);
            return;
        }
Exemplo n.º 27
0
        // add <id|name> <motif> [admin] [date]"
        void AddWatch(BasePlayer parAdmin, string[] parArguments)
        {
            int argSize = parArguments.Length;

            if (argSize < 3)
            {
                DisplayUsage(parAdmin);
                return;
            }

            BasePlayer player = (BasePlayer)AshTools?.Call("GetPlayerActifOnTheServerByIdOrNameIFN", parArguments[1].ToUpper());

            if (player == null)
            {
                PrintToConsole(parAdmin, string.Format(lang.GetMessage("DoNotExists", this, parAdmin.UserIDString), parArguments[1]));
                return;
            }

            string   motif     = parArguments[2];
            ulong    adminId   = parAdmin.userID;
            string   adminName = parAdmin.displayName;
            DateTime date      = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local);

            // overwrite admin information
            bool     hasDelay      = false;
            DateTime dateWithDelay = date;

            if (argSize > 3)
            {
                float nbDay;
                if (hasDelay = float.TryParse(parArguments[3], out nbDay))
                {
                    dateWithDelay = dateWithDelay.AddDays(nbDay);
                }
            }

            // create new watch
            int maxId = 0;

            foreach (WatchInfo watch in FPlayerDatas.ToList().FindAll((p) => p.FPlayerId == player.userID))
            {
                if (watch.FWatchId > maxId)
                {
                    maxId = watch.FWatchId;
                }
            }
            WatchInfo watchInfo = new WatchInfo();

            watchInfo.FAdminId          = adminId;
            watchInfo.FAdminName        = adminName;
            watchInfo.FWatchId          = maxId + 1;
            watchInfo.FDate             = date;
            watchInfo.FDateStopWatching = dateWithDelay;
            watchInfo.FPlayerId         = player.userID;
            watchInfo.FPlayerName       = player.displayName;
            watchInfo.FPlayerNameUpper  = watchInfo.FPlayerName.ToUpper();
            watchInfo.FText             = parArguments[2];

            FPlayerDatas.Add(watchInfo);
            PrintToConsole(parAdmin, "Le joueur " + player.displayName + " est maintenant sous surveillance" + (DateTime.Compare(watchInfo.FDateStopWatching, watchInfo.FDate) > 0 ? " jusqu'au " + watchInfo.FDateStopWatching.ToString("dd/MM/yyyy HH:mm") : ""));

            // envoie un message à tout les staffs actif en jeu
            foreach (BasePlayer user in BasePlayer.activePlayerList)
            {
                if (user != parAdmin && permission.UserHasPermission(user.UserIDString, FPermission))
                {
                    PrintToChat(user, "Le joueur " + player.displayName + " a été mis sous surveillance par " + parAdmin.displayName + (watchInfo.FDateStopWatching > watchInfo.FDate ? " jusqu'au " + watchInfo.FDateStopWatching.ToString("dd/MM/yyyy HH:mm") : ""));
                }
            }
            Save();
        }
Exemplo n.º 28
0
        // Update the watched_by_path hash and the path stored inside the watch
        // in response to a move event.
        private static void MoveWatch(WatchInfo watch, string name)
        {
            lock (watched_by_wd) {

                watched_by_path.Remove (watch.Path);
                watch.Path = name;
                watched_by_path [watch.Path] = watch;
            }
        }
Exemplo n.º 29
0
        // Ensure our watch exists, meets all the subscribers requirements,
        // and isn't matching any other events that we don't care about.
        private static void CreateOrModifyWatch(WatchInfo watched)
        {
            EventType new_mask = base_mask;
            foreach (WatchInternal watch in watched.Subscribers)
                new_mask |= watch.Mask;

            if (watched.Wd >= 0 && watched.Mask == new_mask)
                return;

            // We rely on the behaviour that watching the same inode twice won't result
            // in the wd value changing.
            // (no need to worry about watched_by_wd being polluted with stale watches)

            int wd = -1;
            wd = inotify_glue_watch (inotify_fd, watched.Path, new_mask);
            if (wd < 0) {
                string msg = String.Format ("Attempt to watch {0} failed!", watched.Path);
                throw new IOException (msg);
            }
            if (watched.Wd >= 0 && watched.Wd != wd) {
                string msg = String.Format ("Watch handle changed unexpectedly!", watched.Path);
                throw new IOException (msg);
            }

            watched.Wd = wd;
            watched.Mask = new_mask;
        }
Exemplo n.º 30
0
			public WatchInternal (InotifyCallback callback, EventType mask, WatchInfo watchinfo)
			{
				this.callback = callback;
				this.mask = mask;
				this.watchinfo = watchinfo;
				this.is_subscribed = true;
			}
    /// <summary>
    /// Gets the root watch.
    /// </summary>
    /// <returns>The root watch.</returns>
    private WatchInfo GetRoot()
    {
        if (((mRootWatch == null)))
        {
            mRootWatch = new WatchInfo(ROOTNAME, null);
        }

        return mRootWatch;
    }
        /// <summary>
        /// Creates a new instance of the WatchInfo class.
        /// </summary>
        public WatchInfo(string name, WatchInfo parent)
        {
            mName = name;
            mWatch = new Stopwatch();
            mParent = parent;

            if (((parent != null)))
                mParent.Childs.Add(this);
        }
    /// <summary>
    /// Starts the current watch.
    /// If there is no current watch a new watch will be created and started.
    /// If the current watch is already running, a new watch will be created, started and added as a child,
    /// the current watch will be pushed on a stack and the created watch becomes the current watch.
    /// </summary>
    /// <param name="name">Name of the watch.</param>
    /// <param name="stopAndResetChilds">Flag for stopping and resetting all child watches of the current timer.</param>
    public void StartWatch(string name, bool stopAndResetChilds = false)
    {
        if ((TurnOff))
            return;

        if ((mStackTable.Count == 0))
        {
            mStackTable.Push(new WatchInfo(name, GetRoot()));
        }

        dynamic wInfo = (WatchInfo)mStackTable.Peek();
        if ((wInfo.IsRunning))
        {
            dynamic newWInfo = new WatchInfo(name, wInfo);
            mStackTable.Push(newWInfo);
            newWInfo.RestartWatch(stopAndResetChilds);
        }
        else
        {
            wInfo.RestartWatch(stopAndResetChilds);
        }
    }
Exemplo n.º 34
0
		// The caller has to handle all locking itself
		private static void Forget (WatchInfo watched)
		{
			if (last_watched == watched)
				last_watched = null;
			if (watched.Parent != null)
				watched.Parent.Children.Remove (watched);
			watched_by_wd.Remove (watched.Wd);
			watched_by_path.Remove (watched.Path);
		}
Exemplo n.º 35
0
			public PendingMove (WatchInfo watched, string srcname, DateTime time, uint cookie) {
				Watch = watched;
				SrcName = srcname;
				Time = time;
				Cookie = cookie;
			}
Exemplo n.º 36
0
        private static void Unsubscribe(WatchInfo watched, WatchInternal watch)
        {
            watched.Subscribers.Remove (watch);

            // Other subscribers might still be around
            if (watched.Subscribers.Count > 0) {
                // Minimize it
                CreateOrModifyWatch (watched);
                return;
            }

            int retval = inotify_glue_ignore (inotify_fd, watched.Wd);
            if (retval < 0) {
                string msg = String.Format ("Attempt to ignore {0} failed!", watched.Path);
                throw new IOException (msg);
            }

            Forget (watched);
            return;
        }
Exemplo n.º 37
0
		// Ensure our watch exists, meets all the subscribers requirements,
		// and isn't matching any other events that we don't care about.
		private static void CreateOrModifyWatch (WatchInfo watched)
		{
			EventType new_mask = base_mask;
			foreach (WatchInternal watch in watched.Subscribers)
				new_mask |= watch.Mask;

			if (watched.Wd >= 0 && watched.Mask == new_mask)
				return;

			//Log.Debug ("{0} inotify watch on {1}", watched.Wd >= 0 ? "Recreating" : "Creating", watched.Path);

			// We rely on the behaviour that watching the same inode twice won't result
			// in the wd value changing.
			// (no need to worry about watched_by_wd being polluted with stale watches)
			
			int wd = -1;
			wd = inotify_glue_watch (inotify_fd, watched.Path, new_mask);
			if (wd < 0) {
				Mono.Unix.Native.Errno errno = Mono.Unix.Native.NativeConvert.ToErrno (-wd);

				if (! watch_limit_error_displayed && errno == Mono.Unix.Native.Errno.ENOSPC) {
					Log.Error ("Maximum inotify watch limit hit adding watch to {0}.  Try adjusting /proc/sys/fs/inotify/max_user_watches", watched.Path);
					watch_limit_error_displayed = true;
				}

				string msg = String.Format ("Attempt to watch {0} failed: {1}", watched.Path, Mono.Unix.UnixMarshal.GetErrorDescription (errno));
				throw new IOException (msg);
			}

			if (watched.Wd >= 0 && watched.Wd != wd) {
				string msg = String.Format ("Watch handle changed unexpectedly!", watched.Path);	
				throw new IOException (msg);
			}

			watched.Wd = wd;
			watched.Mask = new_mask;
		}
Exemplo n.º 38
0
		private static void Unsubscribe (WatchInfo watched, WatchInternal watch)
		{
			watched.Subscribers.Remove (watch);

			// Other subscribers might still be around			
			if (watched.Subscribers.Count > 0) {
				// Minimize it
				CreateOrModifyWatch (watched);
				return;
			}

			int retval = inotify_glue_ignore (inotify_fd, watched.Wd);
			if (retval < 0) {
				Mono.Unix.Native.Errno errno = Mono.Unix.Native.NativeConvert.ToErrno (-retval);
				string msg = String.Format ("Attempt to ignore {0} failed: {1}", watched.Path, Mono.Unix.UnixMarshal.GetErrorDescription (errno));
				throw new IOException (msg);
			}

			Forget (watched);
			return;
		}
Exemplo n.º 39
0
		public static Watch Subscribe (string path, InotifyCallback callback, EventType mask, EventType initial_filter)
		{
			WatchInternal watch;
			WatchInfo watched;
			EventType mask_orig = mask;

			if (!Path.IsPathRooted (path))
				path = Path.GetFullPath (path);

			bool is_directory = false;
			if (Directory.Exists (path))
				is_directory = true;
			else if (! File.Exists (path))
				throw new IOException (path);

			lock (watched_by_wd) {
				watched = watched_by_path [path] as WatchInfo;

				if (watched == null) {
					// We need an entirely new WatchInfo object
					watched = new WatchInfo ();
					watched.Path = path;
					watched.IsDirectory = is_directory;
					watched.Subscribers = new ArrayList ();
					watched.Children = new ArrayList ();
					DirectoryInfo dir = new DirectoryInfo (path);
					if (dir.Parent != null)
						watched.Parent = watched_by_path [dir.Parent.ToString ()] as WatchInfo;
					if (watched.Parent != null)
						watched.Parent.Children.Add (watched);
					watched_by_path [watched.Path] = watched;
				}

				watched.FilterMask = initial_filter;
				watched.FilterSeen = 0;

				watch = new WatchInternal (callback, mask_orig, watched);
				watched.Subscribers.Add (watch);

				CreateOrModifyWatch (watched);
				watched_by_wd [watched.Wd] = watched;
			}

			return watch;
		}
Exemplo n.º 40
0
        //从一个WatchInfo载入一个监视项到界面中,并重现该WatchInfo的信息
        private void AddWatchItem(WatchInfo watch)
        {
            XWXFileSystemWatcher watcher = new XWXFileSystemWatcher(watch.WatchedFolder);

            watcher.BackupFolder = watch.BackupFolder;
            watcher.NotifyFilter = NotifyFilters.Security
                                   | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName
                                   | NotifyFilters.DirectoryName
                                   | NotifyFilters.Size
                                   | NotifyFilters.Attributes | NotifyFilters.CreationTime;

            watcher.OnWatchStatusChanged += new WatchStatusChangedHandler(watcher_OnWatchStatusChanged);

            //目前版本不监视删除和重命名操作
            //watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
            //watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
            if ((watch.ChangeTypes & WatcherChangeTypes.Renamed) == WatcherChangeTypes.Renamed)
            {
                watcher.Renamed            += new RenamedEventHandler(watcher_Renamed);
                watcher.WatchingChangeTypes = (watcher.WatchingChangeTypes | WatcherChangeTypes.Renamed);
            }
            if ((watch.ChangeTypes & WatcherChangeTypes.Created) == WatcherChangeTypes.Created)
            {
                watcher.Created            += new FileSystemEventHandler(watcher_Created);
                watcher.WatchingChangeTypes = (watcher.WatchingChangeTypes | WatcherChangeTypes.Created);
            }
            if ((watch.ChangeTypes & WatcherChangeTypes.Changed) == WatcherChangeTypes.Changed)
            {
                watcher.Changed            += new FileSystemEventHandler(watcher_Changed);
                watcher.WatchingChangeTypes = (watcher.WatchingChangeTypes | WatcherChangeTypes.Changed);
            }

            int rowIndex = dgrdTaskList.Rows.Add();

            dgrdTaskList.Rows[rowIndex].Cells[IDX_WATCHINGDIR].Value = watcher.Path;
            dgrdTaskList.Rows[rowIndex].Cells[IDX_BACKUPDIR].Value   = watcher.BackupFolder;
            dgrdTaskList.Rows[rowIndex].Cells[IDX_STATUS].Value      = GetWatchingStatusName(watcher.EnableRaisingEvents);
            dgrdTaskList.Rows[rowIndex].Tag = watcher;

            DataGridViewComboBoxCell cell = dgrdTaskList[IDX_CHANGETYPE, rowIndex] as DataGridViewComboBoxCell;

            cell.Items.Add("创建、修改及重命名");
            cell.Items.Add("仅创建");
            cell.Items.Add("仅修改");
            cell.Items.Add("仅重命名");
            if (watch.ChangeTypes == WatcherChangeTypes.Changed)
            {
                cell.Value = "仅修改";
            }
            else if (watch.ChangeTypes == WatcherChangeTypes.Created)
            {
                cell.Value = "仅创建";
            }
            else if (watch.ChangeTypes == WatcherChangeTypes.Renamed)
            {
                cell.Value = "仅重命名";
            }
            else
            {
                cell.Value = "创建、修改及重命名";
            }
            cell.ReadOnly = !watch.Enable;

            DataGridViewCheckBoxCell checkbox = dgrdTaskList.Rows[rowIndex].Cells[IDX_SUBDIR] as DataGridViewCheckBoxCell;

            if (checkbox != null)
            {
                checkbox.Value = watch.IncludeSubdirectories;
            }
            dgrdTaskList.Rows[rowIndex].Cells[IDX_SUBDIR].ReadOnly = !watch.Enable;

            if (watch.Enable)
            {
                watcher.StartWatch();
            }
            else
            {
                watcher.StopWatch();
            }

            //同时将该监视项添加到watcherList中
            watcherList.Add(watcher);
        }
    /// <summary>
    /// Clears all watches.
    /// </summary>
    public void ClearAllWatches()
    {
        if ((TurnOff))
            return;

        mRootWatch = null;
        mStackTable.Clear();
    }
Exemplo n.º 42
0
		// Update the watched_by_path hash and the path stored inside the watch
		// in response to a move event.
		private static void MoveWatch (WatchInfo watch, string name)		
		{
			lock (watched_by_wd) {

				watched_by_path.Remove (watch.Path);
				watch.Path = name;
				watched_by_path [watch.Path] = watch;
			}

			if (Verbose)
				Console.WriteLine ("*** inotify: Moved Watch to {0}", watch.Path);
		}
Exemplo n.º 43
0
		// Filter WatchInfo items when we do the Lookup.
		// We do the filtering here to avoid having to acquire
		// the watched_by_wd lock yet again.
		private static WatchInfo Lookup (int wd, EventType event_type)
		{
			lock (watched_by_wd) {
				WatchInfo watched;
				if (last_watched != null && last_watched.Wd == wd)
					watched = last_watched;
				else {
					watched = watched_by_wd [wd] as WatchInfo;
					if (watched != null)
						last_watched = watched;
				}

				if (watched != null && (watched.FilterMask & event_type) != 0) {
					watched.FilterSeen |= event_type;
					watched = null;
				}

				return watched;
			}
		}
Exemplo n.º 44
0
		private static void SendEvent (WatchInfo watched, string filename, string srcpath, EventType mask)
		{
			// Does the watch care about this event?
			if ((watched.Mask & mask) == 0)
				return;

			bool isDirectory = false;
			if ((mask & EventType.IsDirectory) != 0)
				isDirectory = true;

			if (Verbose) {
				Console.WriteLine ("*** inotify: {0} {1} {2} {3} {4} {5}",
						   mask, watched.Wd, watched.Path,
						   filename != "" ? filename : "\"\"",
						   isDirectory == true ? "(directory)" : "(file)",
						   srcpath != null ? "(from " + srcpath + ")" : "");
			}

			if (watched.Subscribers == null)
				return;

			foreach (WatchInternal watch in (IEnumerable) watched.Subscribers.Clone ())
				try {
					if (watch.Callback != null && (watch.Mask & mask) != 0)
						watch.Callback (watch, watched.Path, filename, srcpath, mask);
				} catch (Exception e) {
					Logger.Log.Error (e, "Caught exception executing Inotify callbacks");
				}
		}
Exemplo n.º 45
0
        private static void SendEvent(WatchInfo watched, string filename, string srcpath, EventType mask)
        {
            // Does the watch care about this event?
            if ((watched.Mask & mask) == 0)
                return;

            if (watched.Subscribers == null)
                return;

            foreach (WatchInternal watch in watched.Subscribers)
                try {
                    if (watch.Callback != null && (watch.Mask & mask) != 0)
                        watch.Callback (watch, watched.Path, filename, srcpath, mask);
                } catch (Exception e) {
                    Daemon.LogError ("Exception in inotify callback", e);
                }
        }