-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
433 lines (356 loc) · 15.5 KB
/
Program.cs
File metadata and controls
433 lines (356 loc) · 15.5 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
using IdentityModel.Client;
using iSAMS.Utilities.Reporting.CustomFieldRenaming.Exceptions;
using iSAMS.Utilities.Reporting.CustomFieldRenaming.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace iSAMS.Utilities.Reporting.CustomFieldRenaming
{
class Program
{
private static string AccessToken = null;
private static HttpClient ApiClient = null;
private static readonly string ApiEndpoint = "/api/students/{schoolId}/customFields";
public static ScriptConfiguration Config = null;
private static int CustomFieldId = -1;
private static string CustomFieldResultDirectory_Failed = null;
private static string CustomFieldResultDirectory_Success = null;
private static List<string> FileNames = null;
public const string RestApiScope = "restapi";
private static SummaryStore Summary = new SummaryStore();
private const string TokenPath = "auth/connect/token";
static void Main(string[] args)
{
try
{
GetConfig();
ValidateConfig();
EnsureDirectoryExists(Config.TargetDirectory);
GetFiles();
FilterFilesToProcessable();
EnsureFileNamesHasLength();
AuthenticateApi().GetAwaiter().GetResult();
SetResultDirectories();
ProcessFiles();
SaveSummary();
}
catch (Exception ex)
{
LogError(ex.Message);
}
finally
{
EndProgram();
}
}
#region Config Methods
private static void GetConfig()
{
Console.WriteLine("Getting utility settings...");
var configPath = Path.Combine(Directory.GetCurrentDirectory(), "config.json");
try
{
if (File.Exists(configPath))
{
Console.WriteLine("Utility settings found.");
LoadConfigJson(configPath);
}
else
{
LogError($"No configuration file found. Please ensure 'config.json' exists within {Directory.GetCurrentDirectory()}");
EndProgram();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
}
private static void LoadConfigJson(string path)
{
try
{
Console.WriteLine("Parsing utility settings...");
using (StreamReader reader = new StreamReader(path))
{
string json = reader.ReadToEnd();
json = json.Replace(@"\", @"\\\\");
Config = JsonConvert.DeserializeObject<ScriptConfiguration>(json);
Console.WriteLine("Utility settings parsed successfully.");
}
}
catch (Exception ex)
{
throw ex;
}
}
private static void ValidateConfig()
{
Console.WriteLine("Verifying utility settings...");
var errors = new List<string>();
if (string.IsNullOrEmpty(Config.Domain))
errors.Add("No 'Domain' value was found within the configuration file.");
if (string.IsNullOrEmpty(Config.RestApiClientId))
errors.Add("No 'RestApiClientId' value was found within the configuration file.");
if (string.IsNullOrEmpty(Config.RestApiClientSecret))
errors.Add("No 'RestApiClientSecret' value was found within the configuration file.");
if (string.IsNullOrEmpty(Config.TargetDirectory))
errors.Add("No 'TargetDirectory' value was found within the configuration file.");
if (string.IsNullOrEmpty(Config.CustomFieldName))
errors.Add("No 'CustomFieldName' value was found within the configuration file.");
if (errors.Count > 0)
{
LogError("Configuration invalid. Please address the following issues before continuing.");
LogError(string.Join(Environment.NewLine, errors));
EndProgram();
}
Console.WriteLine("Utility settings verified.");
}
#endregion
#region File/Directory Methods
private static void CopyFileToResultFolder(bool success, string currentFilePath, string newFileName, string message = null)
{
if (!success)
{
var newPath = Path.Combine(CustomFieldResultDirectory_Failed, Path.GetFileName(currentFilePath));
if (!Directory.Exists(CustomFieldResultDirectory_Failed))
{
Directory.CreateDirectory(CustomFieldResultDirectory_Failed);
}
if(Path.GetFullPath(currentFilePath) != Path.GetFullPath(newPath))
{
File.Copy(currentFilePath, newPath, true);
}
Summary.Add($"{Path.GetFileName(currentFilePath)} failed to be renamed. [{message}]", false);
}
else
{
var newPath = Path.Combine(CustomFieldResultDirectory_Success, $"{newFileName}.pdf");
if (!Directory.Exists(CustomFieldResultDirectory_Success))
Directory.CreateDirectory(CustomFieldResultDirectory_Success);
File.Copy(currentFilePath, newPath, true);
Summary.Add($"{Path.GetFileName(currentFilePath)} => {Path.GetFileName(newPath)}", true);
}
}
private static bool DoesDirectoryContainSubDirectory(string directory, string subDirectory)
{
string cleanedDirectory = Regex.Replace(directory, @"\/|\\", "/").Trim('/').ToLower();
string cleanedSubDirectory = Regex.Replace(subDirectory, @"\/|\\", "/").Trim('/').ToLower();
return cleanedDirectory.EndsWith(cleanedSubDirectory);
}
private static void EnsureDirectoryExists(string path)
{
Console.WriteLine("Validating directory...");
var exists = Directory.Exists(path);
if (!exists)
{
LogError($"The given directory {path} could not be found.");
EndProgram();
}
Console.WriteLine("Directory found.");
}
private static void EnsureFileNamesHasLength()
{
if (FileNames.Count == 0)
{
LogError("None of the discovered files are able to be processed. Please ensure the file names follow the '[SCHOOLID].pdf' format.");
EndProgram();
}
Console.WriteLine($"{FileNames.Count} files found.");
}
private static bool FileShouldBeProcessed(string fileName)
{
return Regex.Match(Path.GetFileName(fileName), "^[0-9]+.pdf").Success;
}
private static void FilterFilesToProcessable()
{
FileNames = FileNames.Where(n => FileShouldBeProcessed(n)).ToList();
}
private static void GetFiles()
{
Console.WriteLine("Getting directory contents...");
FileNames = Directory.GetFiles(Config.TargetDirectory).ToList();
}
private static void ProcessFile(string fileName)
{
GetNewFileName(fileName, Path.GetFileNameWithoutExtension(fileName)).GetAwaiter().GetResult();
}
private static void ProcessFiles()
{
Console.WriteLine("Processing files...");
CreateApiClient();
for (int i = 0; i < FileNames.Count; i++)
{
RenderProgress(i + 1);
var currentFile = FileNames[i];
try
{
ProcessFile(currentFile);
}
catch (Exception ex)
{
var error = $"Something went wrong while processing the file {currentFile}. [{ex.Message}]";
LogError(error);
CopyFileToResultFolder(false, currentFile, null, error);
}
}
DisposeApiClient();
Console.WriteLine();
Console.WriteLine("File processing complete.");
}
private static void SetResultDirectories()
{
var failedName = "Failed";
var successName = "Success";
var failedSubDirectory = Path.Combine(Config.CustomFieldName, failedName);
var successSubDirectory = Path.Combine(Config.CustomFieldName, successName);
//Check whether user is re-running existing failed jobs
if (DoesDirectoryContainSubDirectory(Config.TargetDirectory, failedSubDirectory))
{
CustomFieldResultDirectory_Failed = Config.TargetDirectory;
CustomFieldResultDirectory_Success = Config.TargetDirectory.TrimEnd(failedName.ToCharArray()) + successName;
}
else
{
CustomFieldResultDirectory_Failed = Path.Combine(Config.TargetDirectory, failedSubDirectory);
CustomFieldResultDirectory_Success = Path.Combine(Config.TargetDirectory, successSubDirectory);
}
}
#endregion
#region API Methods
private static async Task AuthenticateApi()
{
TokenResponse tokenResponse;
using (var httpClient = new HttpClient())
{
Console.WriteLine("Retrieving the discovery document...");
var discoveryDocumentResponse = await httpClient.GetDiscoveryDocumentAsync(Config.Authority);
if (discoveryDocumentResponse.IsError)
{
throw new AccessTokenException(
$"[{discoveryDocumentResponse.HttpStatusCode}] Error retrieving the discovery document [{discoveryDocumentResponse.Error}].");
}
Console.WriteLine("Retrieved the discovery document.");
var authTokenUrl = $"{Config.Domain.TrimEnd('/')}/{TokenPath.TrimStart('/')}";
var apiClientCredentials = new ClientCredentialsTokenRequest();
apiClientCredentials.Address = authTokenUrl;
apiClientCredentials.ClientId = Config.RestApiClientId;
apiClientCredentials.ClientSecret = Config.RestApiClientSecret;
apiClientCredentials.Scope = RestApiScope;
Console.WriteLine($"Authenticating {Config.RestApiClientId}...");
tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(apiClientCredentials);
if (tokenResponse.IsError)
{
throw new AccessTokenException(
$"[{tokenResponse.HttpStatusCode}] Error authenticating [{tokenResponse.Error}].");
}
AccessToken = tokenResponse.AccessToken;
Console.WriteLine("Authenticated successfully.");
}
}
private static void CreateApiClient()
{
var apiClient = new HttpClient();
apiClient.BaseAddress = new Uri($"{Config.Domain.TrimEnd('/')}/api");
apiClient.DefaultRequestHeaders.Clear();
apiClient.SetBearerToken(AccessToken);
SetRequestHeaders(apiClient, "application/hal+json");
ApiClient = apiClient;
}
private static void DisposeApiClient()
{
ApiClient.Dispose();
}
private static async Task GetNewFileName(string currentFileName, string schoolId)
{
var apiPath = $"{Config.Domain.TrimEnd('/')}{ApiEndpoint}";
apiPath = apiPath.Replace("{schoolId}", schoolId);
if (CustomFieldId > -1)
{
apiPath = $"{apiPath}/{CustomFieldId}";
}
var response = await InternalGetAsync(ApiClient, apiPath);
if (!response.IsSuccessStatusCode)
{
throw new RestApiException(apiPath,
$"[{response.StatusCode}] Error retrieving the Custom Field value [{response.ReasonPhrase}].");
}
var body = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(body))
{
throw new RestApiException(apiPath,
"Request succeeded but Custom Field is empty.");
}
var customFieldValues = JsonConvert.DeserializeObject<CustomFieldsCollection>(body).CustomFields;
CustomFieldValue customFieldValue;
if (CustomFieldId > -1)
{
customFieldValue = customFieldValues.FirstOrDefault();
}
else
{
customFieldValue = customFieldValues.FirstOrDefault(x => string.Equals(x.Name, Config.CustomFieldName, StringComparison.InvariantCultureIgnoreCase));
if (customFieldValue == null)
{
throw new RestApiException(apiPath,
$"Request succeeded but Custom Field '{Config.CustomFieldName}' could not be found.");
}
CustomFieldId = customFieldValue.Id;
}
if (string.IsNullOrEmpty(customFieldValue?.Value))
{
throw new RestApiException(apiPath,
"Request succeeded but Custom Field is empty.");
}
CopyFileToResultFolder(true, currentFileName, customFieldValue.Value);
}
private static Task<HttpResponseMessage> InternalGetAsync(HttpClient apiClient, string apiPath)
{
return apiClient.GetAsync(apiPath);
}
private static void SetRequestHeaders(HttpClient apiClient, string accept)
{
apiClient.DefaultRequestHeaders.Accept.Clear();
apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
}
#endregion
#region Console Methods
private static void EndProgram()
{
Console.WriteLine("This utility can now be closed.");
Console.ReadLine();
Environment.Exit(0);
}
private static void LogError(string message)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
private static void RenderProgress(int currentFileIndex)
{
var total = FileNames.Count;
Console.CursorLeft = 0;
Console.Write($"Processing {currentFileIndex} of {total} "); //blanks at the end remove any excess
}
#endregion
#region Summary Methods
private static void SaveSummary()
{
var logPath = Path.Combine(Directory.GetParent(CustomFieldResultDirectory_Success).FullName, $"event_log_{DateTime.Now.Ticks}.txt");
File.WriteAllLines(logPath, Summary.Log);
Console.WriteLine($"{Summary.SuccessfulRequests} Successful.");
Console.WriteLine($"{Summary.FailedRequests} Failed.");
Console.WriteLine($"Event log exported to {logPath}");
}
#endregion
}
}