/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: |
@@ -141,4 +143,4 @@ |
} |
} |
} |
} |
} |
/Console/ConsoleSpin.cs |
@@ -19,7 +19,7 @@ |
public class ConsoleSpin : IDisposable |
{ |
private static readonly CircularQueue<string> spinArt = |
new CircularQueue<string>(new[] { ".oOo", "oOo.", "Oo.o", "o.oO" }); |
new CircularQueue<string>(new[] {".oOo", "oOo.", "Oo.o", "o.oO"}); |
|
private static readonly ManualResetEvent spinEvent = new ManualResetEvent(false); |
private static Thread spinThread; |
@@ -59,8 +59,8 @@ |
{ |
run = false; |
spinEvent.Reset(); |
if ((!spinThread.ThreadState.Equals(ThreadState.Running) && |
!spinThread.ThreadState.Equals(ThreadState.WaitSleepJoin)) || spinThread.Join(1000)) |
if (!spinThread.ThreadState.Equals(ThreadState.Running) && |
!spinThread.ThreadState.Equals(ThreadState.WaitSleepJoin) || spinThread.Join(1000)) |
return; |
spinThread.Abort(); |
spinThread.Join(); |
@@ -86,4 +86,4 @@ |
spinEvent.Reset(); |
} |
} |
} |
} |
/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,22 +77,21 @@ |
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 '-': |
continue; |
default: |
SHA1OutputStream.WriteByte((byte)buffer[0]); |
SHA1OutputStream.WriteByte((byte) buffer[0]); |
break; |
} |
} |
} |
SHA1OutputStream.Position = 0L; |
await SHA1OutputStream.CopyToAsync(outStream); |
@@ -87,4 +98,4 @@ |
} |
} |
} |
} |
} |
/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(); |
@@ -50,4 +78,4 @@ |
} |
} |
} |
} |
} |
/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,13 +58,13 @@ |
|
private void Listen(object state) |
{ |
HTTPServerCallbackState callbackState = (HTTPServerCallbackState)state; |
var callbackState = (HTTPServerCallbackState) state; |
|
while (callbackState.Listener.IsListening) |
{ |
callbackState.Listener?.BeginGetContext(ContextCallback, callbackState); |
|
if (WaitHandle.WaitAny(new[] { callbackState.ContextRetrieved, stopListen.WaitHandle }) != 1) |
if (WaitHandle.WaitAny(new[] {callbackState.ContextRetrieved, stopListen.WaitHandle}) != 1) |
continue; |
|
try |
@@ -81,7 +84,7 @@ |
|
private void ContextCallback(IAsyncResult ar) |
{ |
var callbackState = (HTTPServerCallbackState)ar.AsyncState; |
var callbackState = (HTTPServerCallbackState) ar.AsyncState; |
HttpListenerContext httpContext; |
|
Interlocked.Increment(ref processedRequests); |
@@ -111,11 +114,6 @@ |
} |
} |
|
public void Dispose() |
{ |
stopListen.Set(); |
} |
|
private class HTTPServerCallbackState |
{ |
public HTTPServerCallbackState(HttpListener listener) |
@@ -131,4 +129,4 @@ |
public AutoResetEvent ContextRetrieved { get; } |
} |
} |
} |
} |
/Network/IPAddressExtensions.cs |
@@ -25,9 +25,7 @@ |
|
var broadcastAddress = new byte[ipAdressBytes.Length]; |
for (var i = 0; i < broadcastAddress.Length; i++) |
{ |
broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); |
} |
broadcastAddress[i] = (byte) (ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); |
return new IPAddress(broadcastAddress); |
} |
|
@@ -41,9 +39,7 @@ |
|
var broadcastAddress = new byte[ipAdressBytes.Length]; |
for (var i = 0; i < broadcastAddress.Length; i++) |
{ |
broadcastAddress[i] = (byte)(ipAdressBytes[i] & subnetMaskBytes[i]); |
} |
broadcastAddress[i] = (byte) (ipAdressBytes[i] & subnetMaskBytes[i]); |
return new IPAddress(broadcastAddress); |
} |
|
@@ -55,4 +51,4 @@ |
return network1.Equals(network2); |
} |
} |
} |
} |
/Network/SubnetMask.cs |
@@ -30,11 +30,14 @@ |
var binaryMask = new byte[4]; |
|
for (var i = 0; i < 4; i++) |
{ |
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); |
} |
|
@@ -61,4 +63,4 @@ |
return CreateByHostBitLength(b.Length); |
} |
} |
} |
} |
/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,9 +82,7 @@ |
{ |
// User cancelled the UAC elevation prompt. |
if (ex.NativeErrorCode == 1223) |
{ |
return false; |
} |
} |
|
if (process == null) |
@@ -113,9 +109,7 @@ |
{ |
// User cancelled the UAC elevation prompt. |
if (ex.NativeErrorCode == 1223) |
{ |
return false; |
} |
} |
|
if (process == null) |
@@ -124,4 +118,4 @@ |
return process.WaitForExit(timeout); |
} |
} |
} |
} |
/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); |
} |
} |
@@ -64,19 +60,15 @@ |
var getMethod = pi.GetGetMethod(); |
if (getMethod.ReturnType.IsArray) |
{ |
var array = (Array)getMethod.Invoke(@object, null); |
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)) |
{ |
wasGetProperties(pi.GetValue(@object, null), @namespace)) |
yield return sp; |
} |
} |
yield return new KeyValuePair<PropertyInfo, object>(pi, @object); |
} |
@@ -94,18 +86,18 @@ |
public static void wasSetInfoValue<TK, TV>(TK info, ref TV @object, object value) |
{ |
object o = @object; |
var fi = (object)info as FieldInfo; |
var fi = (object) info as FieldInfo; |
if (fi != null) |
{ |
fi.SetValue(o, value); |
@object = (TV)o; |
@object = (TV) o; |
return; |
} |
var pi = (object)info as PropertyInfo; |
var pi = (object) info as PropertyInfo; |
if (pi != null) |
{ |
pi.SetValue(o, value, null); |
@object = (TV)o; |
@object = (TV) o; |
} |
} |
|
@@ -120,21 +112,17 @@ |
/// <returns>the value of the field or property</returns> |
public static object wasGetInfoValue<T>(T info, object value) |
{ |
var fi = (object)info as FieldInfo; |
var fi = (object) info as FieldInfo; |
if (fi != null) |
{ |
return fi.GetValue(value); |
} |
var pi = (object)info as PropertyInfo; |
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,14 +94,14 @@ |
{ |
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(); |
memoryStream.Position = 0; |
return (T)GetSerializer<T>(ExtraTypes).Deserialize(memoryStream); |
return (T) GetSerializer<T>(ExtraTypes).Deserialize(memoryStream); |
} |
} |
} |
@@ -114,11 +115,11 @@ |
{ |
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 })) |
using (var xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings {Indent = true})) |
{ |
var ns = new XmlSerializerNamespaces(); |
ns.Add(string.Empty, string.Empty); |
@@ -179,4 +180,4 @@ |
return Deserialize<T>(reader.ReadToEnd(), null); |
} |
} |
} |
} |
/Syndication/ObservableSyndication.cs |
@@ -47,13 +47,12 @@ |
.Items |
.AsParallel() |
.Where(o => o.PublishDate.CompareTo( |
DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(30)).Subtract(defaultUpdateTime)) > 0) |
DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(30)) |
.Subtract(defaultUpdateTime)) > 0) |
.ForAll(o => |
{ |
if (!syndicationItems.ContainsKey(o.Id)) |
{ |
syndicationItems.Add(o.Id, o); |
} |
}); |
} |
}, defaultUpdateTime, defaultUpdateTime); |
@@ -114,4 +113,4 @@ |
|
public event NotifyCollectionChangedEventHandler CollectionChanged; |
} |
} |
} |
/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" /> |