forked from ianxtianxt/RecentFileCacheParser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
375 lines (290 loc) · 13.3 KB
/
Program.cs
File metadata and controls
375 lines (290 loc) · 13.3 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using Exceptionless;
using Fclp;
using NLog;
using NLog.Config;
using NLog.Targets;
using RecentFileCache;
using ServiceStack;
using ServiceStack.Text;
using CsvWriter = CsvHelper.CsvWriter;
namespace RecentFileCacheParser
{
internal class Program
{
private static Logger _logger;
private static FluentCommandLineParser<AppArgs> _fluentCommandLineParser;
private static readonly string _dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
private static void Main(string[] args)
{
ExceptionlessClient.Default.Startup("Wdlq68AwLteBtuqOwNv5rgphcMxzKuHKJQAVK5JN");
SetupNLog();
_logger = LogManager.GetCurrentClassLogger();
_fluentCommandLineParser = new FluentCommandLineParser<AppArgs>
{
IsCaseSensitive = false
};
_fluentCommandLineParser.Setup(arg => arg.File)
.As('f')
.WithDescription("File to process. Required");
_fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
.As("csv")
.WithDescription(
"Directory to save CSV formatted results to. Be sure to include the full path in double quotes");
_fluentCommandLineParser.Setup(arg => arg.CsvName)
.As("csvf")
.WithDescription(
"File name to save CSV formatted results to. When present, overrides default name");
_fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
.As("json")
.WithDescription(
"Directory to save json representation to. Use --pretty for a more human readable layout");
_fluentCommandLineParser.Setup(arg => arg.JsonPretty)
.As("pretty")
.WithDescription(
"When exporting to json, use a more human readable layout\r\n").SetDefault(false);
_fluentCommandLineParser.Setup(arg => arg.Quiet)
.As('q')
.WithDescription(
"Only show the filename being processed vs all output. Useful to speed up exporting to json and/or csv\r\n")
.SetDefault(false);
var header =
$"RecentFileCacheParser version {Assembly.GetExecutingAssembly().GetName().Version}" +
"\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
"\r\nhttps://github.com/EricZimmerman/RecentFileCacheParser";
var footer = @"Examples: RecentFileCacheParser.exe -f ""C:\Temp\RecentFileCache.bcf"" --csv ""c:\temp""" +
"\r\n\t " +
@" RecentFileCacheParser.exe -f ""C:\Temp\RecentFileCache.bcf"" --json ""D:\jsonOutput"" --jsonpretty" +
"\r\n\t " +
"\r\n\t" +
" Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";
_fluentCommandLineParser.SetupHelp("?", "help")
.WithHeader(header)
.Callback(text => _logger.Info(text + "\r\n" + footer));
var result = _fluentCommandLineParser.Parse(args);
if (result.HelpCalled)
{
return;
}
if (result.HasErrors)
{
_logger.Error("");
_logger.Error(result.ErrorText);
_fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);
return;
}
if (_fluentCommandLineParser.Object.File.IsNullOrEmpty())
{
_fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);
_logger.Warn("-f is required. Exiting");
return;
}
if (_fluentCommandLineParser.Object.File.IsNullOrEmpty() == false &&
!File.Exists(_fluentCommandLineParser.Object.File))
{
_logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
return;
}
_logger.Info(header);
_logger.Info("");
_logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");
if (IsAdministrator() == false)
{
_logger.Fatal($"Warning: Administrator privileges not found!\r\n");
}
try
{
if (_fluentCommandLineParser.Object.Quiet == false)
{
_logger.Warn($"Processing '{_fluentCommandLineParser.Object.File}'");
_logger.Info("");
}
var sw = new Stopwatch();
sw.Start();
var rfc = RecentFileCache.RecentFileCache.LoadFile(_fluentCommandLineParser.Object.File);
if (_fluentCommandLineParser.Object.Quiet == false)
{
_logger.Error($"Source file: {rfc.SourceFile}");
_logger.Info($" Source created: {rfc.SourceCreated.ToString(_dateTimeFormat)} ");
_logger.Info($" Source modified: {rfc.SourceModified.ToString(_dateTimeFormat)}");
_logger.Info($" Source accessed: {rfc.SourceAccessed.ToString(_dateTimeFormat)}");
_logger.Info("");
_logger.Warn("File names");
foreach (var rfcFileName in rfc.FileNames)
{
_logger.Info($"{rfcFileName}");
}
_logger.Info("");
}
sw.Stop();
if (_fluentCommandLineParser.Object.Quiet)
{
_logger.Info("");
}
_logger.Info(
$"---------- Processed '{rfc.SourceFile}' in {sw.Elapsed.TotalSeconds:N8} seconds ----------");
if (_fluentCommandLineParser.Object.Quiet == false)
{
_logger.Info("\r\n");
}
try
{
StreamWriter sw1 = null;
if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
{
if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
{
_logger.Warn(
$"'{_fluentCommandLineParser.Object.CsvDirectory} does not exist. Creating...'");
Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
}
var outName =
$"{DateTimeOffset.Now:yyyyMMddHHmmss}_RecentFileCacheParser_Output.csv";
if (_fluentCommandLineParser.Object.CsvName.IsNullOrEmpty() == false)
{
outName = Path.GetFileName(_fluentCommandLineParser.Object.CsvName);
}
var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);
_fluentCommandLineParser.Object.CsvDirectory =
Path.GetFullPath(outFile);
_logger.Warn(
$"CSV output will be saved to '{Path.GetFullPath(outFile)}'");
try
{
sw1 = new StreamWriter(outFile);
var csv = new CsvWriter(sw1);
csv.Configuration.HasHeaderRecord = true;
var foo = csv.Configuration.AutoMap<CsvOut>();
foo.Map(t => t.SourceAccessed)
.ConvertUsing(t => t.SourceAccessed.ToString(_dateTimeFormat));
foo.Map(t => t.SourceCreated).ConvertUsing(t => t.SourceCreated.ToString(_dateTimeFormat));
foo.Map(t => t.SourceModified)
.ConvertUsing(t => t.SourceModified.ToString(_dateTimeFormat));
csv.WriteHeader(typeof(CsvOut));
csv.NextRecord();
csv.WriteRecords(GetCsvFormat(rfc));
}
catch (Exception ex)
{
_logger.Error(
$"Unable to open '{outFile}' for writing. Export canceled. Error: {ex.Message}");
}
}
if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
{
if (Directory.Exists(_fluentCommandLineParser.Object.JsonDirectory) == false)
{
_logger.Warn(
$"'{_fluentCommandLineParser.Object.JsonDirectory} does not exist. Creating...'");
Directory.CreateDirectory(_fluentCommandLineParser.Object.JsonDirectory);
}
_logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
SaveJson(rfc, _fluentCommandLineParser.Object.JsonPretty,
_fluentCommandLineParser.Object.JsonDirectory);
}
//Close CSV stuff
sw1?.Flush();
sw1?.Close();
}
catch (Exception e)
{
_logger.Error(
$"Error exporting data! Error: {e.Message}");
}
}
catch (UnauthorizedAccessException ua)
{
_logger.Error(
$"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ua.Message}");
}
catch (Exception ex)
{
_logger.Error(
$"Error processing file '{_fluentCommandLineParser.Object.File}' Please send it to [email protected]. Error: {ex.Message}");
}
}
private static List<CsvOut> GetCsvFormat(RecentFileCacheFile rcf)
{
var csOut = new List<CsvOut>();
foreach (var rcfFileName in rcf.FileNames)
{
var cs = new CsvOut
{
SourceFile = rcf.SourceFile,
SourceCreated = rcf.SourceCreated,
SourceModified = rcf.SourceModified,
SourceAccessed = rcf.SourceAccessed,
Filename = rcfFileName
};
csOut.Add(cs);
}
return csOut;
}
private static void DumpToJson(RecentFileCacheFile rfc, bool pretty, string outFile)
{
if (pretty)
{
File.WriteAllText(outFile, rfc.Dump());
}
else
{
File.WriteAllText(outFile, rfc.ToJson());
}
}
private static void SaveJson(RecentFileCacheFile rfc, bool pretty, string outDir)
{
try
{
if (Directory.Exists(outDir) == false)
{
Directory.CreateDirectory(outDir);
}
var outName =
$"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}_{Path.GetFileName(rfc.SourceFile)}.json";
var outFile = Path.Combine(outDir, outName);
DumpToJson(rfc, pretty, outFile);
}
catch (Exception ex)
{
_logger.Error($"Error exporting json for '{rfc.SourceFile}'. Error: {ex.Message}");
}
}
private static readonly string BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static void SetupNLog()
{
if (File.Exists( Path.Combine(BaseDirectory,"Nlog.config")))
{
return;
}
var config = new LoggingConfiguration();
var loglevel = LogLevel.Info;
var layout = @"${message}";
var consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
consoleTarget.Layout = layout;
var rule1 = new LoggingRule("*", loglevel, consoleTarget);
config.LoggingRules.Add(rule1);
LogManager.Configuration = config;
}
}
public sealed class CsvOut
{
public string SourceFile { get; set; }
public DateTimeOffset SourceCreated { get; set; }
public DateTimeOffset SourceModified { get; set; }
public DateTimeOffset SourceAccessed { get; set; }
public string Filename { get; set; }
}
}