コード例 #1
0
 public static void GetArray(int[,] array)
 {
     for (int i = 0; i < array.GetLength(0); i++)
     {
         for (int j = 0; j < array.GetLength(1); j++)
         {
             Console.Write($"{array[i, j]}\t");
         }
         NewLine?.Invoke();
     }
 }
コード例 #2
0
 public static void Write(string log)
 {
     m_consoleLogList.Enqueue(log);
     if (m_curConsoleTask == null)
     {
         lock (m_consoleObj)
         {
             if (m_curConsoleTask == null)
             {
                 m_curConsoleTask = m_taskFactory.StartNew(() => DoWriteConsole());
             }
         }
     }
     NewLine?.Invoke(null, new NewLineEventArgs(log));
 }
コード例 #3
0
        private void ReadWatchedFiles()
        {
            void ParsePendingText(String fileName, StreamingContext context)
            {
                foreach (var line in context.ReadPendingText(cancellationTokenSource.Token))
                {
                    NewLine?.Invoke(fileName, line);
                }
            }

            logger.Debug("Reading and parsing current file contents...");
            var readLineTasks = watchedFiles.Select(kvp =>
                                                    Task.Run(() => ParsePendingText(kvp.Key, kvp.Value))
                                                    ).ToList();

            using (new Profiler("Read initial file contents", logger))
            {
                var waitTask = Task.WhenAll(readLineTasks.ToArray());
                while (!waitTask.IsCompleted)
                {
                    Task.Delay(10);
                }
            }

            logger.Debug("Read tasks finished");

            if (cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            var archiveFiles = watchedFiles.Keys.Where(IsArchivedFile).ToList();

            logger.Debug("Removing {count} archives from set of watched files...", archiveFiles.Count);
            foreach (var file in archiveFiles)
            {
                watchedFiles.Remove(file, out StreamingContext _);
            }

            using (new Profiler("Running GC for cleaned streams", logger))
                GC.Collect(2, GCCollectionMode.Forced, true, true);

            logger.Debug("Enabling FS watcher");
            this.logFolderWatcher.EnableRaisingEvents = true;
        }
コード例 #4
0
        private void Watch()
        {
            using FileStream fs   = new(LogFullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using StreamReader sr = new(fs);
            string streamLine;

            while (Running)
            {
                streamLine = sr.ReadLine();
                if (streamLine != null)
                {
                    NewLine?.Invoke(this, new LogLineArgs(streamLine));
                }
                else
                {
                    Thread.Sleep(1);
                }
            }
        }
コード例 #5
0
        void LogFolderWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            logger.Verbose("File {name} changed, checking for updates...", e.Name);

            lock (watchedFiles)
                if (!watchedFiles.ContainsKey(e.FullPath))
                {
                    return;
                }

            var context = watchedFiles[e.FullPath];

            Task.Run(() =>
            {
                using (new JobContext(this))
                {
                    foreach (var line in context.ReadPendingText(cancellationTokenSource.Token))
                    {
                        NewLine?.Invoke(e.FullPath, line);
                    }
                }
            });
        }
コード例 #6
0
        // Derived from MimeKit's MimeParser
        private static long ReadOrCountLines(Stream stream, Encoding encoding, byte[] workingBuffer, NewLine onNewLine,
                                             CancellationToken cancellationToken, IMetricsHost metrics)
        {
            var count       = 0L;
            var offset      = stream.CanSeek ? stream.Position : 0L;
            var from        = Constants.ReadAheadSize;
            var to          = Constants.ReadAheadSize;
            var endOfStream = false;

            var preamble = encoding.GetPreambleBuffer();

            unsafe
            {
                fixed(byte *buffer = workingBuffer)
                {
                    if (stream.CanSeek && stream.Position != offset)
                    {
                        stream.Seek(offset, SeekOrigin.Begin);
                    }

                    if (!ReadPreamble(stream, preamble, buffer, workingBuffer, ref from, ref to, ref endOfStream,
                                      cancellationToken))
                    {
                        throw new FormatException(ErrorStrings.UnexpectedEndOfStream);
                    }

                    do
                    {
                        if (ReadAhead(stream, workingBuffer, Constants.ReadAheadSize, 2, ref from, ref to,
                                      ref endOfStream,
                                      cancellationToken) <= 0)
                        {
                            break;
                        }

                        var position   = buffer + from;
                        var end        = buffer + to;
                        var startIndex = from;

                        *end = (byte)'\n';

                        while (position < end)
                        {
                            var alignment = (startIndex + 3) & ~3;
                            var aligned   = buffer + alignment;
                            var start     = position;
                            var c         = *aligned;

                            *aligned = Constants.LineFeed;
                            while (*position != Constants.LineFeed)
                            {
                                position++;
                            }

                            *aligned = c;

                            if (position == aligned && c != Constants.LineFeed)
                            {
                                var  dword = (uint *)position;
                                uint mask;
                                do
                                {
                                    mask = *dword++ ^ 0x0A0A0A0A;
                                    mask = (mask - 0x01010101) & ~mask & 0x80808080;
                                } while (mask == 0);

                                position = (byte *)(dword - 1);
                                while (*position != Constants.LineFeed)
                                {
                                    position++;
                                }
                            }

                            var length = (int)(position - start);

                            if (position < end)
                            {
                                length++;
                                position++;
                                count++;

                                BytesPerSecond(metrics, length);
                                onNewLine?.Invoke(count, false, start, length, encoding, metrics);
                            }
                            else if (count == 0 && position == end)
                            {
                                BytesPerSecond(metrics, length);
                                onNewLine?.Invoke(count, false, start, length, encoding, metrics);
                                return(1);
                            }
                            else
                            {
                                // line spans across the read-ahead buffer
                                BytesPerSecond(metrics, length);
                                onNewLine?.Invoke(count, true, start, length, encoding, metrics);
                            }

                            startIndex += length;
                        }

                        from = startIndex;
                    } while (true);
                }
            }

            return(count);
        }
コード例 #7
0
 protected void OnNewLine()
 {
     NewLine?.Invoke();
 }
コード例 #8
0
ファイル: Parser.cs プロジェクト: dlebansais/PgChatParser
 private void ParseLine(DateTime logTime, string logLine)
 {
     NewLine?.Invoke(this, logTime, logLine);
 }
コード例 #9
0
ファイル: Logic.cs プロジェクト: whistyun/MultiRept
        /// <summary>
        /// 置換処理
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="keyword"></param>
        private void TryReplace(string filepath, Encoding encoding, List <ReplaceParameter> keywords)
        {
            var replaceOcc = false;
            // 出力先
            var output = Path.GetTempFileName();

            if (encoding == null)
            {
                var detector = new CodeDetector();
                encoding = detector.Check(new FileInfo(filepath));
            }

            if (encoding != null)
            {
                using (var reader = new StreamReader(filepath, encoding, false, 1024 * 20))
                    using (var writer = new StreamWriter(output, false, encoding, 1024 * 20))
                    {
                        int           lineCnt = 0;
                        string        lnCd;
                        string        line;
                        StringBuilder newLine = new StringBuilder();
                        while ((line = reader.ReadLine(out lnCd)) != null)
                        {
                            lineCnt++;
                            bool findMatch = false;
                            int  startAt   = 0;

                            do
                            {
                                //置換対象キーワードを含んでいるか?
                                var hitKeyAndMatch =
                                    // 全てのキーワードについて検索
                                    keywords.Select(keyword => Tuple.Create(
                                                        keyword,
                                                        keyword.ReplaceFromPattern.Matches(line, startAt)
                                                        .Cast <Match>().Where(m => m.Success && m.Length != 0)
                                                        .OrderBy(m => m.Index)
                                                        .FirstOrDefault()
                                                        ))
                                    .Where(regres => regres.Item2 != null && regres.Item2.Success && regres.Item2.Length != 0)
                                    // 最初にヒットしたものを対象とする
                                    .OrderBy(regres => regres.Item2.Index)
                                    .FirstOrDefault();

                                if (hitKeyAndMatch != null)
                                {
                                    findMatch = true;

                                    var hitKey = hitKeyAndMatch.Item1;
                                    var match  = hitKeyAndMatch.Item2;

                                    replaceOcc = true;

                                    // ヒット位置より前の文字をそのままコピー
                                    var beforeText = line.Substring(0, match.Index);
                                    newLine.Append(beforeText);

                                    var bgnIdx = startAt;
                                    var endIdx = match.Index;
                                    if (bgnIdx != endIdx)
                                    {
                                        if (AddPlain != null)
                                        {
                                            AddPlain.Invoke(line.Substring(bgnIdx, endIdx - bgnIdx));
                                        }
                                    }

                                    int newLineLength = newLine.Length;

                                    // ヒット位置の文字を置換後の文字に変更
                                    foreach (ExtendReplaceTo rep in hitKey.ReplaceToPattern)
                                    {
                                        if (rep.Type == ReplaceToType.Plain)
                                        {
                                            newLine.Append(rep.Label);
                                        }
                                        else
                                        {
                                            Group group = rep.Type == ReplaceToType.GroupIndex ?
                                                          match.Groups[rep.Index] :
                                                          match.Groups[rep.Label];

                                            string value = group.Value;

                                            switch (rep.Change)
                                            {
                                            case ChangeCase.LowerHead:
                                                value = Char.ToLower(value[0]) + value.Substring(1);
                                                break;

                                            case ChangeCase.LowerAll:
                                                value = value.ToLower();
                                                break;

                                            case ChangeCase.UpperHead:
                                                value = Char.ToUpper(value[0]) + value.Substring(1);
                                                break;

                                            case ChangeCase.UpperAll:
                                                value = value.ToUpper();
                                                break;
                                            }
                                            newLine.Append(value);
                                        }
                                    }

                                    if (AddDiff != null)
                                    {
                                        AddDiff.Invoke(
                                            match.Groups[0].Value,
                                            newLine.ToString().Substring(newLineLength));
                                    }

                                    // ヒット位置より後の文字をそのままコピーし、再検索
                                    startAt = newLine.Length;
                                    newLine.Append(line.Substring(match.Index + match.Length));
                                    line = newLine.ToString();
                                    newLine.Clear();
                                }
                                else
                                {
                                    // どのパターンもヒットしていないなら打ち止め、次の行へ
                                    break;
                                }
                            } while (startAt < line.Length);

                            // startAt < line.Lengthなら、置換されなかった文字があるはずなので、通知
                            if (startAt < line.Length)
                            {
                                if (AddPlain != null)
                                {
                                    AddPlain.Invoke(line.Substring(startAt));
                                }
                            }

                            // 置換処理が行われたことを通知
                            if (findMatch)
                            {
                                if (Inform != null)
                                {
                                    Inform.Invoke(lineCnt, encoding, line);
                                }
                            }

                            writer.Write(line);
                            if (lnCd != null)
                            {
                                writer.Write(lnCd);
                                if (NewLine != null)
                                {
                                    NewLine.Invoke();
                                }
                            }
                        }
                    }

                if (replaceOcc)
                {
                    // 置換前のファイルの退避(DBへ)
                    db.Insert(
                        filepath,
                        Util.MakeHash(output),
                        (Action <string, string>) delegate(string src, string dist)
                    {
                        // ファイル置換
                        File.Delete(dist);
                        File.Move(src, dist);
                    },
                        output,
                        filepath);
                }
            }
        }
コード例 #10
0
 public static void WriteLine(string msg)
 {
     Console.WriteLine(msg);
     NewLine?.Invoke(msg);
 }
コード例 #11
0
 public void WriteLine(string message)
 {
     NewLine?.Invoke(this, new LogEventArgs(message));
 }
コード例 #12
0
 private void FireNewLine(string text)
 {
     NewLine?.Invoke(this, new NewLineEventArgs(text));
 }
コード例 #13
0
 public override void WriteLine(string message)
 {
     NewLine?.Invoke(message, this.IndentLevel);
 }