Inheritance: MonoBehaviour
Exemple #1
0
		public static FileChecker TryCreate(ReadedFileInfo fileInfo, WatchMode watch, TimeSpan? delay, CheckMode check)
		{
			switch (watch)
			{
				case WatchMode.None:
					return null;

				case WatchMode.Time:
					if (delay == null)
						throw new ArgumentNullException("delay");
					return new PeriodicFileChecker(fileInfo, delay.Value, check);

				case WatchMode.Auto:
					try
					{
						return new WatchedFileChecker(fileInfo, delay, check);
					}
					catch (Exception)
					{
						if (delay == null)
							throw;
					}
					return new PeriodicFileChecker(fileInfo, delay.Value, check);

				case WatchMode.System:
					return new WatchedFileChecker(fileInfo, delay, check);

				default:
					throw new ArgumentOutOfRangeException("unexpected mode");
			}
		}
        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;

            if (CheckMode.Equals("number") && appDelegate.Edited == true)
            {
                if (SelectedRowCountArr.Count == 0)
                {
                    this.UpdateInfoWithMaxCountNum1Num2Num3(MaxCount, "0", "0", "0");
                }
                else if (SelectedRowCountArr.Count == 1)
                {
                    this.UpdateInfoWithMaxCountNum1Num2Num3(MaxCount, SelectedRowCountArr[0].ToString(), "", "");
                }
                else if (SelectedRowCountArr.Count == 2)
                {
                    this.UpdateInfoWithMaxCountNum1Num2Num3(MaxCount, SelectedRowCountArr[0].ToString(), SelectedRowCountArr[1].ToString(), "");
                }
                else
                {
                    this.UpdateInfoWithMaxCountNum1Num2Num3(MaxCount, SelectedRowCountArr[0].ToString(), SelectedRowCountArr[1].ToString(), SelectedRowCountArr[2].ToString());
                }
            }
        }
Exemple #3
0
        public void ChangeByte(CheckMode checkMode, bool expectedEvent)
        {
            string file = Path.GetTempFileName();

            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));
            var m        = createChecker(fileInfo, checkMode);
            var wait     = new ManualResetEvent(false);

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(400);
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    fs.Position = 2;
                    fs.WriteByte(1);
                    fs.Close();
                }
            }, TaskCreationOptions.LongRunning);

            Assert.AreEqual(expectedEvent, wait.WaitOne(700), "700 ms elapsed");
        }
        public void ChangeLength(CheckMode checkMode)
        {
            string file = Path.GetTempFileName();
            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));
            var m = createChecker(fileInfo, checkMode);
            var wait = new ManualResetEvent(false);
            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(400);
                using (var fs = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                {
                    fs.Position = 3;
                    fs.WriteByte(1);
                    fs.Close();
                };
            }, TaskCreationOptions.LongRunning);

            Assert.IsTrue(wait.WaitOne(700), "700 sec elapsed");

            wait.Reset();

            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Assert.IsTrue(wait.WaitOne(100), "100 sec elapsed");
        }
Exemple #5
0
        static void Main(string[] args)
        {
            //args = "-parse -path /Users/mask/Downloads/playlists/parse/".Split(' ');
            //args = "-check".Split(' ');
            args = "-export -path /Users/mask/Downloads/playlists/out_playlist.m3u".Split(' ');

            if (args == null || args.Length == 0)
            {
                return;
            }

            // get app mode
            AppMode mode = null;

            if (args.Contains("-parse"))
            {
                mode = new ParserMode(args);
            }
            else if (args.Contains("-groups"))
            {
                mode = new GroupsMode(args);
            }
            else if (args.Contains("-check"))
            {
                mode = new CheckMode(args);
            }
            else if (args.Contains("-export"))
            {
                mode = new ExportMode(args);
            }

            mode?.Run();
        }
Exemple #6
0
        public bool CheckRevision(string revision, CheckMode mode, bool mute = false)
        {
            if (mode == CheckMode.NOTHING)
            {
                return(true);
            }

            using (var s = data.OpenSession())
            {
                if (!mute)
                {
                    var revisionNumber = s.Get <Commit>()
                                         .Single(x => x.Revision == revision)
                                         .Number;
                    OnCheckRevision?.Invoke(GetRevisionName(revision, revisionNumber));
                }
                var filesToCheck = s.SelectionDSL()
                                   .Commits().RevisionIs(revision)
                                   .Files().Reselect(
                    e => mode == CheckMode.TOUCHED ? e.TouchedInCommits() : e)
                                   .ExistInRevision(revision)
                                   .ToArray();

                var result = true;
                foreach (var file in filesToCheck)
                {
                    result &= CheckLinesContent(s, revision, file);
                }
                return(result);
            }
        }
Exemple #7
0
        public DataChannel(
            short channelID,
            QosType qos,
            Compression compression,
            Encryption encryption,
            ReceivedHandler onReceived,
            CheckMode checkMode = CheckMode.Sequre
            )
        {
            ChannelID   = channelID;
            Qos         = qos;
            Compression = compression;
            Encryption  = encryption;

            OnReceived += onReceived;

            CheckMode = checkMode;

            converter = DataSerializer.GetConverter(typeof(T));

            if (Compression == Compression.LZ4)
            {
                byteArrayConverter = DataSerializer.GetConverter(typeof(byte[]));
            }

            if (Encryption == Encryption.Rsa || Encryption == Encryption.Aes)
            {
                encArrayConverter = DataSerializer.GetConverter(typeof(byte[]));
            }
        }
Exemple #8
0
        protected async Task <bool> checkFile(CheckMode check)
#endif
        {
            lock (_sync)
                if (_disposed)
                {
                    return(false);
                }

            if (_fileInfo.WasChanged(check.HasFlag(CheckMode.Attr)))
            {
                return(true);
            }

            if (check.HasFlag(CheckMode.Hash))
            {
#if NET40
                if (_fileInfo.WasHashChanged())
#else
                if (await _fileInfo.WasHashChanged().ConfigureAwait(false))
#endif
                { return(true); }
            }

            return(false);
        }
        public static Validator GetValidator(CheckMode checkMode, Package package, params object[] auxParams)
        {
            if (checkMode == CheckMode.Existing)
            {
                return(new ExistenceValidator(package));
            }
            if (checkMode == CheckMode.FileExisting)
            {
                return(new FileExistenceValidator(package));
            }
            if (checkMode == CheckMode.ValueIsNumber)
            {
                return(new NumberValidator(package));
            }
            if (checkMode == CheckMode.ValueIsNotEmptyString)
            {
                return(new StringValidator(package));
            }
            if (checkMode == CheckMode.ValueIsInRange)
            {
                var bounds = auxParams.Cast <int>().ToArray();
                return(new RangeValidator(package, bounds[0], bounds[1]));
            }

            if (checkMode == CheckMode.ValueIsInCollection)
            {
                return(new CollectionValidator(package, auxParams.Cast <string>().ToArray()));
            }

            if (checkMode == CheckMode.FileRangeExisting)
            {
                return(new FileRangeValidator(package, (string)auxParams[0]));
            }
            return(null);
        }
Exemple #10
0
 public LayerProperties(string name, string tag, CheckMode checkMode, bool isExclusive, string metaDataUrl)
 {
     Name        = name;
     Tag         = tag;
     CheckMode   = checkMode;
     IsExclusive = isExclusive;
     MetaDataUrl = metaDataUrl;
 }
Exemple #11
0
        private static TestCaseData createData(string checkerName, TimeSpan delay, CheckMode mode, params string[] workflow)
        {
            Func <ReadedFileInfo, IChangeable> checkerCreator = fi => checkerCreatorByName(checkerName, fi, delay, mode);
            var name = string.Format("{0} Delay: {1} Mode: {2} Workflow: {3}",
                                     checkerName, delay, mode, string.Join("-", workflow));

            return(new TestCaseData(checkerCreator, workflow).SetName(name));
        }
        public ICheckModeDescriptor GetDescriptorFor(CheckMode checkMode)
        {
            if (!CheckModes.TryGetValue(checkMode, out var checkModeRules))
            {
                throw new ArgumentException($"Check mode {checkMode} nas no one rule", nameof(checkModeRules));
            }

            return(new CheckModeDescriptor(checkMode, checkModeRules));
        }
Exemple #13
0
        public IChangeable createChecker(ReadedFileInfo fileInfo, CheckMode checkMode)
        {
            if (_fromConfig)
            {
                string modeText;
                if (_monitorType == "Periodic")
                {
                    modeText = "Time";
                }
                else if (_monitorType == "Watched")
                {
                    modeText = "System";
                }
                else
                {
                    throw new NotImplementedException();
                }

                string checkText = "None";
                if (checkMode.HasFlag(CheckMode.Hash))
                {
                    checkText = "Hash";
                }
                if (checkMode.HasFlag(CheckMode.Attr))
                {
                    if (checkText == "None")
                    {
                        checkText = "Attr";
                    }
                    else
                    {
                        checkText += ",Attr";
                    }
                }

                var settings = string.Format(_xmlFormat, modeText, checkText).ToXmlSettings();

                return(FileChecker.TryCreate(settings, fileInfo));
            }
            else
            {
                if (_monitorType == "Periodic")
                {
                    return(new PeriodicFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode));
                }

                if (_monitorType == "Watched")
                {
                    return(new WatchedFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode));
                }
            }

            throw new NotImplementedException();
        }
		public PeriodicFileChecker(ReadedFileInfo fileInfo, TimeSpan delay, CheckMode checkMode)
			: base(fileInfo)
		{
			if (delay <= TimeSpan.FromMilliseconds(1))
				throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");

			_delay = delay;
			_checkMode = checkMode;
			_cts = new CancellationTokenSource();
			Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking.");
		}
        public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
        {
            if (CheckMode.Equals("number"))
            {
                var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
                appDelegate.Edited = true;

                SelectedRowCountArr.RemoveAt(indexPath.Row);
                this.TableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
            }
        }
 public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
 {
     if (CheckMode.Equals("number"))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
		public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan? delay, CheckMode checkMode)
			: base(fileInfo)
		{
			_delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60));

			if (_delay <= TimeSpan.FromMilliseconds(1))
				throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");

			_fileInfo = fileInfo;
			_checkMode = checkMode;
			_watcher = createWatch();
			Task.Run(() => checkLoop()).ThrowUnhandledException("Error while file checking.");
		}
        private static List <T> CreateInstances <T>(CheckMode mode)
        {
            var result = new List <T>();

            ForEachType(mode, typeof(T), (Type type) => {
                T instance = Factory.Create <T>(type);
                if (instance != null)
                {
                    result.Add(instance);
                }
            });
            return(result);
        }
 public override nint RowsInSection(UITableView tableView, nint section)
 {
     if (CheckMode.Equals("count"))
     {
         return(CountArray.Count);
     }
     else if (CheckMode.Equals("number"))
     {
         return(SelectedRowCountArr.Count);
     }
     else
     {
         return(0);
     }
 }
        public override void RowDeselected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);
            var cell = tableView.CellAt(indexPath);

            if (CheckMode.Equals("count"))
            {
                cell.Accessory = UITableViewCellAccessory.None;
            }
            else if (CheckMode.Equals("number"))
            {
                cell.Accessory = UITableViewCellAccessory.None;
                arrayToDelete.Remove(SelectedRowCountArr[indexPath.Row]);
            }
        }
Exemple #21
0
        public DataChannel(
            short channelID, QosType qos, Compression compression, ReceivedHandler onReceived, CheckMode checkMode = CheckMode.Sequre
            )
        {
            ChannelID   = channelID;
            Qos         = qos;
            Compression = compression;

            OnReceived += onReceived;

            CheckMode = checkMode;

            converter    = DataSerializer.GetConverter(typeof(T));
            lz4converter = DataSerializer.GetConverter(typeof(byte[]));
        }
    void SetMode(CheckMode mode)
    {
        switch (mode)
        {
        case CheckMode.Freq:
            m_checkMode         = CheckMode.Freq;
            modeButtonText.text = "F";
            break;

        case CheckMode.Volume:
            m_checkMode         = CheckMode.Volume;
            modeButtonText.text = "V";
            break;
        }
    }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.CellAt(indexPath);

            if (CheckMode.Equals("count"))
            {
                cell.Accessory = UITableViewCellAccessory.Checkmark;

                this.UpdateInfoWithMaxCountNum1Num2Num3(Convert.ToInt16(CountArray[indexPath.Row]), SelectedRowCountArr[0].ToString(), SelectedRowCountArr[1].ToString(), SelectedRowCountArr[2].ToString());
                this.NavigationController.PopViewController(true);
            }
            else if (CheckMode.Equals("number"))
            {
                arrayToDelete.Add(SelectedRowCountArr[indexPath.Row]);
            }
        }
Exemple #24
0
        public void Check(int revisionsToSkip, CheckMode mode)
        {
            var revisions = data.UsingSession(s => s.Get <Commit>()
                                              .OrderBy(x => x.Number)
                                              .Skip(revisionsToSkip)
                                              .Select(c => c.Revision)
                                              .ToArray());

            foreach (var r in revisions)
            {
                if (!CheckRevision(r, mode))
                {
                    return;
                }
            }
        }
Exemple #25
0
        /// <summary>
        /// 初始化.
        /// </summary>
        public override void Clear()
        {
            base.Clear();

            buildName      = null;
            fileSuffix     = null;
            checkMode      = CheckMode.CustomMd5;
            buildTarget    = null;
            appVersion     = null;
            compressFormat = CompressFormat.None;
            manifestUpload = false;
            targets.Clear();

#if UNITY_EDITOR
            uploadWay = UploadWay.Default;
#endif
        }
Exemple #26
0
		protected async Task<bool> checkFile(CheckMode check)
		{
			lock(_sync)
				if (_disposed)
					return false;

			if (_fileInfo.WasChanged(check.HasFlag(CheckMode.Attr)))
				return true;

			if (check.HasFlag(CheckMode.Hash))
			{
				if (await _fileInfo.WasHashChanged().ConfigureAwait(false))
					return true;
			}

			return false;
		}
Exemple #27
0
        public PeriodicFileChecker(ReadedFileInfo fileInfo, TimeSpan delay, CheckMode checkMode)
            : base(fileInfo)
        {
            if (delay <= TimeSpan.FromMilliseconds(1))
            {
                throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");
            }

            _delay     = delay;
            _checkMode = checkMode;
            _cts       = new CancellationTokenSource();

#if NET40
            Task.Factory.StartNew(checkLoop, TaskCreationOptions.LongRunning).ThrowUnhandledException(MsgErrorWhileFileChecking);
#else
            Task.Run(() => checkLoop()).ThrowUnhandledException(MsgErrorWhileFileChecking);
#endif
        }
        public WatchedFileChecker(ReadedFileInfo fileInfo, TimeSpan?delay, CheckMode checkMode)
            : base(fileInfo)
        {
            _delay = delay.GetValueOrDefault(TimeSpan.FromSeconds(5 * 60));

            if (_delay <= TimeSpan.FromMilliseconds(1))
            {
                throw new ArgumentOutOfRangeException("delay should be greater of 1 ms");
            }

            _fileInfo  = fileInfo;
            _checkMode = checkMode;
            _watcher   = createWatch();
#if NET40
            Task.Factory.StartNew(checkLoop, TaskCreationOptions.LongRunning).ThrowUnhandledException(MsgErrorWhileFileChecking);
#else
            Task.Run(() => checkLoop()).ThrowUnhandledException(MsgErrorWhileFileChecking);
#endif
        }
        private static bool IsValidType(CheckMode mode, Type baseType, Type type)
        {
            if (type == null || baseType == null)
            {
                return(false);
            }
            switch (mode)
            {
            case CheckMode.SubClass:
                return(type.IsSubclassOf(baseType));

            case CheckMode.Interface:
                return(type.GetInterfaces().Contains(baseType));

            case CheckMode.Assignable:
                return(baseType.IsAssignableFrom(type));
            }
            return(false);
        }
        private static void ForEachType(CheckMode mode, Type baseType, Action <Type> callback)
        {
            Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly asm in asms)
            {
                Type[] types = asm.GetTypes();

                foreach (Type type in types)
                {
                    if (type.IsAbstract)
                    {
                        continue;
                    }
                    if (!IsValidType(mode, baseType, type))
                    {
                        continue;
                    }

                    callback(type);
                }
            }
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.DequeueReusableCell("Cell", indexPath);

            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
            cell.Accessory      = UITableViewCellAccessory.None;
            if (CheckMode.Equals("count"))
            {
                cell.SelectionStyle = UITableViewCellSelectionStyle.Default;
                cell.TextLabel.Text = String.Format("{0}개", CountArray[indexPath.Row].ToString());
                if (Convert.ToInt32(MaxCount) == Convert.ToInt32(CountArray[indexPath.Row]))
                {
                    cell.Accessory = UITableViewCellAccessory.Checkmark;
                }
            }
            else if (CheckMode.Equals("number"))
            {
                cell.TextLabel.Text = String.Format("{0}", SelectedRowCountArr[indexPath.Row]);
            }

            return(cell);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;

            MaxCount = appDelegate.UserInfo.maxSelectNumber;

            EditCheck = false;

            if (CheckMode.Equals("number"))
            {
                numbersData = new ArrayList();

                for (int i = 1; i < 46; i++)
                {
                    var temp = String.Format("{0}", i);
                    numbersData.Add(temp);
                }

                arrayToDelete = new ArrayList();
                if (SelectedRowCountArr == null)
                {
                    SelectedRowCountArr = new ArrayList();
                }

                //var newAddButton = new UIBarButtonItem("추가", UIBarButtonItemStyle.Plain, this, new ObjCRuntime.Selector("Add"));
                var newAddButton = new UIBarButtonItem("추가", UIBarButtonItemStyle.Plain, Add);

                this.NavigationItem.RightBarButtonItem = newAddButton;
                this.NavigationItem.Title = "고정번호선택";
            }
            else if (CheckMode.Equals("count"))
            {
                this.NavigationItem.Title = "번호생성갯수";
            }
        }
        /// <summary>
        /// Get suggestions asynchronous.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="preContextText">The pre context text.</param>
        /// <param name="postContextText">The post context text.</param>
        /// <returns>
        /// SpellCheckResult object.
        /// </returns>
        /// <exception cref="ClientException"></exception>
        /// <exception cref="ErrorResponse"></exception>
        /// <exception cref="ClientError"></exception>
        public async Task<SpellCheckResult> GetSuggestionsAsync(string text, string preContextText = null, string postContextText = null, CheckMode checkMode = CheckMode.Proof)
        {
            var queryStrings = new List<KeyValuePair<string, string>>();
            queryStrings.Add(new KeyValuePair<string, string>("text", text));
            if (!String.IsNullOrWhiteSpace(preContextText))
            {
                queryStrings.Add(new KeyValuePair<string, string>("PreContextText", preContextText));
            }

            if (!String.IsNullOrWhiteSpace(postContextText))
            {
                queryStrings.Add(new KeyValuePair<string, string>("PostContextText", postContextText));
            }

            var content = new FormUrlEncodedContent(queryStrings);
            string mode = null;
            switch (checkMode)
            {
                case CheckMode.Proof:
                    mode = "proof";
                    break;
                case CheckMode.Spell:
                    mode = "spell";
                    break;
            }

            var response = httpClient.PostAsync("SpellCheck?mode=" + mode, content).Result;

            if (response.IsSuccessStatusCode)
            {
                string responseContent = null;
                if (response.Content != null)
                {
                    responseContent = await response.Content.ReadAsStringAsync();
                }

                if (!String.IsNullOrWhiteSpace(responseContent))
                {
                    return JsonConvert.DeserializeObject<SpellCheckResult>(responseContent, settings);
                }
            }
            else
            {
                if (response.Content != null && response.Content.Headers.ContentType.MediaType.Contains("application/json"))
                {
                    var errorObjectString = await response.Content.ReadAsStringAsync();
                    ErrorResponse errorCollection = JsonConvert.DeserializeObject<ErrorResponse>(errorObjectString);
                    if (errorCollection != null && errorCollection.Errors != null)
                    {
                        throw new ClientException(errorCollection, response.StatusCode);
                    }
                    else
                    {
                        ClientError error = JsonConvert.DeserializeObject<ClientError>(errorObjectString);

                        if (error != null)
                        {
                            throw new ClientException(
                                new ErrorResponse()
                                {
                                    Errors = new ClientError[1] 
                                    { 
                                        new ClientError()
                                        { 
                                            Code = error.Code, 
                                            Message = error.Message
                                        }
                                    }
                                },
                                response.StatusCode);
                        }
                    }
                }

                response.EnsureSuccessStatusCode();
            }

            return null;
        }
Exemple #34
0
 public LicenseAttribute(CheckMode mode)
 {
     _checkMode = mode;
 }
        public void ChangeWriteTime(CheckMode checkMode, bool expectedEvent)
        {
            string file = Path.GetTempFileName();
            File.WriteAllBytes(file, new byte[] { 1, 2, 3 });

            var fileInfo = ReadedFileInfo.Create(file, _ => _.CopyTo(Stream.Null));
            var m = createChecker(fileInfo, checkMode);
            var wait = new ManualResetEvent(false);
            m.Changed += (a, e) =>
            {
                wait.Set();
            };

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(200);
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    fs.Position = 1;
                    fs.WriteByte(2);
                    fs.Close();
                };
            }, TaskCreationOptions.LongRunning);

            Assert.AreEqual(expectedEvent, wait.WaitOne(500));
        }
        public IChangeable createChecker(ReadedFileInfo fileInfo, CheckMode checkMode)
        {
            if (_fromConfig)
            {
                string modeText;
                if (_monitorType == "Periodic")
                    modeText = "Time";
                else if(_monitorType == "Watched")
                    modeText = "System";
                else
                    throw new NotImplementedException();

                string checkText = "None";
                if(checkMode.HasFlag(CheckMode.Hash))
                    checkText = "Hash";
                if(checkMode.HasFlag(CheckMode.Attr))
                {
                    if(checkText == "None")
                        checkText = "Attr";
                    else
                        checkText += ",Attr";
                }

                var settings = string.Format(_xmlFormat, modeText, checkText).ToXmlSettings();

                return FileChecker.TryCreate(settings, fileInfo);
            }
            else
            {
                if (_monitorType == "Periodic")
                    return new PeriodicFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode);

                if (_monitorType == "Watched")
                    return new WatchedFileChecker(fileInfo, TimeSpan.FromMilliseconds(100), checkMode);
            }

            throw new NotImplementedException();
        }
Exemple #37
0
        private static IChangeable checkerCreatorByName(string name, ReadedFileInfo fi, TimeSpan delay, CheckMode mode)
        {
            switch (name)
            {
            case "PeriodicFileChecker":
                return(new PeriodicFileChecker(fi, delay, mode));

            case "WatchedFileChecker":
                return(new WatchedFileChecker(fi, delay, mode));

            default:
                throw new NotSupportedException();
            }
        }
Exemple #38
0
        /// <summary>
        /// Returns the index of the last instruction in targetSquence, or -1 if not found
        /// </summary>
        /// <param name="instructions"></param>
        /// <param name="targetSequence"></param>
        /// <param name="checkMode"></param>
        /// <param name="showDebugOutput"></param>
        /// <returns></returns>
        public static int FindSequence(IEnumerable <CodeInstruction> instructions, IEnumerable <CodeInstruction> targetSequence, CheckMode checkMode = CheckMode.ALWAYS, bool showDebugOutput = false)
        {
            List <CodeInstruction> Instructions = instructions.ToList();

            CodeInstruction targetStart = targetSequence.ElementAt(0);
            int             targetSize  = targetSequence.Count();

            for (int i = 0; i < Instructions.Count; i++)
            {
                bool targetSequenceStillFits = i + targetSize <= Instructions.Count;

                if (targetSequenceStillFits)
                {
                    bool foundTargetSequence = true;

                    for (int x = 0; x < targetSize && foundTargetSequence; x++)
                    {
                        foundTargetSequence = Instructions[i + x].opcode.Equals(targetSequence.ElementAt(x).opcode);
                        if (checkMode != CheckMode.NEVER) //check that target sequence matches.
                        {
                            foundTargetSequence = foundTargetSequence &&
                                                  (
                                (Instructions[i + x].operand == null || checkMode == CheckMode.NONNULL) && targetSequence.ElementAt(x).operand == null ||
                                Instructions[i + x].operand.Equals(targetSequence.ElementAt(x).operand)
                                                  );
                        }

                        if (showDebugOutput && foundTargetSequence)
                        {
                            Logger.Info($"Found {targetSequence.ElementAt(x).opcode} at {i + x}");
                        }
                    }

                    if (foundTargetSequence)
                    {
                        return(i + targetSize);
                    }
                }
                else
                {
                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine($"Couldn't find target sequence.  This might be okay in certain cases.");

                    // Cut down the stack trace because it's 20 lines of unhelpful reflection internals.
                    // Show enough to figure out which mod + transpiler method is causing this:
                    sb.AppendLine($"Stack Trace:");
                    string[] stackTrace = new System.Diagnostics.StackTrace().ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    for (int lineNumber = 0; lineNumber < 2; lineNumber++)
                    {
                        sb.AppendLine(stackTrace[lineNumber]);
                    }

                    Logger.Info(sb.ToString());
                    break;
                }
            }

            return(-1);
        }
Exemple #39
0
 public LayerProperties(string name, string tag, CheckMode checkMode, bool isExclusive, string metaDataUrl)
 {
   Name = name;
   Tag = tag;
   CheckMode = checkMode;
   IsExclusive = isExclusive;
   MetaDataUrl = metaDataUrl;
 }