/Console/ConsoleExtensions.cs |
@@ -69,7 +69,8 @@ |
switch (alignment) |
{ |
case ConsoleTextAlignment.TOP_CENTER: |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, 0); |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, |
0); |
System.Console.WriteLine(data); |
break; |
|
@@ -83,7 +84,8 @@ |
switch (alignment) |
{ |
case ConsoleTextAlignment.TOP_CENTER: |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, 0); |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, |
0); |
WriteLine(data, foregroundColor); |
break; |
|
@@ -101,7 +103,8 @@ |
switch (alignment) |
{ |
case ConsoleTextAlignment.TOP_CENTER: |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, 0); |
System.Console.CursorLeft = Math.Max(System.Console.WindowWidth / 2 - data.ToString().Length / 2, |
0); |
System.Console.Write(data); |
break; |
|
@@ -121,7 +124,8 @@ |
case ConsoleTextAlignment.TOP_CENTER: |
var enumerable = data as IList<object> ?? data.ToList(); |
var textBlock = enumerable.Select(o => o.ToString()).ToArray(); |
var padding = Math.Max(System.Console.WindowWidth / 2 - textBlock.Select(o => o.Length).Max() / 2, 0); |
var padding = Math.Max(System.Console.WindowWidth / 2 - textBlock.Select(o => o.Length).Max() / 2, |
0); |
foreach (var line in enumerable) |
{ |
System.Console.CursorLeft = padding; |
@@ -131,9 +135,7 @@ |
|
case ConsoleTextAlignment.TOP_LEFT: |
foreach (var line in data) |
{ |
WriteLine(line, System.Console.ForegroundColor); |
} |
break; |
|
default: |
/Cryptography/SHA1.cs |
@@ -5,7 +5,9 @@ |
/////////////////////////////////////////////////////////////////////////// |
|
using System; |
using System.Collections.Generic; |
using System.IO; |
using System.Linq; |
using System.Text; |
using System.Threading.Tasks; |
|
@@ -24,6 +26,16 @@ |
} |
|
/// <summary> |
/// Return a 40 character hex representation of a SHA1 hash from multiple sequential byte arrays. |
/// </summary> |
/// <param name="sha1">the SHA1 hash object</param> |
/// <param name="data">the byte data to compute the hash from</param> |
public static string ToHex(this System.Security.Cryptography.SHA1 sha1, IEnumerable<byte[]> data) |
{ |
return sha1.ToHex(data.Where(i => i != null).SelectMany(i => i).ToArray()); |
} |
|
/// <summary> |
/// Return a 40 character hex representation of a SHA1 hash. |
/// </summary> |
/// <param name="sha1">the SHA1 hash object</param> |
@@ -65,13 +77,13 @@ |
public static async Task CopyToAsync(this System.Security.Cryptography.SHA1 sha1, byte[] data, Stream outStream) |
{ |
var buffer = new char[1]; |
using (MemoryStream SHA1OutputStream = new MemoryStream()) |
using (var SHA1OutputStream = new MemoryStream()) |
{ |
using (StringReader SHA1InputStream = new StringReader(BitConverter.ToString(sha1.ComputeHash(data)).Replace("-", ""))) |
using (var SHA1InputStream = |
new StringReader(BitConverter.ToString(sha1.ComputeHash(data)).Replace("-", ""))) |
{ |
int count; |
while ((count = await SHA1InputStream.ReadAsync(buffer, 0, 1)) != 0) |
{ |
switch (buffer[0]) |
{ |
case '-': |
@@ -81,10 +93,9 @@ |
break; |
} |
} |
} |
SHA1OutputStream.Position = 0L; |
await SHA1OutputStream.CopyToAsync(outStream); |
} |
} |
} |
} |
} |
/IO/Utilities/IOExtensions.cs |
@@ -4,6 +4,8 @@ |
// rights of fair usage, the disclaimer and warranty conditions. // |
/////////////////////////////////////////////////////////////////////////// |
|
using System; |
using System.Diagnostics; |
using System.IO; |
|
namespace wasSharpNET.IO.Utilities |
@@ -10,6 +12,34 @@ |
{ |
public static class IOExtensions |
{ |
/// <summary> |
/// Attempt to obtain a filestream by polling a file till the handle becomes available. |
/// </summary> |
/// <param name="path">the path to the file</param> |
/// <param name="mode">the file mode to use</param> |
/// <param name="access">the level of access to the file</param> |
/// <param name="share">the type of file share locking</param> |
/// <param name="timeout">the timeout in milliseconds to fail opening the file</param> |
/// <returns>a filestream if the file was opened successfully</returns> |
public static FileStream GetWriteStream(string path, FileMode mode, FileAccess access, FileShare share, |
int timeout) |
{ |
var time = Stopwatch.StartNew(); |
while (time.ElapsedMilliseconds < timeout) |
try |
{ |
return new FileStream(path, mode, access, share); |
} |
catch (IOException e) |
{ |
// access error |
if (e.HResult != -2147024864) |
throw; |
} |
|
throw new TimeoutException($"Failed to get a write handle to {path} within {timeout}ms."); |
} |
|
public static bool isRootedIn(this string path, string root) |
{ |
// Path is empty and root is empty. |
@@ -28,8 +58,8 @@ |
if (string.IsNullOrEmpty(path)) |
return true; |
|
DirectoryInfo p = new DirectoryInfo(path); |
DirectoryInfo r = new DirectoryInfo(root); |
var p = new DirectoryInfo(path); |
var r = new DirectoryInfo(root); |
|
return string.Equals(p.Parent?.FullName, r.Parent?.FullName) || isRootedIn(p.Parent?.FullName, root); |
} |
@@ -36,14 +66,12 @@ |
|
public static void Empty(this string directory) |
{ |
DirectoryInfo dir = new DirectoryInfo(directory); |
var dir = new DirectoryInfo(directory); |
|
foreach (FileInfo fi in dir.GetFiles()) |
{ |
foreach (var fi in dir.GetFiles()) |
fi.Delete(); |
} |
|
foreach (DirectoryInfo di in dir.GetDirectories()) |
foreach (var di in dir.GetDirectories()) |
{ |
Empty(di.FullName); |
di.Delete(); |
/Network/HTTP/HTTPServer.cs |
@@ -13,6 +13,9 @@ |
{ |
public abstract class HTTPServer : IDisposable |
{ |
private readonly ManualResetEventSlim listenStop = new ManualResetEventSlim(false); |
|
private readonly ManualResetEventSlim stopListen = new ManualResetEventSlim(false); |
private int activeRequests; |
|
private HttpListener HTTPListener; |
@@ -24,8 +27,10 @@ |
|
public bool IsRunning => HTTPListener != null && HTTPListener.IsListening; |
|
private readonly ManualResetEventSlim stopListen = new ManualResetEventSlim(false); |
private readonly ManualResetEventSlim listenStop = new ManualResetEventSlim(false); |
public void Dispose() |
{ |
stopListen.Set(); |
} |
|
public bool Start(List<string> prefixes) |
{ |
@@ -37,9 +42,7 @@ |
// Add all prefixes. |
HTTPListener.Prefixes.Clear(); |
foreach (var prefix in prefixes) |
{ |
HTTPListener.Prefixes.Add(prefix); |
} |
|
// Do not bomb if the client disconnects. |
HTTPListener.IgnoreWriteExceptions = true; |
@@ -55,7 +58,7 @@ |
|
private void Listen(object state) |
{ |
HTTPServerCallbackState callbackState = (HTTPServerCallbackState)state; |
var callbackState = (HTTPServerCallbackState) state; |
|
while (callbackState.Listener.IsListening) |
{ |
@@ -111,11 +114,6 @@ |
} |
} |
|
public void Dispose() |
{ |
stopListen.Set(); |
} |
|
private class HTTPServerCallbackState |
{ |
public HTTPServerCallbackState(HttpListener listener) |
/Network/SubnetMask.cs |
@@ -30,11 +30,14 @@ |
var binaryMask = new byte[4]; |
|
for (var i = 0; i < 4; i++) |
if (i * 8 + 8 <= netPartLength) |
{ |
if (i * 8 + 8 <= netPartLength) |
binaryMask[i] = 255; |
} |
else if (i * 8 > netPartLength) |
{ |
binaryMask[i] = 0; |
} |
else |
{ |
var oneLength = netPartLength - i * 8; |
@@ -42,7 +45,6 @@ |
string.Empty.PadLeft(oneLength, '1').PadRight(8, '0'); |
binaryMask[i] = Convert.ToByte(binaryDigit, 2); |
} |
} |
return new IPAddress(binaryMask); |
} |
|
/Platform/Windows/Commands/NetSH/URLACL.cs |
@@ -14,11 +14,11 @@ |
public class URLACL |
{ |
private readonly string domain; |
private readonly int timeout; |
private readonly string URL; |
|
private readonly Regex URLReservationRegex; |
private readonly string username; |
private readonly int timeout; |
|
public URLACL(string URL, string username, string domain, int timeout) |
{ |
@@ -53,9 +53,7 @@ |
checkProcess.OutputDataReceived += (sender, output) => |
{ |
if (output?.Data != null) |
{ |
netSHOutput.Append(output.Data); |
} |
}; |
|
checkProcess.Start(); |
@@ -84,10 +82,8 @@ |
{ |
// User cancelled the UAC elevation prompt. |
if (ex.NativeErrorCode == 1223) |
{ |
return false; |
} |
} |
|
if (process == null) |
return false; |
@@ -113,10 +109,8 @@ |
{ |
// User cancelled the UAC elevation prompt. |
if (ex.NativeErrorCode == 1223) |
{ |
return false; |
} |
} |
|
if (process == null) |
return false; |
/Platform/Windows/Services/Utilities.cs |
@@ -0,0 +1,46 @@ |
/////////////////////////////////////////////////////////////////////////// |
// Copyright (C) Wizardry and Steamworks 2017 - License: GNU GPLv3 // |
// Please see: http://www.gnu.org/licenses/gpl.html for legal details, // |
// rights of fair usage, the disclaimer and warranty conditions. // |
/////////////////////////////////////////////////////////////////////////// |
|
using System; |
using System.ServiceProcess; |
|
namespace wasSharpNET.Platform.Windows.Services |
{ |
public static class Utilities |
{ |
/// <summary> |
/// Start or stop a service. |
/// </summary> |
/// <param name="service">the name of service</param> |
/// <param name="running">the requested service state</param> |
/// <returns>true if the action could be performed</returns> |
public static void SetServiceRunning(string service, bool running) |
{ |
var s = new ServiceController(service); |
|
// Do not make any change in case the service status matches the requested service status. |
if (s.Status.Equals(ServiceControllerStatus.Running) && running) |
return; |
|
if (s.Status.Equals(ServiceControllerStatus.Stopped) && !running) |
return; |
|
switch (running) |
{ |
case true: |
s.Start(); |
break; |
case false: |
s.Stop(); |
break; |
} |
|
// Default Windows timespan of 30 seconds for service status result. |
s.WaitForStatus(running ? ServiceControllerStatus.Running : ServiceControllerStatus.Stopped, |
TimeSpan.FromSeconds(60)); |
} |
} |
} |
/Reflection.cs |
@@ -31,12 +31,8 @@ |
{ |
if (fi.FieldType.FullName.Split('.', '+') |
.Contains(@namespace, StringComparer.OrdinalIgnoreCase)) |
{ |
foreach (var sf in wasGetFields(fi.GetValue(@object), @namespace)) |
{ |
yield return sf; |
} |
} |
yield return new KeyValuePair<FieldInfo, object>(fi, @object); |
} |
} |
@@ -67,17 +63,13 @@ |
var array = (Array)getMethod.Invoke(@object, null); |
foreach (var sp in |
array.Cast<object>().SelectMany(element => wasGetProperties(element, @namespace))) |
{ |
yield return sp; |
} |
} |
foreach ( |
var sp in |
wasGetProperties(pi.GetValue(@object, null), @namespace)) |
{ |
yield return sp; |
} |
} |
yield return new KeyValuePair<PropertyInfo, object>(pi, @object); |
} |
} |
@@ -122,19 +114,15 @@ |
{ |
var fi = (object)info as FieldInfo; |
if (fi != null) |
{ |
return fi.GetValue(value); |
} |
var pi = (object)info as PropertyInfo; |
if (pi != null) |
{ |
if (pi.GetIndexParameters().Any()) |
{ |
return value; |
} |
return pi.GetValue(value, null); |
} |
return null; |
} |
} |
} |
} |
/Serialization/XmlSerializerCache.cs |
@@ -18,9 +18,12 @@ |
{ |
public static class XmlSerializerCache |
{ |
private static readonly ReaderWriterLockSlim SerializerCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); |
private static readonly Dictionary<string, XmlSerializer> SerializerCache = new Dictionary<string, XmlSerializer>(); |
private static readonly ReaderWriterLockSlim SerializerCacheLock = |
new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); |
|
private static readonly Dictionary<string, XmlSerializer> SerializerCache = |
new Dictionary<string, XmlSerializer>(); |
|
public static XmlSerializer GetSerializer<T>() |
{ |
return GetSerializer<T>(null); |
@@ -40,9 +43,7 @@ |
{ |
var Signature = MainTypeForSerialization.FullName; |
if (ExtraTypes != null) |
{ |
Signature = ExtraTypes.Aggregate(Signature, (current, tp) => current + ("-" + tp.FullName)); |
} |
Signature = ExtraTypes.Aggregate(Signature, (current, tp) => current + "-" + tp.FullName); |
|
SerializerCacheLock.EnterReadLock(); |
XmlSerializer XmlEventSerializer; |
@@ -93,9 +94,9 @@ |
{ |
try |
{ |
using (MemoryStream memoryStream = new MemoryStream()) |
using (var memoryStream = new MemoryStream()) |
{ |
using (StreamWriter streamWriter = new StreamWriter(memoryStream)) |
using (var streamWriter = new StreamWriter(memoryStream)) |
{ |
streamWriter.Write(XmlData); |
streamWriter.Flush(); |
@@ -114,9 +115,9 @@ |
{ |
try |
{ |
using (MemoryStream memoryStream = new MemoryStream()) |
using (var memoryStream = new MemoryStream()) |
{ |
using (StreamReader streamReader = new StreamReader(memoryStream)) |
using (var streamReader = new StreamReader(memoryStream)) |
{ |
using (var xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings { Indent = true })) |
{ |
/wasSharpNET.csproj |
@@ -34,6 +34,7 @@ |
<Reference Include="System.Core" /> |
<Reference Include="System.Security" /> |
<Reference Include="System.ServiceModel" /> |
<Reference Include="System.ServiceProcess" /> |
<Reference Include="System.Xml.Linq" /> |
<Reference Include="System.Data.DataSetExtensions" /> |
<Reference Include="Microsoft.CSharp" /> |
@@ -54,6 +55,7 @@ |
<Compile Include="Network\SubnetMask.cs" /> |
<Compile Include="Network\TCP\Utilities.cs" /> |
<Compile Include="Platform\Windows\Commands\NetSH\URLACL.cs" /> |
<Compile Include="Platform\Windows\Services\Utilities.cs" /> |
<Compile Include="Process.cs" /> |
<Compile Include="Reflection.cs" /> |
<Compile Include="Properties\AssemblyInfo.cs" /> |