Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Threading;
- using System.Threading.Parallel;
- using DbMon.NET.Options;
- namespace DbMon.NET {
- /// <summary>
- /// Monitors a specified file and outputs the contents via 'OutputQueue'
- /// </summary>
- public partial class FileMonitorComponent:Component {
- const string FILE_DEBUG_PATH = @"C:\DATA\temp\_TestFiles\FileDebugWriter\dbmon.txt";
- const long FLUSH_BUFFER = 1024;
- bool _enabled;
- bool _started;
- long _cancelled;
- bool _paused;
- string _filePath;
- OutputQueue<DebugItem> _outputQueue;
- FileStream _stream;
- public bool PurgeOnStartup { get; set; }
- protected FileStream Stream {
- get {
- if(_stream == null) {
- Interlocked.CompareExchange<FileStream>(
- ref _stream,
- File.Open(FilePath,FileMode.OpenOrCreate,FileAccess.Read,FileShare.ReadWrite),
- null);
- }
- return _stream;
- }
- }
- public string FilePath {
- get {
- return _filePath;
- }
- }
- public bool Enabled {
- get {
- return _enabled;
- }
- set {
- _enabled = value;
- }
- }
- public bool Started {
- get {
- return _started;
- }
- protected set {
- _started = value;
- }
- }
- public bool Cancelled {
- get {
- return ParallelTask.GetRefBool(ref _cancelled);
- }
- protected set {
- ParallelTask.SetRefBool(value,ref _cancelled);
- }
- }
- public bool IsPaused {
- get { return _paused; }
- protected set { _paused = value; }
- }
- public FileMonitorComponent() {
- InitializeComponent();
- _filePath = FILE_DEBUG_PATH;
- }
- public FileMonitorComponent(IContainer container) {
- container.Add(this);
- InitializeComponent();
- _filePath = FILE_DEBUG_PATH;
- }
- public virtual void Pause() {
- IsPaused = true;
- }
- public virtual void Resume() {
- IsPaused = false;
- beginRead();
- }
- public virtual void Start(string filePath,OutputQueue<DebugItem> outputQueue) {
- _filePath = filePath;
- _outputQueue = outputQueue;
- if(Started)
- return;
- if(_filePath.IsNull())
- throw new ArgumentNullException("filePath");
- Started = true;
- var parameters = new ReadParameters() {
- Path = _filePath,
- LastWrittenTime = DateTime.MinValue,
- };
- ThreadPool.QueueUserWorkItem(readThread,parameters);
- }
- void readThread(object state) {
- //State = OutputQueueState.Started;
- //_stopResetEvent.Reset();
- ReadParameters parameters = state as ReadParameters;
- bool setup = false;
- while(!Cancelled) {
- try {
- if(!setup) {
- bool success = SetupFile(parameters);
- if(!success) {
- SleepSpin(500);
- continue;
- }
- else {
- parameters.LastWrittenTime = DateTime.MinValue;
- setup = true;
- }
- }
- if(IsPaused) {
- SleepSpin(200);
- continue;
- }
- ReadFile(parameters);
- if(parameters.Contents.Length > 0) {
- var items = parameters.GetDebugItems();
- _outputQueue.EnqueueOutput(items);
- SleepSpin(50);
- }
- else
- SleepSpin(50);
- }
- catch(Exception err) {
- Trace.WriteLine("ERROR: runningThread() -> dequeueQueue() -> " + err.ToString());
- SleepSpin(500);
- }
- }
- }
- bool SetupFile(ReadParameters parameters) {
- bool startAtEOF = AppOptions.Environment.AsBool(DataOptionsEnum.FileStartAtEOF,true);
- long lastPosition = AppOptions.History.AsLong(parameters.Path,0);
- FileInfo finfo = new FileInfo(_filePath);
- if(finfo.Exists) {
- if(startAtEOF)
- lastPosition = finfo.Length;
- else {
- if(lastPosition > 0) {
- if(lastPosition > finfo.Length)
- lastPosition = finfo.Length;
- }
- }
- parameters.LastReadSet(lastPosition);
- return true;
- }
- else
- return false;
- }
- void ReadFile(ReadParameters parameters) {
- string path = parameters.Path;
- var lastWrite = File.GetLastWriteTimeUtc(path);
- if(lastWrite.CompareTo(parameters.LastWrittenTime) == 0) {
- return;
- }
- parameters.LastWrittenTime = lastWrite;
- using(FileStream stream = File.Open(path.ToString(),FileMode.OpenOrCreate,FileAccess.Read,FileShare.ReadWrite)) {
- byte[] buffer = new byte[(1024 * 10)];
- int bytesRead = 1;
- while(bytesRead > 0 && !Cancelled) {
- stream.Position = (int)parameters.LastReadPosition;
- bytesRead = stream.Read(buffer,0,buffer.Length);
- if(bytesRead < 1) {
- return;
- }
- AppOptions.History[path] = parameters.LastReadPositionAdd(bytesRead);
- string read = Encoding.Default.GetString(buffer,0,bytesRead);
- parameters.WriteContents(read);
- }
- }
- }
- class ReadParameters {
- long _lastReadPosition;
- public string Path { get; set; }
- public DateTime LastWrittenTime { get; set; }
- public void LastReadSet(long value) {
- Interlocked.Exchange(ref _lastReadPosition,value);
- }
- public long LastReadPosition {
- get {
- return Interlocked.Read(ref _lastReadPosition);
- }
- }
- public long LastReadPositionAdd(long value) {
- return Interlocked.Add(ref _lastReadPosition,value);
- }
- public StringBuilder Contents { get; set; }
- public void WriteContents(string value) {
- lock(this) {
- Contents.Append(value);
- }
- }
- public DebugItem[] GetDebugItems() {
- List<DebugItem> list = new List<DebugItem>();
- string fileName = System.IO.Path.GetFileName(Path);
- lock(this) {
- try {
- string[] splitValues = Contents.ToString().Split(Environment.NewLine.ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
- foreach(string item in splitValues) {
- DebugItem di = new DebugItem(-1,item) {
- ProcessName = fileName,
- };
- list.Add(di);
- }
- }
- finally {
- Contents.Length = 0;
- }
- }
- return list.ToArray();
- }
- public ReadParameters() {
- Contents = new StringBuilder();
- }
- }
- protected void SleepSpin(int millisecondsTimeout) {
- int spinby = 10;
- int iterations = (millisecondsTimeout / spinby);
- for(int i = 0;i < iterations;i++) {
- if(Cancelled)
- return;
- Thread.Sleep(spinby);
- }
- }
- void beginRead() {
- if(!Enabled)
- return;
- if(IsPaused)
- return;
- var timeOut = TimeSpan.FromSeconds(10);
- }
- void readCompleted(object sender,EventArgs e) {
- }
- public virtual void Stop() {
- Cancelled = true;
- Started = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment