forked from sbozzie/test-intel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntelChannel.cs
More file actions
829 lines (759 loc) · 32.1 KB
/
Copy pathIntelChannel.cs
File metadata and controls
829 lines (759 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
using PleaseIgnore.IntelMap.Properties;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace PleaseIgnore.IntelMap {
/// <summary>
/// Monitors the log directory for new log entries to a specific
/// channel.
/// </summary>
/// <remarks>
/// <para>When running, <see cref="IntelChannel"/> makes use of the
/// <see cref="ThreadPool"/> to perform background operations. The
/// following sequence of events are processed:</para>
/// <list type="number">
/// <item>
/// <term><see cref="OnStart()"/></term>
/// <description>Called after the initial call to
/// <see cref="Start()"/>. Responsible for initializing the
/// internal operations and searching the log directory for
/// possible active logs. Will not be called by subsequent
/// calls to <see cref="Start()"/> unless an intervening call
/// to <see cref="Stop()"/> has been made.</description>
/// </item>
/// <item>
/// <term><see cref="OnFileCreated()"/></term>
/// <description>Generated by an internal instance of
/// <see cref="FileSystemWatcher"/> to notify us of new files
/// being created within the log directory, allowing us to
/// switch to newer log files.</description>
/// </item>
/// <item>
/// <term><see cref="OnFileChanged()"/></term>
/// <description>Generated by an internal instance of
/// <see cref="FileSystemWatcher"/> to notify us of changes
/// to files in the log directory, allowing us to rescan and
/// reopen log files appropriately. Unfortunately, due to
/// performance optimizations in Windows, change notifications
/// are often sent when the file is <em>closed</em>, not when
/// new data has been written to the file.</description>
/// </item>
/// <item>
/// <term><see cref="OnTick()"/></term>
/// <description>Generated periodically by the
/// <see cref="ThreadPool"/> to allow us to rescan the log
/// files. Has primary responsibility for generating
/// <see cref="IntelReported"/> events.</description>
/// </item>
/// <item>
/// <term><see cref="OnStop()"/></term>
/// <description>Called after the initial call to
/// <see cref="Stop()"/>. Destroys all internal tracking
/// structures. Will be not be called by subsequent calls
/// to <see cref="Stop()"/> unless an intervening call to
/// <see cref="Start()"/> has been made.</description>
/// </item>
/// </list>
/// <note>Internal <see langword="protected"/> and <see langword="virtual"/>
/// members are provided for the benefit of user testing. Redefinition may
/// lead to behavior defects or loss of thread safety.</note>
/// </remarks>
/// <threadsafety static="true" instance="true"/>
[DefaultEvent("IntelReported"), DefaultProperty("Name")]
public class IntelChannel : Component {
// Internal members should be referenced by any other class within
// PleaseIgnore.IntelMap. They are made internal purely for the
// benefit of implementing unit tests.
// Regular Expression used to break apart each entry in the log file.
private static readonly Regex Parser = new Regex(
"^\uFEFF?" + @"\[\s*(\d{4})\.(\d{2})\.(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s*\](.*)$",
RegexOptions.CultureInvariant);
// Regular Expression used to extract the timestamp from the filename.
private static readonly Regex FilenameParser = new Regex(
@"_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.txt$",
RegexOptions.CultureInvariant);
// Default directory to find EVE logs
private static readonly string defaultLogDirectory = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"EVE",
"logs",
"Chatlogs");
// The timer period to use when scheduling the timer
private const int timerPeriod = 5000;
// The default value for expireLog
private const string defaultExpireLog = "00:30:00";
// Synchronization primitive
internal readonly object syncRoot = new object();
// Raises the periodic timer for log scanning
private readonly Timer logTimer;
// The local file system watcher object
private FileSystemWatcher watcher;
// The channel file name stub
[ContractPublicPropertyName("Name")]
private string channelFileName;
// The path to search for EVE chat logs
[ContractPublicPropertyName("Path")]
private string logDirectory = defaultLogDirectory;
// The current component status
[ContractPublicPropertyName("Status")]
private volatile IntelStatus status;
// The currently processed log file
private StreamReader reader;
// The last time we parsed a log entry from the current log
private DateTime lastEntry;
// The time to wait before calling a log file "dead"
[ContractPublicPropertyName("LogExpiration")]
private TimeSpan expireLog = TimeSpan.Parse(
defaultExpireLog,
CultureInfo.InvariantCulture);
// true if the timer is currently running
private bool timerEnabled;
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel"/> class.
/// </summary>
public IntelChannel() : this(null, null) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel"/> class
/// with the specified <see cref="Name"/>.
/// </summary>
/// <param name="name">
/// The initial value for <see cref="Name"/>.
/// </param>
public IntelChannel(string name)
: this(name, null) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel"/> class
/// with the specified <see cref="Container"/>.
/// </summary>
/// <param name="container">
/// Optional parent <see cref="Container"/>.
/// </param>
public IntelChannel(IContainer container)
: this(null, container) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel"/> class
/// with the specified <see cref="Name"/> and <see cref="Container"/>.
/// </summary>
/// <param name="name">
/// The initial value for <see cref="Name"/>.
/// </param>
/// <param name="container">
/// Optional parent <see cref="Container"/>.
/// </param>
public IntelChannel(string name, IContainer container) {
this.channelFileName = name;
this.logTimer = new Timer(this.timer_Callback);
if (container != null) {
container.Add(this);
}
}
/// <inheritdoc/>
~IntelChannel() {
this.Dispose(false);
}
/// <summary>
/// Occurs when a new log entry has been read from the chat logs.
/// </summary>
public event EventHandler<IntelEventArgs> IntelReported;
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the default directory to search for EVE chat logs.
/// </summary>
public static string DefaultPath {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return defaultLogDirectory;
}
}
/// <summary>
/// Gets or sets the directory to search for log files.
/// </summary>
public string Path {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return this.logDirectory;
}
set {
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
lock (this.syncRoot) {
if (value != this.logDirectory) {
this.logDirectory = value;
if (this.watcher != null) {
try {
this.watcher.Path = value;
this.ScanFiles();
} catch (ArgumentException) {
this.watcher.Dispose();
this.watcher = null;
this.Status = IntelStatus.InvalidPath;
}
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Path"));
}
}
}
}
/// <summary>
/// Gets or sets the channel name of this <see cref="IntelChannel"/>
/// </summary>
/// <remarks>
/// The channel name cannot be modified when <see cref="IsRunning"/>
/// is <see langword="true"/>.
/// </remarks>
[DefaultValue((string)null)]
public string Name {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())
|| !this.IsRunning);
var channelName = this.channelFileName;
var site = this.Site;
if (!String.IsNullOrEmpty(channelName)) {
return channelName;
} else if (site != null) {
return site.Name;
} else {
return null;
}
}
set {
lock (this.syncRoot) {
if (this.IsRunning) {
throw new InvalidOperationException();
}
this.channelFileName = value;
}
}
}
/// <summary>
/// Gets the number of reports that have been made by this
/// <see cref="IntelChannel"/>.
/// </summary>
public int IntelCount { get; private set; }
/// <summary>
/// Gets the log file currently being observed for new intel.
/// </summary>
public FileInfo LogFile { get; private set; }
/// <summary>
/// Gets the current operational status of the
/// <see cref="IntelChannel"/> object.
/// </summary>
public virtual IntelStatus Status {
get {
return this.status;
}
private set {
Contract.Ensures(Status == value);
if (this.status != value) {
this.status = value;
this.UpdateTimer();
this.OnPropertyChanged(new PropertyChangedEventArgs("Status"));
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="IntelChannel"/>
/// is currently running and watching for log entries.
/// </summary>
public bool IsRunning { get { return this.Status.IsRunning(); } }
/// <summary>
/// Gets or sets the time between log entries before declaring
/// that the channel is no longer being monitored.
/// </summary>
[DefaultValue(typeof(TimeSpan), defaultExpireLog)]
public TimeSpan LogExpiration {
get {
Contract.Ensures(Contract.Result<TimeSpan>() > TimeSpan.Zero);
return this.expireLog;
}
set {
Contract.Requires<ArgumentOutOfRangeException>(
value > TimeSpan.Zero,
"value");
Contract.Ensures(LogExpiration == value);
lock (this) {
if (this.expireLog != value) {
this.expireLog = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("LogExpiration"));
}
}
}
}
/// <summary>
/// Initiate the acquisition of log entries from the EVE chat logs. This
/// method enables <see cref="IntelReported"/> events.
/// </summary>
public virtual void Start() {
Contract.Requires<ObjectDisposedException>(
Status != IntelStatus.Disposed,
null);
Contract.Requires<InvalidOperationException>(
!String.IsNullOrEmpty(Name));
Contract.Ensures(Status != IntelStatus.Stopped);
Contract.Ensures(IsRunning);
lock (this.syncRoot) {
if (this.status == IntelStatus.Stopped) {
this.Status = IntelStatus.Starting;
this.channelFileName = this.Name;
this.OnStart();
}
}
}
/// <summary>
/// Stops the <see cref="IntelChannel"/> from providing location data and events.
/// </summary>
public virtual void Stop() {
Contract.Ensures((Status == IntelStatus.Stopped)
|| (Status == IntelStatus.Disposed));
Contract.Ensures(!IsRunning);
lock (this.syncRoot) {
if ((this.status != IntelStatus.Stopped)
|| (this.status == IntelStatus.Disposed)) {
this.Status = IntelStatus.Stopping;
this.OnStop();
this.UpdateTimer();
}
}
}
/// <inheritdoc/>
protected override void Dispose(bool disposing) {
Contract.Ensures(Status == IntelStatus.Disposed);
if (disposing) {
lock (this.syncRoot) {
if (this.status != IntelStatus.Disposed) {
// Normal shutdown
this.Stop();
this.Status = IntelStatus.Disposed;
// Dispose child objects
this.logTimer.Dispose();
// Clear any lingering object references
this.IntelReported = null;
this.PropertyChanged = null;
}
}
} else {
// We really can't touch anything safely
this.status = IntelStatus.Disposed;
}
base.Dispose(disposing);
}
/// <inheritdoc/>
public override string ToString() {
return String.Format(
CultureInfo.CurrentCulture,
Resources.IntelChannel_ToString,
this.GetType().Name,
this.Name ?? Resources.IntelChannel_NoName,
this.Status);
}
/// <summary>
/// Creates the instance of <see cref="FileSystemWatcher"/> used
/// to monitor the file system.
/// </summary>
/// <returns>
/// An instance of <see cref="FileSystemWatcher"/> that will be
/// used to monitor the directory for the creation/modification
/// of log files.
/// </returns>
/// <remarks>
/// <see cref="CreateFileSystemWatcher"/> will be called from within
/// synchronized members so should not attempt to perform any
/// additional synchronization itself.
/// </remarks>
protected virtual FileSystemWatcher CreateFileSystemWatcher() {
Contract.Ensures(Contract.Result<FileSystemWatcher>() != null);
var watcher = new FileSystemWatcher();
watcher.BeginInit();
watcher.Changed += this.watcher_Changed;
watcher.Created += this.watcher_Created;
watcher.EnableRaisingEvents = true;
watcher.Filter = this.Name + "_*.txt";
watcher.IncludeSubdirectories = false;
watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite
| NotifyFilters.DirectoryName | NotifyFilters.FileName;
watcher.Path = this.Path;
watcher.EndInit();
return watcher;
}
/// <summary>
/// Raises the <see cref="IntelReported"/> event.
/// </summary>
/// <param name="e">
/// Arguments of the event being raised.
/// </param>
/// <remarks>
/// <see cref="OnIntelReported"/> will be called from within
/// synchronized members so should not attempt to perform any
/// additional synchronization itself.
/// </remarks>
internal protected void OnIntelReported(IntelEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is IntelEventArgs);
var handler = this.IntelReported;
if (handler != null) {
handler(this, (IntelEventArgs)state);
}
}, e);
this.lastEntry = DateTime.UtcNow;
++this.IntelCount;
this.OnPropertyChanged(new PropertyChangedEventArgs("IntelCount"));
}
/// <summary>
/// Raises the <see cref="PropertyChanged"/> event.
/// </summary>
/// <param name="e">
/// Arguments of the event being raised.
/// </param>
/// <remarks>
/// <see cref="OnPropertyChanged"/> will be called from within
/// synchronized members so should not attempt to perform any
/// additional synchronization itself.
/// </remarks>
internal protected void OnPropertyChanged(PropertyChangedEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
Debug.Assert(String.IsNullOrEmpty(e.PropertyName)
|| (GetType().GetProperty(e.PropertyName) != null));
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is PropertyChangedEventArgs);
var handler = this.PropertyChanged;
if (handler != null) {
handler(this, (PropertyChangedEventArgs)state);
}
}, e);
}
/// <summary>
/// Called after <see cref="Start()"/> has been called.
/// </summary>
/// <remarks>
/// <see cref="OnFileCreated"/> will be called with synchronized
/// access to the object state.
/// </remarks>
protected virtual void OnStart() {
Contract.Requires<InvalidOperationException>(
Status == IntelStatus.Starting);
Contract.Ensures((Status == IntelStatus.Active)
|| (Status == IntelStatus.Waiting)
|| (Status == IntelStatus.InvalidPath));
// Create the file system watcher object
try {
this.watcher = this.CreateFileSystemWatcher();
} catch(ArgumentException) {
this.Status = IntelStatus.InvalidPath;
}
// Open the log file with the latest timestamp in its filename
this.ScanFiles();
}
/// <summary>
/// Called when a new log file is created for the channel we
/// are monitoring.
/// </summary>
/// <param name="e">
/// Instance of <see cref="FileSystemEventArgs"/> describing the
/// new file.
/// </param>
/// <remarks>
/// <see cref="OnFileCreated"/> will be called with synchronized
/// access to the object state.
/// </remarks>
protected virtual void OnFileCreated(FileSystemEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
// Assume it's going to be a better file....for now
OpenFile(new FileInfo(e.FullPath));
}
/// <summary>
/// Called when a log file associated with the channel we are
/// monitoring has been modified.
/// </summary>
/// <param name="e">
/// Instance of <see cref="FileSystemEventArgs"/> describing the
/// modified file.
/// </param>
/// <remarks>
/// <see cref="OnFileChanged"/> will be called with synchronized
/// access to the object state.
/// </remarks>
protected virtual void OnFileChanged(FileSystemEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
// Only process this message if we have nothing else to go on
if (this.reader == null) {
this.OpenFile(new FileInfo(e.FullPath));
}
}
/// <summary>
/// Called every couple of seconds to sweep the log file for
/// new entries.
/// </summary>
/// <remarks>
/// <see cref="OnTick()"/> will be called with synchronized
/// access to the object state.
/// </remarks>
protected virtual void OnTick() {
if (this.watcher == null) {
// Try (again) to create the watcher object
try {
this.watcher = this.CreateFileSystemWatcher();
this.Status = IntelStatus.Waiting;
this.ScanFiles();
} catch (ArgumentException) {
// Still doesn't seem to exist
}
}
if (this.reader != null) {
// Read new log entries from the current log
try {
string line;
while ((line = reader.ReadLine()) != null) {
Trace.WriteLine("R " + line, IntelExtensions.WebTraceCategory);
var match = Parser.Match(line);
if (match.Success) {
var e = new IntelEventArgs(
this.Name,
new DateTime(
match.Groups[1].ToInt32(),
match.Groups[2].ToInt32(),
match.Groups[3].ToInt32(),
match.Groups[4].ToInt32(),
match.Groups[5].ToInt32(),
match.Groups[6].ToInt32(),
DateTimeKind.Utc),
match.Groups[7].Value);
this.OnIntelReported(e);
}
}
} catch (IOException) {
this.CloseFile();
}
// Close the log if it has been idle for too long
if (this.lastEntry + this.expireLog < DateTime.UtcNow) {
this.CloseFile();
}
}
}
/// <summary>
/// Called after <see cref="Stop()"/> has been called.
/// </summary>
/// <remarks>
/// <see cref="OnStop()"/> will be called with synchronized
/// access to the object state.
/// </remarks>
protected virtual void OnStop() {
Contract.Requires<InvalidOperationException>(
Status == IntelStatus.Stopping);
Contract.Ensures(Status == IntelStatus.Stopped);
if (this.reader != null) {
this.reader.Close();
this.reader = null;
}
if (this.LogFile != null) {
this.LogFile = null;
this.OnPropertyChanged(new PropertyChangedEventArgs("LogFile"));
}
this.Status = IntelStatus.Stopped;
}
/// <summary>
/// Rescans the active directory looking for valid log files
/// </summary>
/// <returns>
/// <see langword="true"/> if we were able to open a log file;
/// otherwise, <see langword="false"/>.
/// </returns>
protected bool ScanFiles() {
try {
var downtime = IntelExtensions.LastDowntime;
var file = new DirectoryInfo(this.Path)
.GetFiles(this.Name + "_*.txt", SearchOption.TopDirectoryOnly)
.Select(x => new {
File = x,
Match = FilenameParser.Match(x.Name)
})
.Where(x => x.Match.Success)
.Select(x => new {
File = x.File,
Timestamp = new DateTime(
x.Match.Groups[1].ToInt32(),
x.Match.Groups[2].ToInt32(),
x.Match.Groups[3].ToInt32(),
x.Match.Groups[4].ToInt32(),
x.Match.Groups[5].ToInt32(),
x.Match.Groups[6].ToInt32(),
DateTimeKind.Utc)
})
.Where(x => x.Timestamp > downtime)
.OrderByDescending(x => x.Timestamp)
.FirstOrDefault(x => this.OpenFile(x.File));
if (file == null) {
this.CloseFile();
}
return file != null;
} catch (IOException) {
return false;
}
}
/// <summary>
/// Closes the existing log file and opens a new log file.
/// </summary>
/// <param name="fileInfo">
/// The new log file to track.
/// </param>
/// <returns>
/// <see langword="true"/> if we were able to open the file;
/// otherwise, <see langword="false"/>.
/// </returns>
internal protected bool OpenFile(FileInfo fileInfo) {
Contract.Requires<ArgumentNullException>(fileInfo != null, "fileInfo");
//Contract.Ensures(Status == IntelChannelStatus.Active);
var oldStatus = this.status;
var oldFile = this.LogFile;
// Close the existing file (if any)
if (this.reader != null) {
try {
this.reader.Close();
} catch (IOException) {
} finally {
this.reader = null;
}
}
// Clear the status (defer raising PropertyChanged)
this.LogFile = null;
this.status = (this.watcher != null)
? IntelStatus.Waiting
: IntelStatus.InvalidPath;
// Try to open the file stream
FileStream stream = null;
try {
stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
stream.Seek(0, SeekOrigin.End);
// XXX: We rely upon StreamReader's BOM detection. EVE seems
// to generate Little Endian UTF-16 log files. We could hard
// code that, but we don't know if that would cause other
// problems.
this.reader = new StreamReader(stream, true);
this.status = IntelStatus.Active;
this.LogFile = fileInfo;
this.lastEntry = DateTime.UtcNow;
} catch (IOException) {
// Don't leak FileStream references
if (stream != null) {
try {
stream.Close();
} catch (IOException) {
}
}
}
// Raise any deferred PropertyChanged events
if (this.status != oldStatus) {
this.OnPropertyChanged(new PropertyChangedEventArgs("Status"));
}
if (this.LogFile != oldFile) {
this.OnPropertyChanged(new PropertyChangedEventArgs("LogFile"));
}
// Success if we opened a reader
this.UpdateTimer();
return (this.reader != null);
}
/// <summary>
/// Closes the existing log file
/// </summary>
protected void CloseFile() {
Contract.Ensures((Status == IntelStatus.Waiting)
|| (Status == IntelStatus.InvalidPath));
if (this.reader != null) {
try {
this.reader.Close();
} catch (IOException) {
} finally {
this.reader = null;
}
}
if (this.LogFile != null) {
this.LogFile = null;
this.OnPropertyChanged(new PropertyChangedEventArgs("LogFile"));
}
this.Status = (this.watcher != null)
? IntelStatus.Waiting
: IntelStatus.InvalidPath;
}
/// <summary>
/// Updates the timer for <see cref="OnTick"/>
/// </summary>
private void UpdateTimer() {
switch (this.status) {
case IntelStatus.Active:
case IntelStatus.InvalidPath:
// Operations that require us to ping the filesystem regularly
if (!this.timerEnabled) {
this.logTimer.Change(timerPeriod, timerPeriod);
this.timerEnabled = true;
}
break;
case IntelStatus.Disposed:
// The timer object is no longer valid
break;
default:
// Operations when we are not actively monitoring the filesystem
if (this.timerEnabled) {
this.logTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.timerEnabled = false;
}
break;
}
}
/// <summary>
/// Handler for <see cref="FileSystemWatcher.Created"/> event.
/// </summary>
private void watcher_Created(object sender, FileSystemEventArgs e) {
Contract.Requires(e != null);
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is FileSystemEventArgs);
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnFileCreated((FileSystemEventArgs)e);
}
}
}, e);
}
/// <summary>
/// Handler for <see cref="FileSystemWatcher.Created"/> event.
/// </summary>
private void watcher_Changed(object sender, FileSystemEventArgs e) {
Contract.Requires(e != null);
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is FileSystemEventArgs);
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnFileChanged((FileSystemEventArgs)e);
}
}
}, e);
}
/// <summary>
/// Handler for the <see cref="Timer"/> callback
/// </summary>
private void timer_Callback(object state) {
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnTick();
}
}
}
[ContractInvariantMethod]
private void ObjectInvariant() {
Contract.Invariant(!String.IsNullOrEmpty(this.channelFileName)
|| !this.IsRunning);
Contract.Invariant(!String.IsNullOrEmpty(this.logDirectory));
Contract.Invariant(this.IntelCount >= 0);
}
}
}