Migrate aurora-sharp-desktop

This commit is contained in:
Brandon Watson
2021-03-05 23:10:12 -05:00
parent d6496355a9
commit b8c0dadf91
186 changed files with 8521 additions and 0 deletions

View File

@ -0,0 +1,25 @@
using System.Linq;
namespace Aurora.Utils
{
public static class Misc
{
public static string Combine(string[] args)
{
string outString = "";
foreach (string arg in args)
{
if (arg == args.Last())
{
outString += arg;
}
else
{
outString += arg + ":";
}
}
return outString;
}
}
}

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Aurora.Utils
{
public class FileSystemUtils
{
public FileSystemUtils()
{
}
/// <summary>
/// Asynchronousely recursively traverse a directory path.
/// </summary>
/// <param name="path">The path to the directory to traverse</param>
/// <param name="extensions">Comma separated list of file extensions to accept</param>
public static List<FileInfo> TraverseFoldersAsync(string path, string extensions)
{
string[] extensionList = extensions.Split(',');
ConcurrentBag<Task> tasks = new ConcurrentBag<Task>();
List<FileInfo> outFiles = new List<FileInfo>();
DirectoryInfo directoryInfo = new DirectoryInfo(path);
tasks.Add(Task.Run(() => Traverse(directoryInfo, tasks, outFiles, extensionList)));
Task waitingTask;
while (tasks.TryTake(out waitingTask))
{
waitingTask.Wait();
}
return outFiles;
}
/// <summary>
/// Recursive method to capture children of a directory.
/// </summary>
/// <param name="dir">The directory to traverse</param>
/// <param name="tasks">The list of currently running tasks</param>
private static void Traverse(DirectoryInfo dir, ConcurrentBag<Task> tasks, List<FileInfo> outFiles, string[] extensions)
{
try
{
DirectoryInfo[] directoryInfos = dir.GetDirectories();
//Enque children
foreach (DirectoryInfo childInfo in directoryInfos)
{
tasks.Add(Task.Run(() => Traverse(childInfo, tasks, outFiles, extensions)));
}
//Collect files
foreach (FileInfo fileInfo in dir.GetFiles())
{
if (extensions.Any(e => e == fileInfo.Extension))
{
//Don't know if this lock is necessary
lock (outFiles)
{
outFiles.Add(fileInfo);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType()} {ex.Message}\n{ex.StackTrace}");
ex = ex.InnerException;
}
}
}
}

View File

@ -0,0 +1,25 @@
using System.Security.Cryptography;
using System.Text;
using System;
namespace Aurora.Utils
{
public class HashUtil
{
public static Guid GetHash(string[] inputs)
{
string input = "";
foreach (string str in inputs)
{
input += str;
}
byte[] stringbytes = Encoding.UTF8.GetBytes(input);
byte[] hashedBytes = new System.Security.Cryptography
.SHA1CryptoServiceProvider()
.ComputeHash(stringbytes);
Array.Resize(ref hashedBytes, 16);
return new Guid(hashedBytes);
}
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Linq;
using System.Reflection;
namespace Aurora.Utils
{
public static class ReflectionUtils
{
private const char IndexBeginOp = '[';
private const char IndexEndOp = ']';
private const char PropertyOfOp = '.';
public static object GetValueByPath(object obj, string path)
{
object result = obj;
var tokens = path?.Split(IndexBeginOp, PropertyOfOp).ToList();
foreach (var token in tokens)
{
if (result == null)
break;
// Property
if (!token.Contains(IndexEndOp.ToString()))
{
result = GetPropertyValue(result, token);
}
// Index
else
{
result = GetIndexValue(result, token.Replace(IndexEndOp.ToString(), ""));
}
}
return result;
}
private static object GetPropertyValue(object obj, string propertyName)
{
try
{
return obj?.GetType().GetRuntimeProperty(propertyName)?.GetValue(obj);
}
catch
{
return null;
}
}
private static object GetIndexValue(object obj, string index)
{
object result = null;
var indexOperator = obj?.GetType().GetRuntimeProperty("Item");
if (indexOperator != null)
{
var indexParameters = indexOperator.GetIndexParameters();
// Looking up suitable index operator
foreach (var parameter in indexParameters)
{
bool isIndexOpWorked = true;
try
{
var indexVal = Convert.ChangeType(index, parameter.ParameterType);
result = indexOperator.GetValue(obj, new object[] { indexVal });
}
catch
{
isIndexOpWorked = false;
}
// If the index operator worked, skip looking up others
if (isIndexOpWorked)
break;
}
}
return result;
}
}
}

View File

@ -0,0 +1,85 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
namespace Aurora.Utils
{
public class Time
{
public Time(DateTime dateTime, TimeSpan elapsed)
{
this.DateTime = dateTime;
this.Elapsed = elapsed;
}
public DateTime DateTime { get; private set; }
public TimeSpan Elapsed { get; private set; }
}
public static class TimeUtils
{
public static Time GetNetworkTime()
{
Stopwatch stopwatch = new Stopwatch();
//default Windows time server
const string ntpServer = "time.windows.com";
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Connect(ipEndPoint);
//Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
stopwatch.Start();
socket.Send(ntpData);
stopwatch.Stop();
socket.Receive(ntpData);
socket.Close();
}
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
stopwatch.Stop();
return new Time(networkDateTime.ToLocalTime(), stopwatch.Elapsed); ;
}
// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
}