SortCodeMethods
DirectoryToISO TextToJson
This commit is contained in:
@ -43,8 +43,10 @@ internal static class Helper20230906
|
||||
httpRequestMessage.Headers.Add(segments[0], segments[1]);
|
||||
}
|
||||
}
|
||||
#pragma warning disable IL2026, IL3050
|
||||
if (jsonBodyLine is not null)
|
||||
httpRequestMessage.Content = JsonContent.Create(lines[jsonBodyLine.Value]);
|
||||
#pragma warning restore IL2026, IL3050
|
||||
httpClient = new(new HttpClientHandler { UseCookies = false }) { BaseAddress = new Uri(lines[0]) };
|
||||
if (userAgent is not null)
|
||||
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
|
@ -13,6 +13,7 @@ internal static class Helper20231122
|
||||
private static ReadOnlyCollection<Record> GetRecords(string sourceDirectory, string timestampFormat)
|
||||
{
|
||||
List<Record> results = [];
|
||||
Record record;
|
||||
string fileName;
|
||||
string equipment;
|
||||
string timestamp;
|
||||
@ -28,7 +29,8 @@ internal static class Helper20231122
|
||||
timestamp = segments[1].Split('.')[0];
|
||||
if (timestamp.Length != timestampFormat.Length)
|
||||
continue;
|
||||
results.Add(new(file, fileName, equipment, timestamp));
|
||||
record = new(file, fileName, equipment, timestamp);
|
||||
results.Add(record);
|
||||
}
|
||||
return new(results.OrderBy(l => l.TimeStamp).ToArray());
|
||||
}
|
@ -9,29 +9,6 @@ internal static class Helper20231130
|
||||
|
||||
private record Record(string File, string FileName, string Equipment, string TimeStamp);
|
||||
|
||||
private static ReadOnlyCollection<Record> GetRecords(string sourceDirectory, string timestampFormat)
|
||||
{
|
||||
List<Record> results = [];
|
||||
string fileName;
|
||||
string equipment;
|
||||
string timestamp;
|
||||
string[] segments;
|
||||
string[] files = Directory.GetFiles(sourceDirectory, "*.pdsf", SearchOption.TopDirectoryOnly).ToArray();
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileName = Path.GetFileName(file);
|
||||
segments = fileName.Split('_');
|
||||
if (segments.Length != 2)
|
||||
continue;
|
||||
equipment = segments[0];
|
||||
timestamp = segments[1].Split('.')[0];
|
||||
if (timestamp.Length != timestampFormat.Length)
|
||||
continue;
|
||||
results.Add(new(file, fileName, equipment, timestamp));
|
||||
}
|
||||
return new(results.OrderBy(l => l.TimeStamp).ToArray());
|
||||
}
|
||||
|
||||
private static ReadOnlyDictionary<string, string> GetSystemStates()
|
||||
{
|
||||
Dictionary<string, string> results = [];
|
||||
@ -50,6 +27,31 @@ internal static class Helper20231130
|
||||
return new(results);
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<Record> GetRecords(string sourceDirectory, string timestampFormat)
|
||||
{
|
||||
List<Record> results = [];
|
||||
Record record;
|
||||
string fileName;
|
||||
string equipment;
|
||||
string timestamp;
|
||||
string[] segments;
|
||||
string[] files = Directory.GetFiles(sourceDirectory, "*.pdsf", SearchOption.TopDirectoryOnly).ToArray();
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileName = Path.GetFileName(file);
|
||||
segments = fileName.Split('_');
|
||||
if (segments.Length != 2)
|
||||
continue;
|
||||
equipment = segments[0];
|
||||
timestamp = segments[1].Split('.')[0];
|
||||
if (timestamp.Length != timestampFormat.Length)
|
||||
continue;
|
||||
record = new(file, fileName, equipment, timestamp);
|
||||
results.Add(record);
|
||||
}
|
||||
return new(results.OrderBy(l => l.TimeStamp).ToArray());
|
||||
}
|
||||
|
||||
internal static void RenameReactorProcessDataStandardFormatFiles(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string line;
|
@ -6,6 +6,20 @@ namespace File_Folder_Helper.Day;
|
||||
internal static partial class Helper20231205
|
||||
{
|
||||
|
||||
private static string? GetStrippedMacAddress(string[] segments)
|
||||
{
|
||||
string? result = null;
|
||||
foreach (string segment in segments)
|
||||
{
|
||||
if (segment.Length != 17)
|
||||
continue;
|
||||
if (segment[2] is not ':' or '-' || segment[5] is not ':' or '-' || segment[8] is not ':' or '-' || segment[11] is not ':' or '-' || segment[14] is not ':' or '-')
|
||||
continue;
|
||||
result = $"{segment[0]}{segment[1]}{segment[3]}{segment[4]}{segment[6]}{segment[7]}{segment[9]}{segment[10]}{segment[12]}{segment[13]}{segment[15]}{segment[16]}".ToLower();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"[\\,\/,\:,\*,\?,\"",\<,\>,\|]")]
|
||||
private static partial Regex WindowsSafe();
|
||||
|
||||
@ -25,24 +39,11 @@ internal static partial class Helper20231205
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string? GetStrippedMacAddress(string[] segments)
|
||||
{
|
||||
string? result = null;
|
||||
foreach (string segment in segments)
|
||||
{
|
||||
if (segment.Length != 17)
|
||||
continue;
|
||||
if (segment[2] is not ':' or '-' || segment[5] is not ':' or '-' || segment[8] is not ':' or '-' || segment[11] is not ':' or '-' || segment[14] is not ':' or '-')
|
||||
continue;
|
||||
result = $"{segment[0]}{segment[1]}{segment[3]}{segment[4]}{segment[6]}{segment[7]}{segment[9]}{segment[10]}{segment[12]}{segment[13]}{segment[15]}{segment[16]}".ToLower();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static void SplitMarkdownFile(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string[] lines;
|
||||
string? fileName;
|
||||
Regex windowsSafe;
|
||||
string[] segments;
|
||||
string checkFileName;
|
||||
string? strippedIpV4;
|
||||
@ -69,7 +70,10 @@ internal static partial class Helper20231205
|
||||
strippedIpV4 = GetStrippedIPV4(segments);
|
||||
strippedMacAddress = GetStrippedMacAddress(segments);
|
||||
if (strippedMacAddress is null && strippedIpV4 is null)
|
||||
fileName = $"{WindowsSafe().Replace(line[3..], "-").Trim().ToLower()}.md";
|
||||
{
|
||||
windowsSafe = WindowsSafe();
|
||||
fileName = $"{windowsSafe.Replace(line[3..], "-").Trim().ToLower()}.md";
|
||||
}
|
||||
else if (strippedMacAddress is null)
|
||||
{
|
||||
fileName = $"ipv4-{strippedIpV4}.md";
|
@ -2,16 +2,12 @@ using Microsoft.Extensions.Logging;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20231212
|
||||
{
|
||||
|
||||
[GeneratedRegex(@"[\\,\/,\:,\*,\?,\"",\<,\>,\|]")]
|
||||
private static partial Regex WindowsSafe();
|
||||
|
||||
private record Debugging(
|
||||
[property: JsonPropertyName("Level")] int Level
|
||||
);
|
||||
@ -352,6 +348,16 @@ internal static partial class Helper20231212
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<ReadOnlyCollection<string>> GetHostLinesSpaceSegments()
|
||||
{
|
||||
List<ReadOnlyCollection<string>> results = [];
|
||||
string hostFile = "C:/Windows/System32/drivers/etc/hosts";
|
||||
string[] lines = !File.Exists(hostFile) ? [] : File.ReadAllLines(hostFile);
|
||||
foreach (string line in lines)
|
||||
results.Add(new(line.Split(' ')));
|
||||
return new(results);
|
||||
}
|
||||
|
||||
private static string[] GetMacAddressSegments(string value)
|
||||
{
|
||||
string[] result;
|
||||
@ -370,16 +376,6 @@ internal static partial class Helper20231212
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<ReadOnlyCollection<string>> GetHostLinesSpaceSegments()
|
||||
{
|
||||
List<ReadOnlyCollection<string>> results = [];
|
||||
string hostFile = "C:/Windows/System32/drivers/etc/hosts";
|
||||
string[] lines = !File.Exists(hostFile) ? [] : File.ReadAllLines(hostFile);
|
||||
foreach (string line in lines)
|
||||
results.Add(new(line.Split(' ')));
|
||||
return new(results);
|
||||
}
|
||||
|
||||
internal static void SplitJsonFile(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string json;
|
@ -33,53 +33,6 @@ internal static partial class Helper20231222
|
||||
private static short GetSortOrderOnlyLengthIndex(MetadataConfiguration metadataConfiguration) =>
|
||||
(short)metadataConfiguration.Offset.ToString().Length;
|
||||
|
||||
private static int GetId(MetadataConfiguration metadataConfiguration, string intelligentId)
|
||||
{
|
||||
int result;
|
||||
StringBuilder results = new();
|
||||
if (metadataConfiguration.IntMinValueLength < (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2))
|
||||
throw new NotSupportedException();
|
||||
for (int i = intelligentId.Length - (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2); i > -1; i--)
|
||||
_ = results.Append(intelligentId[i]);
|
||||
_ = results.Append(intelligentId[^3]).Append(intelligentId[^2]);
|
||||
result = int.Parse(results.ToString());
|
||||
if (intelligentId[^1] is '1' or '2')
|
||||
result *= -1;
|
||||
else if (intelligentId[^1] is not '9' and not '8')
|
||||
throw new NotSupportedException();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static IntelligentIdRecord GetIntelligentIdRecord(MetadataConfiguration metadataConfiguration, long id, bool ignore)
|
||||
{
|
||||
IntelligentIdRecord result;
|
||||
StringBuilder stringBuilder = new();
|
||||
if (metadataConfiguration.IntMinValueLength < (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2))
|
||||
throw new NotSupportedException();
|
||||
int key;
|
||||
string value;
|
||||
List<char> chars = [];
|
||||
if (id > -1)
|
||||
{
|
||||
key = ignore ? 8 : 9;
|
||||
value = id.ToString().PadLeft(metadataConfiguration.IntMinValueLength, '0');
|
||||
}
|
||||
else
|
||||
{
|
||||
key = ignore ? 2 : 1;
|
||||
value = id.ToString()[1..].PadLeft(metadataConfiguration.IntMinValueLength, '0');
|
||||
}
|
||||
for (int i = value.Length - metadataConfiguration.ResultAllInOneSubdirectoryLength - 1; i > -1; i--)
|
||||
_ = stringBuilder.Append(value[i]);
|
||||
for (int i = value.Length - metadataConfiguration.ResultAllInOneSubdirectoryLength; i < value.Length; i++)
|
||||
chars.Add(value[i]);
|
||||
result = new(key, new(chars), stringBuilder.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetIntelligentId(IntelligentIdRecord intelligentId) =>
|
||||
$"{intelligentId.Reverse}{string.Join(string.Empty, intelligentId.ResultAllInOneSubdirectoryChars)}{intelligentId.Key}";
|
||||
|
||||
private static bool NameWithoutExtensionIsIntelligentIdFormat(MetadataConfiguration metadataConfiguration, string fileNameFirstSegment) =>
|
||||
fileNameFirstSegment.Length - 1 == metadataConfiguration.IntMinValueLength && fileNameFirstSegment[^1] is '1' or '2' or '8' or '9' && fileNameFirstSegment.All(char.IsNumber);
|
||||
|
||||
@ -148,6 +101,53 @@ internal static partial class Helper20231222
|
||||
return result;
|
||||
}
|
||||
|
||||
private static IntelligentIdRecord GetIntelligentIdRecord(MetadataConfiguration metadataConfiguration, long id, bool ignore)
|
||||
{
|
||||
IntelligentIdRecord result;
|
||||
StringBuilder stringBuilder = new();
|
||||
if (metadataConfiguration.IntMinValueLength < (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2))
|
||||
throw new NotSupportedException();
|
||||
int key;
|
||||
string value;
|
||||
List<char> chars = [];
|
||||
if (id > -1)
|
||||
{
|
||||
key = ignore ? 8 : 9;
|
||||
value = id.ToString().PadLeft(metadataConfiguration.IntMinValueLength, '0');
|
||||
}
|
||||
else
|
||||
{
|
||||
key = ignore ? 2 : 1;
|
||||
value = id.ToString()[1..].PadLeft(metadataConfiguration.IntMinValueLength, '0');
|
||||
}
|
||||
for (int i = value.Length - metadataConfiguration.ResultAllInOneSubdirectoryLength - 1; i > -1; i--)
|
||||
_ = stringBuilder.Append(value[i]);
|
||||
for (int i = value.Length - metadataConfiguration.ResultAllInOneSubdirectoryLength; i < value.Length; i++)
|
||||
chars.Add(value[i]);
|
||||
result = new(key, new(chars), stringBuilder.ToString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string GetIntelligentId(IntelligentIdRecord intelligentId) =>
|
||||
$"{intelligentId.Reverse}{string.Join(string.Empty, intelligentId.ResultAllInOneSubdirectoryChars)}{intelligentId.Key}";
|
||||
|
||||
private static int GetId(MetadataConfiguration metadataConfiguration, string intelligentId)
|
||||
{
|
||||
int result;
|
||||
StringBuilder results = new();
|
||||
if (metadataConfiguration.IntMinValueLength < (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2))
|
||||
throw new NotSupportedException();
|
||||
for (int i = intelligentId.Length - (metadataConfiguration.ResultAllInOneSubdirectoryLength + 2); i > -1; i--)
|
||||
_ = results.Append(intelligentId[i]);
|
||||
_ = results.Append(intelligentId[^3]).Append(intelligentId[^2]);
|
||||
result = int.Parse(results.ToString());
|
||||
if (intelligentId[^1] is '1' or '2')
|
||||
result *= -1;
|
||||
else if (intelligentId[^1] is not '9' and not '8')
|
||||
throw new NotSupportedException();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<Record> GetRecords(MetadataConfiguration metadataConfiguration, string sourceDirectory, string searchPattern)
|
||||
{
|
||||
List<Record> results = [];
|
@ -1020,6 +1020,28 @@ internal static partial class Helper20240105
|
||||
{
|
||||
}
|
||||
|
||||
private static int GetDeterministicHashCode(byte[] value)
|
||||
{
|
||||
int result;
|
||||
unchecked
|
||||
{
|
||||
int hash1 = (5381 << 16) + 5381;
|
||||
int hash2 = hash1;
|
||||
for (int i = 0; i < value.Length; i += 2)
|
||||
{
|
||||
hash1 = ((hash1 << 5) + hash1) ^ value[i];
|
||||
if (i == value.Length - 1)
|
||||
break;
|
||||
hash2 = ((hash2 << 5) + hash2) ^ value[i + 1];
|
||||
}
|
||||
result = hash1 + (hash2 * 1566083941);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string? ConvertPassword(string? value) =>
|
||||
string.IsNullOrEmpty(value) ? "-" : GetDeterministicHashCode(System.Text.Encoding.ASCII.GetBytes(value)).ToString();
|
||||
|
||||
private static Item? GetEntry(Guid folderId, string folderName, KeePassFileGroupEntry keePassFileGroupEntry)
|
||||
{
|
||||
Item? result;
|
||||
@ -1081,29 +1103,109 @@ internal static partial class Helper20240105
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static int GetDeterministicHashCode(byte[] value)
|
||||
private static List<Item> GetItems(Guid folderId, string folderName, KeePassFileGroup keePassFileGroup)
|
||||
{
|
||||
int result;
|
||||
unchecked
|
||||
List<Item> results = [];
|
||||
if (keePassFileGroup.Entry is not null)
|
||||
{
|
||||
int hash1 = (5381 << 16) + 5381;
|
||||
int hash2 = hash1;
|
||||
for (int i = 0; i < value.Length; i += 2)
|
||||
Item? item;
|
||||
foreach (KeePassFileGroupEntry keePassFileGroupEntry in keePassFileGroup.Entry)
|
||||
{
|
||||
hash1 = ((hash1 << 5) + hash1) ^ value[i];
|
||||
if (i == value.Length - 1)
|
||||
break;
|
||||
hash2 = ((hash2 << 5) + hash2) ^ value[i + 1];
|
||||
item = GetEntry(folderId, folderName, keePassFileGroupEntry);
|
||||
if (item is null)
|
||||
continue;
|
||||
results.Add(item);
|
||||
}
|
||||
result = hash1 + (hash2 * 1566083941);
|
||||
}
|
||||
if (keePassFileGroup.Group is not null)
|
||||
{
|
||||
foreach (KeePassFileGroup keePassFileGroupInner in keePassFileGroup.Group)
|
||||
{
|
||||
folderId = Guid.NewGuid();
|
||||
results.AddRange(GetItems(folderId, $"{folderName}/{keePassFileGroupInner.Name}", keePassFileGroupInner));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static MemoryStream ToStream(string @this)
|
||||
{
|
||||
MemoryStream memoryStream = new();
|
||||
StreamWriter streamWriter = new(memoryStream);
|
||||
streamWriter.Write(@this);
|
||||
streamWriter.Flush();
|
||||
memoryStream.Position = 0;
|
||||
return memoryStream;
|
||||
}
|
||||
|
||||
private static KeePassFile? ParseXML(string value, bool throwExceptions)
|
||||
{
|
||||
KeePassFile? result;
|
||||
try
|
||||
{
|
||||
Type type = typeof(KeePassFile);
|
||||
Stream stream = ToStream(value.Trim());
|
||||
XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
|
||||
#pragma warning disable IL2026
|
||||
XmlSerializer xmlSerializer = new(type, type.GetNestedTypes());
|
||||
result = xmlSerializer.Deserialize(xmlReader) as KeePassFile;
|
||||
#pragma warning restore IL2026
|
||||
stream.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (throwExceptions)
|
||||
throw;
|
||||
result = null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string? ConvertPassword(string? value) =>
|
||||
// string.IsNullOrEmpty(value) ? "-" : string.Join('-', from l in value select l);
|
||||
// string.IsNullOrEmpty(value) ? "-" : string.Join('-', from l in value orderby random.Next() select l);
|
||||
string.IsNullOrEmpty(value) ? "-" : GetDeterministicHashCode(System.Text.Encoding.ASCII.GetBytes(value)).ToString();
|
||||
private static List<Item> GetItems(KeePassFileRoot keePassFileRoot)
|
||||
{
|
||||
List<Item> results = [];
|
||||
Guid folderId = Guid.NewGuid();
|
||||
string folderName = string.Empty;
|
||||
if (keePassFileRoot.Entry is not null)
|
||||
{
|
||||
Item? item;
|
||||
foreach (KeePassFileGroupEntry keePassFileGroupEntry in keePassFileRoot.Entry)
|
||||
{
|
||||
item = GetEntry(folderId, folderName, keePassFileGroupEntry);
|
||||
if (item is null)
|
||||
continue;
|
||||
results.Add(item);
|
||||
}
|
||||
}
|
||||
if (keePassFileRoot.Group is not null)
|
||||
{
|
||||
foreach (KeePassFileGroup keePassFileGroup in keePassFileRoot.Group)
|
||||
{
|
||||
folderId = Guid.NewGuid();
|
||||
folderName = keePassFileGroup.Name;
|
||||
results.AddRange(GetItems(folderId, folderName, keePassFileGroup));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static List<Folder> GetFolders(List<Item> items)
|
||||
{
|
||||
List<Folder> results = [];
|
||||
Folder folder;
|
||||
List<string> distinct = [];
|
||||
foreach (Item item in items)
|
||||
{
|
||||
if (item.FolderName is null)
|
||||
throw new NullReferenceException(nameof(item.FolderName));
|
||||
if (distinct.Contains(item.FolderName))
|
||||
continue;
|
||||
distinct.Add(item.FolderName);
|
||||
folder = new(item.FolderId, item.FolderName);
|
||||
results.Add(folder);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static List<Item> Filter(string xmlFile, ILogger<Worker> logger, List<Item> items)
|
||||
{
|
||||
@ -1208,110 +1310,6 @@ internal static partial class Helper20240105
|
||||
File.WriteAllLines(Path.ChangeExtension(xmlFile, ".tvs"), lines);
|
||||
}
|
||||
|
||||
private static MemoryStream ToStream(string @this)
|
||||
{
|
||||
MemoryStream memoryStream = new();
|
||||
StreamWriter streamWriter = new(memoryStream);
|
||||
streamWriter.Write(@this);
|
||||
streamWriter.Flush();
|
||||
memoryStream.Position = 0;
|
||||
return memoryStream;
|
||||
}
|
||||
|
||||
private static KeePassFile? ParseXML(string @this, bool throwExceptions)
|
||||
{
|
||||
KeePassFile? result;
|
||||
try
|
||||
{
|
||||
Type type = typeof(KeePassFile);
|
||||
Stream stream = ToStream(@this.Trim());
|
||||
XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
|
||||
#pragma warning disable IL2026
|
||||
XmlSerializer xmlSerializer = new(type, type.GetNestedTypes());
|
||||
result = xmlSerializer.Deserialize(xmlReader) as KeePassFile;
|
||||
#pragma warning restore IL2026
|
||||
stream.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (throwExceptions)
|
||||
throw;
|
||||
result = null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<Item> GetItems(Guid folderId, string folderName, KeePassFileGroup keePassFileGroup)
|
||||
{
|
||||
List<Item> results = [];
|
||||
if (keePassFileGroup.Entry is not null)
|
||||
{
|
||||
Item? item;
|
||||
foreach (KeePassFileGroupEntry keePassFileGroupEntry in keePassFileGroup.Entry)
|
||||
{
|
||||
item = GetEntry(folderId, folderName, keePassFileGroupEntry);
|
||||
if (item is null)
|
||||
continue;
|
||||
results.Add(item);
|
||||
}
|
||||
}
|
||||
if (keePassFileGroup.Group is not null)
|
||||
{
|
||||
foreach (KeePassFileGroup keePassFileGroupInner in keePassFileGroup.Group)
|
||||
{
|
||||
folderId = Guid.NewGuid();
|
||||
results.AddRange(GetItems(folderId, $"{folderName}/{keePassFileGroupInner.Name}", keePassFileGroupInner));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static List<Item> GetItems(KeePassFileRoot keePassFileRoot)
|
||||
{
|
||||
List<Item> results = [];
|
||||
Guid folderId = Guid.NewGuid();
|
||||
string folderName = string.Empty;
|
||||
if (keePassFileRoot.Entry is not null)
|
||||
{
|
||||
Item? item;
|
||||
foreach (KeePassFileGroupEntry keePassFileGroupEntry in keePassFileRoot.Entry)
|
||||
{
|
||||
item = GetEntry(folderId, folderName, keePassFileGroupEntry);
|
||||
if (item is null)
|
||||
continue;
|
||||
results.Add(item);
|
||||
}
|
||||
}
|
||||
if (keePassFileRoot.Group is not null)
|
||||
{
|
||||
foreach (KeePassFileGroup keePassFileGroup in keePassFileRoot.Group)
|
||||
{
|
||||
folderId = Guid.NewGuid();
|
||||
folderName = keePassFileGroup.Name;
|
||||
results.AddRange(GetItems(folderId, folderName, keePassFileGroup));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static List<Folder> GetFolders(List<Item> items)
|
||||
{
|
||||
List<Folder> results = [];
|
||||
Folder folder;
|
||||
List<string> distinct = [];
|
||||
foreach (Item item in items)
|
||||
{
|
||||
if (item.FolderName is null)
|
||||
throw new NullReferenceException(nameof(item.FolderName));
|
||||
if (distinct.Contains(item.FolderName))
|
||||
continue;
|
||||
distinct.Add(item.FolderName);
|
||||
folder = new(item.FolderId, item.FolderName);
|
||||
results.Add(folder);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static void ConvertKeePassExport(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
Root root;
|
128
Day/2024-Q1/Helper-2024-01-06.cs
Normal file
128
Day/2024-Q1/Helper-2024-01-06.cs
Normal file
@ -0,0 +1,128 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20240106
|
||||
{
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(Dictionary<string, Dictionary<string, string>>))]
|
||||
private partial class DictionaryDictionarySourceGenerationContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
|
||||
private record Record(string Key, Dictionary<string, string> KeyValuePairs);
|
||||
|
||||
private static Dictionary<string, Dictionary<string, string>> GetKeyValuePairs(List<Record> collection, bool replaceFound)
|
||||
{
|
||||
Dictionary<string, Dictionary<string, string>> results = [];
|
||||
if (replaceFound)
|
||||
{
|
||||
foreach ((string key, Dictionary<string, string> keyValuePairs) in collection)
|
||||
_ = results.TryAdd(key, keyValuePairs);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach ((string key, Dictionary<string, string> keyValuePairs) in collection.OrderBy(l => l.Key))
|
||||
_ = results.TryAdd(key, keyValuePairs);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static int? GetHeaderLine(string[] lines)
|
||||
{
|
||||
int? headerLine = null;
|
||||
for (int i = 0; i < lines.Length - 1; i++)
|
||||
{
|
||||
if (!lines[i].Contains('\t'))
|
||||
continue;
|
||||
headerLine = i;
|
||||
}
|
||||
return headerLine;
|
||||
}
|
||||
|
||||
private static Dictionary<string, Dictionary<string, string>> GetKeyValuePairs(int keyIndex, int keyLength, string replace, string[] headers, string[] lines, int headerLine)
|
||||
{
|
||||
Dictionary<string, Dictionary<string, string>> results;
|
||||
string? key;
|
||||
Record record;
|
||||
bool replaceFound = false;
|
||||
List<Record> collection = [];
|
||||
Dictionary<string, string> keyValuePairs;
|
||||
for (int i = headerLine + 1; i < lines.Length; i++)
|
||||
{
|
||||
key = null;
|
||||
keyValuePairs = [];
|
||||
for (int j = 0; j < headers.Length; j++)
|
||||
{
|
||||
if (j > 0)
|
||||
i++;
|
||||
if (lines.Length <= i)
|
||||
{
|
||||
keyValuePairs.Clear();
|
||||
break;
|
||||
}
|
||||
if (j == keyIndex)
|
||||
{
|
||||
key = lines[i];
|
||||
if (key.Length != keyLength)
|
||||
{
|
||||
keyValuePairs.Clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lines[i] != replace)
|
||||
_ = keyValuePairs.TryAdd(headers[j], lines[i]);
|
||||
else
|
||||
{
|
||||
if (!replaceFound)
|
||||
replaceFound = true;
|
||||
_ = keyValuePairs.TryAdd(headers[j], lines[i]);
|
||||
j++;
|
||||
_ = keyValuePairs.TryAdd(headers[j], lines[i]);
|
||||
}
|
||||
}
|
||||
if (keyValuePairs.Count != headers.Length)
|
||||
continue;
|
||||
key ??= "-";
|
||||
record = new(key, keyValuePairs);
|
||||
collection.Add(record);
|
||||
}
|
||||
results = GetKeyValuePairs(collection, replaceFound);
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static void TextToJson(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string json;
|
||||
string[] lines;
|
||||
int? headerLine;
|
||||
FileInfo fileInfo;
|
||||
string replace = args[6];
|
||||
int keyIndex = int.Parse(args[4]);
|
||||
int keyLength = int.Parse(args[5]);
|
||||
string[] headers = args[7].Split(',');
|
||||
string[] txtFiles = Directory.GetFiles(args[0], args[2]);
|
||||
Dictionary<string, Dictionary<string, string>> keyValuePairs;
|
||||
foreach (string txtFile in txtFiles)
|
||||
{
|
||||
lines = File.ReadAllLines(txtFile);
|
||||
if (lines.Length == 0)
|
||||
continue;
|
||||
headerLine = GetHeaderLine(lines);
|
||||
if (headerLine is null)
|
||||
continue;
|
||||
fileInfo = new(txtFile);
|
||||
keyValuePairs = GetKeyValuePairs(keyIndex, keyLength, replace, headers, lines, headerLine.Value);
|
||||
if (keyValuePairs.Count == 0)
|
||||
continue;
|
||||
json = JsonSerializer.Serialize(keyValuePairs, DictionaryDictionarySourceGenerationContext.Default.DictionaryStringDictionaryStringString);
|
||||
logger.LogInformation("Writing output file...");
|
||||
File.WriteAllText($"{txtFile}-{fileInfo.LastWriteTime.Ticks}.json", json);
|
||||
File.WriteAllText(txtFile, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
38
Day/2024-Q1/Helper-2024-01-07.cs
Normal file
38
Day/2024-Q1/Helper-2024-01-07.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using DiscUtils.Iso9660;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20240107
|
||||
{
|
||||
|
||||
private static void DirectoryToISO(ILogger<Worker> logger, string destinationDirectory, string directory)
|
||||
{
|
||||
string relativePath;
|
||||
string directoryName = Path.GetFileName(directory);
|
||||
CDBuilder builder = new() { UseJoliet = true, VolumeIdentifier = directoryName };
|
||||
IEnumerable<string> files = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories);
|
||||
foreach (string file in files)
|
||||
{
|
||||
relativePath = Path.GetRelativePath(directory, file);
|
||||
_ = builder.AddFile(relativePath, file);
|
||||
}
|
||||
logger.LogInformation(destinationDirectory);
|
||||
builder.Build(Path.Combine(destinationDirectory, $"{directoryName}.iso"));
|
||||
logger.LogInformation(directoryName);
|
||||
}
|
||||
|
||||
internal static void DirectoryToISO(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string sourceDirectory = args[0];
|
||||
int directories = int.Parse(args[2]);
|
||||
string destinationDirectory = args[3];
|
||||
logger.LogInformation(sourceDirectory);
|
||||
string[] subDirectories = directories == 1 ? [sourceDirectory] : Directory.GetDirectories(sourceDirectory, "*", SearchOption.TopDirectoryOnly);
|
||||
if (subDirectories.Length != directories)
|
||||
throw new Exception($"{directories} != {subDirectories.Length}");
|
||||
foreach (string directory in subDirectories)
|
||||
DirectoryToISO(logger, destinationDirectory, directory);
|
||||
}
|
||||
|
||||
}
|
280
Day/2024-Q1/Helper-2024-01-08.cs
Normal file
280
Day/2024-Q1/Helper-2024-01-08.cs
Normal file
@ -0,0 +1,280 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20240108
|
||||
{
|
||||
|
||||
private record Method(string Name,
|
||||
int ParameterCount,
|
||||
int StartLine,
|
||||
int EndLine,
|
||||
int FirstUsedLine);
|
||||
|
||||
[GeneratedRegex(@"(?<method>[A-Z]{1}[A-Za-z_0-9]*)\(")]
|
||||
private static partial Regex CSharpMethodName();
|
||||
|
||||
[GeneratedRegex(@"\s[a-zA-Z_]*,")]
|
||||
private static partial Regex CSharpParameter();
|
||||
|
||||
[GeneratedRegex(@"\b(public|private|internal|protected)\s\b(static)?\s?\b(partial)?\s?\b(async)?\s?[[\]<,>?a-zA-Z()\s]*\s[A-Z]{1}[a-zA-Z_]+\(.*\)")]
|
||||
private static partial Regex CSharpMethodLine();
|
||||
|
||||
private static string? GetName(string line)
|
||||
{
|
||||
string? result;
|
||||
Match match = CSharpMethodName().Match(line);
|
||||
if (!match.Success)
|
||||
result = null;
|
||||
else
|
||||
result = match.Groups["method"].Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int GetStartLine(string[] lines, int i)
|
||||
{
|
||||
int result = i;
|
||||
string line;
|
||||
for (int j = i - 1; j > -1; j--)
|
||||
{
|
||||
line = lines[j].Trim();
|
||||
if (!line.StartsWith('[') && !line.StartsWith("/// "))
|
||||
break;
|
||||
result--;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int GetParameterCount(string line, string search)
|
||||
{
|
||||
int result;
|
||||
string after = line.Split(search)[^1];
|
||||
if (after.StartsWith(')'))
|
||||
result = 0;
|
||||
else
|
||||
{
|
||||
string[] segments = CSharpParameter().Split(after);
|
||||
result = segments.Length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int GetLineBlockCount(string line, bool isLinq)
|
||||
{
|
||||
int result = 0;
|
||||
bool ignore = false;
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
{
|
||||
if (line[i] == '\'')
|
||||
i++;
|
||||
else if (!isLinq && !ignore && line[i] == '{')
|
||||
result++;
|
||||
else if (!isLinq && !ignore && line[i] == '}')
|
||||
result--;
|
||||
else if (isLinq && !ignore && line[i] == ';')
|
||||
result--;
|
||||
else if (i > 0 && line[i] == '"' && line[i - 1] != '\\')
|
||||
ignore = !ignore;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int? GetFirstUsedLine(string[] lines, int i, string search, string searchNot, string searchWrap, string searchConstructor, int parameterCount)
|
||||
{
|
||||
int? result = null;
|
||||
string[] segments;
|
||||
string[] afterSegments;
|
||||
string lastSegmentBeforeDot;
|
||||
for (int j = 0; j < lines.Length; j++)
|
||||
{
|
||||
if (j == i)
|
||||
continue;
|
||||
segments = lines[j].Split(search);
|
||||
if (segments.Length == 1)
|
||||
{
|
||||
segments = lines[j].Split(searchNot);
|
||||
if (segments.Length == 1)
|
||||
{
|
||||
segments = lines[j].Split(searchWrap);
|
||||
if (segments.Length == 1)
|
||||
{
|
||||
segments = lines[j].Split(searchConstructor);
|
||||
if (segments.Length == 1)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
lastSegmentBeforeDot = segments[^1].Split(").")[0];
|
||||
if (parameterCount == 0)
|
||||
{
|
||||
if (lastSegmentBeforeDot.Contains(','))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
afterSegments = lastSegmentBeforeDot.Split(',');
|
||||
if (afterSegments.Length != parameterCount)
|
||||
continue;
|
||||
}
|
||||
result = j;
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<int> GetMethodLines(ReadOnlyCollection<Method> methods)
|
||||
{
|
||||
List<int> results = [];
|
||||
foreach (Method method in methods)
|
||||
{
|
||||
for (int i = method.StartLine; i < method.EndLine + 1; i++)
|
||||
results.Add(i);
|
||||
}
|
||||
return new(results);
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<Method> GetMethods(string cSharpFile, ILogger<Worker> logger, string[] lines)
|
||||
{
|
||||
List<Method> results = [];
|
||||
int blocks;
|
||||
bool isLinq;
|
||||
int endLine;
|
||||
string line;
|
||||
string? name;
|
||||
int startLine;
|
||||
string search;
|
||||
string innerLine;
|
||||
string searchNot;
|
||||
string searchWrap;
|
||||
int parameterCount;
|
||||
int? firstUsedLine;
|
||||
string lineSegmentFirst;
|
||||
string searchConstructor;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
line = lines[i].Trim();
|
||||
if (string.IsNullOrEmpty(line))
|
||||
continue;
|
||||
if (line.Length < 5)
|
||||
continue;
|
||||
if (line.EndsWith(','))
|
||||
continue;
|
||||
if (!CSharpMethodLine().Match(line).Success)
|
||||
continue;
|
||||
name = GetName(line);
|
||||
search = $" {name}(";
|
||||
searchNot = $"!{name}(";
|
||||
searchWrap = $"({name}(";
|
||||
if (string.IsNullOrEmpty(name))
|
||||
continue;
|
||||
blocks = 0;
|
||||
searchConstructor = $"{name.ToLower()} = new(";
|
||||
startLine = GetStartLine(lines, i);
|
||||
parameterCount = GetParameterCount(line, search);
|
||||
isLinq = lines[i + 1].Trim() != "{";
|
||||
if (isLinq)
|
||||
blocks++;
|
||||
for (int j = i + 1; j < lines.Length; j++)
|
||||
{
|
||||
innerLine = lines[j].Trim();
|
||||
if (isLinq && string.IsNullOrEmpty(innerLine))
|
||||
{
|
||||
if (line.EndsWith(';'))
|
||||
blocks--;
|
||||
}
|
||||
blocks += GetLineBlockCount(innerLine, isLinq);
|
||||
if (blocks == 0)
|
||||
{
|
||||
endLine = j;
|
||||
if (lines.Length > j + 1 && string.IsNullOrEmpty(lines[j + 1].Trim()))
|
||||
endLine++;
|
||||
firstUsedLine = GetFirstUsedLine(lines, i, search, searchNot, searchWrap, searchConstructor, parameterCount);
|
||||
if (firstUsedLine is null)
|
||||
{
|
||||
lineSegmentFirst = line.Split(search)[0];
|
||||
if (!lines[i - 1].Trim().StartsWith("[Obsolete"))
|
||||
{
|
||||
if (lineSegmentFirst.StartsWith("private"))
|
||||
logger.LogWarning("<{cSharpFileName}> {name} with {parameterCount} parameter(s) <{line}>", Path.GetFileName(cSharpFile), name, parameterCount, lineSegmentFirst);
|
||||
else
|
||||
logger.LogInformation("<{cSharpFileName}> {name} with {parameterCount} parameter(s) <{line}>", Path.GetFileName(cSharpFile), name, parameterCount, lineSegmentFirst);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (j > lines.Length - 2)
|
||||
throw new Exception();
|
||||
results.Add(new(name, parameterCount, startLine, endLine, firstUsedLine.Value));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new(results.OrderBy(l => l.FirstUsedLine).ToArray());
|
||||
}
|
||||
|
||||
private static bool WriteAllLines(string cSharpFile, string[] lines, ReadOnlyCollection<Method> methods)
|
||||
{
|
||||
bool result;
|
||||
List<string> results = [];
|
||||
ReadOnlyCollection<int> methodLines = GetMethodLines(methods);
|
||||
int minMethodLines = methodLines.Min();
|
||||
for (int i = 0; i < minMethodLines; i++)
|
||||
results.Add(lines[i]);
|
||||
foreach (Method method in methods)
|
||||
{
|
||||
for (int i = method.StartLine; i < method.EndLine + 1; i++)
|
||||
results.Add(lines[i]);
|
||||
}
|
||||
for (int i = minMethodLines; i < lines.Length; i++)
|
||||
{
|
||||
if (methodLines.Contains(i))
|
||||
continue;
|
||||
results.Add(lines[i]);
|
||||
}
|
||||
string text = File.ReadAllText(cSharpFile);
|
||||
string join = string.Join(Environment.NewLine, results);
|
||||
if (join == text)
|
||||
result = false;
|
||||
else
|
||||
{
|
||||
result = true;
|
||||
File.WriteAllText(cSharpFile, join);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool SortFile(ILogger<Worker> logger, string cSharpFile, string[] lines)
|
||||
{
|
||||
bool result;
|
||||
ReadOnlyCollection<Method> methods = GetMethods(cSharpFile, logger, lines);
|
||||
if (methods.Count == 0)
|
||||
result = false;
|
||||
else
|
||||
result = WriteAllLines(cSharpFile, lines, methods);
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static void SortCodeMethods(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
bool result = false;
|
||||
bool check;
|
||||
string[] lines;
|
||||
long ticks = DateTime.Now.Ticks;
|
||||
logger.LogInformation("{ticks}", ticks);
|
||||
string[] cSharpFiles = Directory.GetFiles(args[0], "*.cs", SearchOption.TopDirectoryOnly);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
foreach (string cSharpFile in cSharpFiles)
|
||||
{
|
||||
lines = File.ReadAllLines(cSharpFile);
|
||||
check = SortFile(logger, cSharpFile, lines);
|
||||
if (check && !result)
|
||||
result = true;
|
||||
}
|
||||
if (!result)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -34,6 +34,12 @@ internal static class HelperDay
|
||||
Day.Helper20231222.ConvertId(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-01-05")
|
||||
Day.Helper20240105.ConvertKeePassExport(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-01-06")
|
||||
Day.Helper20240106.TextToJson(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-01-07")
|
||||
Day.Helper20240107.DirectoryToISO(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-01-08")
|
||||
Day.Helper20240108.SortCodeMethods(logger, args);
|
||||
else
|
||||
throw new Exception(appSettings.Company);
|
||||
}
|
||||
|
Reference in New Issue
Block a user