Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

typo, comment #847

Merged
merged 30 commits into from
Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
1b97add
typo, comment, code optimization.
Jim8y Jan 20, 2022
d14d2bd
optimise code
Jim8y Jan 20, 2022
bcc8641
Update ConsoleColorSet.cs
Jim8y Jan 20, 2022
d801df7
Update ConsoleColorSet.cs
Jim8y Jan 20, 2022
37323a9
revert all visiblities
Jim8y Jan 20, 2022
904cd3f
revert change to visibility
Jim8y Jan 24, 2022
d9e98d5
remove null check and optimise code
Jim8y Jan 25, 2022
03a1cd3
remove null check
erikzhang Jan 26, 2022
3b02338
Revert some changes
erikzhang Jan 26, 2022
8825288
Revert some changes
erikzhang Jan 26, 2022
4c3046e
revert recursion
Jim8y Jan 26, 2022
1ed1b40
revert unnessary optimise
Jim8y Jan 27, 2022
3f53fcd
revert unnecessary optimise
Jim8y Jan 27, 2022
df3e957
revert almost all changes that has nothing to do witht typo
Jim8y Jan 27, 2022
5530994
revert if statement changes
Jim8y Jan 27, 2022
40aa10c
revert more unnesary optimise code
Jim8y Jan 27, 2022
a4e5c4e
revert change to using packages order
Jim8y Jan 27, 2022
e4ca76e
revert change in wallet
Jim8y Jan 27, 2022
7343441
Update neo-cli/CLI/MainService.Contracts.cs
Jim8y Jan 27, 2022
759aa09
Update neo-cli/CLI/MainService.Contracts.cs
Jim8y Jan 27, 2022
bc6a098
Update Neo.ConsoleService/ConsoleServiceBase.cs
Jim8y Jan 27, 2022
33e5baa
Update MainService.Node.cs
shargon Jan 27, 2022
0fdb09f
Update MainService.Node.cs
shargon Jan 27, 2022
5018ca4
Update Logger.cs
Jim8y Jan 30, 2022
6f114db
remove default
Jim8y Jan 30, 2022
77ce5a9
remove static
Jim8y Jan 31, 2022
fb45145
remove static
Jim8y Jan 31, 2022
d1b114c
remove token.cancel
Jim8y Mar 28, 2022
0ce742f
Update MainService.Node.cs
Jim8y Mar 28, 2022
52af048
Update MainService.Tools.cs
erikzhang Mar 29, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Neo.ConsoleService/CommandToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal abstract class CommandToken
/// <summary>
/// Value
/// </summary>
public string Value { get; protected set; }
public string Value { get; protected init; }

/// <summary>
/// Constructor
Expand Down Expand Up @@ -152,7 +152,7 @@ public static void Trim(List<CommandToken> args)

// Trim end

while (args.Count > 0 && args[args.Count - 1].Type == CommandTokenType.Space)
while (args.Count > 0 && args[^1].Type == CommandTokenType.Space)
{
args.RemoveAt(args.Count - 1);
}
Expand Down
2 changes: 1 addition & 1 deletion Neo.ConsoleService/ConsoleCommandMethod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ internal class ConsoleCommandMethod
/// </summary>
/// <param name="instance">Instance</param>
/// <param name="method">Method</param>
/// <param name="verbs">Verbs</param>
/// <param name="attribute">Attribute</param>
public ConsoleCommandMethod(object instance, MethodInfo method, ConsoleCommandAttribute attribute)
{
Method = method;
Expand Down
83 changes: 37 additions & 46 deletions Neo.ConsoleService/ConsoleServiceBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ public abstract class ConsoleServiceBase
public bool ReadingPassword { get; set; } = false;

private bool _running;
private readonly CancellationTokenSource _shutdownTokenSource = new CancellationTokenSource();
private readonly CountdownEvent _shutdownAcknowledged = new CountdownEvent(1);
private readonly Dictionary<string, List<ConsoleCommandMethod>> _verbs = new Dictionary<string, List<ConsoleCommandMethod>>();
private readonly Dictionary<string, object> _instances = new Dictionary<string, object>();
private readonly Dictionary<Type, Func<List<CommandToken>, bool, object>> _handlers = new Dictionary<Type, Func<List<CommandToken>, bool, object>>();
private readonly CancellationTokenSource _shutdownTokenSource = new();
private readonly CountdownEvent _shutdownAcknowledged = new(1);
private readonly Dictionary<string, List<ConsoleCommandMethod>> _verbs = new();
private readonly Dictionary<string, object> _instances = new();
private readonly Dictionary<Type, Func<List<CommandToken>, bool, object>> _handlers = new();

private bool OnCommand(string commandLine)
{
Expand Down Expand Up @@ -114,7 +114,7 @@ private bool OnCommand(string commandLine)
case 1:
{
var (command, arguments) = availableCommands[0];
object result = command.Method.Invoke(command.Instance, arguments);
var result = command.Method.Invoke(command.Instance, arguments);
if (result is Task task) task.Wait();
return true;
}
Expand Down Expand Up @@ -188,10 +188,10 @@ protected void OnHelpCommand(string key)

withHelp.Sort((a, b) =>
{
var cate = a.HelpCategory.CompareTo(b.HelpCategory);
var cate = string.Compare(a.HelpCategory, b.HelpCategory, StringComparison.Ordinal);
if (cate == 0)
{
cate = a.Key.CompareTo(b.Key);
cate = string.Compare(a.Key, b.Key, StringComparison.Ordinal);
}
return cate;
});
Expand Down Expand Up @@ -234,7 +234,7 @@ protected void OnHelpCommand(string key)

if (lastKey != command.Key)
{
Console.WriteLine($"You can call this command like this:");
Console.WriteLine("You can call this command like this:");
lastKey = command.Key;
}

Expand All @@ -247,7 +247,7 @@ protected void OnHelpCommand(string key)

if (!found)
{
throw new ArgumentException($"Command not found.");
throw new ArgumentException("Command not found.");
}
}
}
Expand Down Expand Up @@ -297,8 +297,7 @@ public virtual void OnStop()
public string ReadUserInput(string prompt, bool password = false)
{
const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
StringBuilder sb = new StringBuilder();
ConsoleKeyInfo key;
var sb = new StringBuilder();

if (!string.IsNullOrEmpty(prompt))
{
Expand All @@ -316,21 +315,15 @@ public string ReadUserInput(string prompt, bool password = false)
}
else
{
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);

if (t.IndexOf(key.KeyChar) != -1)
{
sb.Append(key.KeyChar);
if (password)
{
Console.Write('*');
}
else
{
Console.Write(key.KeyChar);
}
Console.Write(password ? '*' : key.KeyChar);
}
else if (key.Key == ConsoleKey.Backspace && sb.Length > 0)
{
Expand Down Expand Up @@ -411,38 +404,33 @@ protected ConsoleServiceBase()
{
// Register self commands

RegisterCommandHander<string>((args, canConsumeAll) =>
{
return CommandToken.ReadString(args, canConsumeAll);
});
RegisterCommandHandler<string>(CommandToken.ReadString);

RegisterCommandHander<string[]>((args, canConsumeAll) =>
RegisterCommandHandler<string[]>((args, canConsumeAll) =>
{
if (canConsumeAll)
{
var ret = CommandToken.ToString(args);
args.Clear();
return ret.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
return CommandToken.ReadString(args, false).Split(',', ' ');
return ret.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}

return CommandToken.ReadString(args, false).Split(',', ' ');
});

RegisterCommandHander<string, byte>(false, (str) => byte.Parse(str));
RegisterCommandHander<string, bool>(false, (str) => str == "1" || str == "yes" || str == "y" || bool.Parse(str));
RegisterCommandHander<string, ushort>(false, (str) => ushort.Parse(str));
RegisterCommandHander<string, uint>(false, (str) => uint.Parse(str));
RegisterCommandHander<string, IPAddress>(false, (str) => IPAddress.Parse(str));
RegisterCommandHandler<string, byte>(false, str => byte.Parse(str));
RegisterCommandHandler<string, bool>(false, str => str == "1" || str == "yes" || str == "y" || bool.Parse(str));
RegisterCommandHandler<string, ushort>(false, str => ushort.Parse(str));
RegisterCommandHandler<string, uint>(false, str => uint.Parse(str));
RegisterCommandHandler<string, IPAddress>(false, IPAddress.Parse);
}

/// <summary>
/// Register command handler
/// </summary>
/// <typeparam name="TRet">Return type</typeparam>
/// <param name="handler">Handler</param>
private void RegisterCommandHander<TRet>(Func<List<CommandToken>, bool, object> handler)
private void RegisterCommandHandler<TRet>(Func<List<CommandToken>, bool, object> handler)
{
_handlers[typeof(TRet)] = handler;
}
Expand All @@ -454,9 +442,9 @@ private void RegisterCommandHander<TRet>(Func<List<CommandToken>, bool, object>
/// <typeparam name="TRet">Return type</typeparam>
/// <param name="canConsumeAll">Can consume all</param>
/// <param name="handler">Handler</param>
public void RegisterCommandHander<T, TRet>(bool canConsumeAll, Func<T, object> handler)
public void RegisterCommandHandler<T, TRet>(bool canConsumeAll, Func<T, object> handler)
{
_handlers[typeof(TRet)] = (args, cosumeAll) =>
_handlers[typeof(TRet)] = (args, _) =>
{
var value = (T)_handlers[typeof(T)](args, canConsumeAll);
return handler(value);
Expand All @@ -469,11 +457,11 @@ public void RegisterCommandHander<T, TRet>(bool canConsumeAll, Func<T, object> h
/// <typeparam name="T">Base type</typeparam>
/// <typeparam name="TRet">Return type</typeparam>
/// <param name="handler">Handler</param>
public void RegisterCommandHander<T, TRet>(Func<T, object> handler)
public void RegisterCommandHandler<T, TRet>(Func<T, object> handler)
{
_handlers[typeof(TRet)] = (args, cosumeAll) =>
_handlers[typeof(TRet)] = (args, consumeAll) =>
{
var value = (T)_handlers[typeof(T)](args, cosumeAll);
var value = (T)_handlers[typeof(T)](args, consumeAll);
return handler(value);
};
}
Expand All @@ -498,7 +486,7 @@ public void RegisterCommand(object instance, string name = null)

if (!method.GetParameters().All(u => u.ParameterType.IsEnum || _handlers.ContainsKey(u.ParameterType)))
{
throw new ArgumentException("Handler not found for the command: " + method.ToString());
throw new ArgumentException("Handler not found for the command: " + method);
}

// Add command
Expand Down Expand Up @@ -576,7 +564,7 @@ public void Run(string[] args)

protected string ReadLine()
{
Task<string> readLineTask = Task.Run(() => Console.ReadLine());
Task<string> readLineTask = Task.Run(Console.ReadLine);

try
{
Expand All @@ -598,7 +586,10 @@ public virtual void RunConsole()
{
Console.Title = ServiceName;
}
catch { }
catch
{
// ignored
}
Jim8y marked this conversation as resolved.
Show resolved Hide resolved

Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.SetIn(new StreamReader(Console.OpenStandardInput(), Console.InputEncoding, false, ushort.MaxValue));
Expand All @@ -612,7 +603,7 @@ public virtual void RunConsole()
}

Console.ForegroundColor = ConsoleColor.Yellow;
string line = ReadLine()?.Trim();
var line = ReadLine()?.Trim();
if (line == null) break;
Console.ForegroundColor = ConsoleColor.White;

Expand All @@ -623,7 +614,7 @@ public virtual void RunConsole()
ConsoleHelper.Error("Command not found");
}
}
catch (TargetInvocationException ex)
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
ConsoleHelper.Error(ex.InnerException.Message);
}
Expand Down
8 changes: 4 additions & 4 deletions Neo.ConsoleService/ServiceProxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,21 @@ namespace Neo.ConsoleService
{
internal class ServiceProxy : ServiceBase
{
private readonly ConsoleServiceBase service;
private readonly ConsoleServiceBase _service;

public ServiceProxy(ConsoleServiceBase service)
{
this.service = service;
this._service = service;
}

protected override void OnStart(string[] args)
{
service.OnStart(args);
_service.OnStart(args);
}

protected override void OnStop()
{
service.OnStop();
_service.OnStop();
}
}
}
9 changes: 5 additions & 4 deletions neo-cli/CLI/ConsolePercent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public class ConsolePercent : IDisposable
{
#region Variables

private long _maxValue, _value;
private readonly long _maxValue;
private long _value;
private decimal _lastFactor;
private string _lastPercent;

Expand All @@ -33,7 +34,7 @@ public class ConsolePercent : IDisposable
/// </summary>
public long Value
{
get { return _value; }
get => _value;
set
{
if (value == _value) return;
Expand All @@ -48,8 +49,8 @@ public long Value
/// </summary>
public long MaxValue
{
get { return _maxValue; }
set
get => _maxValue;
init
{
if (value == _maxValue) return;

Expand Down
59 changes: 32 additions & 27 deletions neo-cli/CLI/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,31 @@ internal class Logger : Plugin, ILogPlugin

public override string Name => "SystemLog";
public override string Description => "Prints consensus log and is a built-in plugin which cannot be uninstalled";
public override string ConfigFile => Combine(GetDirectoryName(Path), "config.json");
public override string ConfigFile => Combine(GetDirectoryName(Path) ?? throw new InvalidOperationException(), "config.json");
Jim8y marked this conversation as resolved.
Show resolved Hide resolved
public override string Path => GetType().Assembly.Location;

private static void GetErrorLogs(StringBuilder sb, Exception ex)
{
sb.AppendLine(ex.GetType().ToString());
sb.AppendLine(ex.Message);
sb.AppendLine(ex.StackTrace);
if (ex is AggregateException ex2)
while (true)
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
{
foreach (Exception inner in ex2.InnerExceptions)
sb.AppendLine(ex.GetType().ToString());
sb.AppendLine(ex.Message);
sb.AppendLine(ex.StackTrace);
if (ex is AggregateException ex2)
{
foreach (var inner in ex2.InnerExceptions)
{
sb.AppendLine();
GetErrorLogs(sb, inner);
}
}
else if (ex.InnerException != null)
{
sb.AppendLine();
GetErrorLogs(sb, inner);
ex = ex.InnerException;
continue;
}
}
else if (ex.InnerException != null)
{
sb.AppendLine();
GetErrorLogs(sb, ex.InnerException);
break;
}
}

Expand Down Expand Up @@ -78,28 +83,28 @@ void ILogPlugin.Log(string source, LogLevel level, object message)
case LogLevel.Fatal: FatalColor.Apply(); break;
case LogLevel.Info: InfoColor.Apply(); break;
case LogLevel.Warning: WarningColor.Apply(); break;
default:
throw new ArgumentOutOfRangeException(nameof(level), level, null);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just ignore it?

}

Console.WriteLine(log);
currentColor.Apply();
}

if (!string.IsNullOrEmpty(Settings.Default.Logger.Path))
if (string.IsNullOrEmpty(Settings.Default.Logger.Path)) return;
var sb = new StringBuilder(source);
foreach (var c in GetInvalidFileNameChars())
sb.Replace(c, '-');
var path = Combine(Settings.Default.Logger.Path, sb.ToString());
Directory.CreateDirectory(path);
path = Combine(path, $"{now:yyyy-MM-dd}.log");
try
{
StringBuilder sb = new StringBuilder(source);
foreach (char c in GetInvalidFileNameChars())
sb.Replace(c, '-');
var path = Combine(Settings.Default.Logger.Path, sb.ToString());
Directory.CreateDirectory(path);
path = Combine(path, $"{now:yyyy-MM-dd}.log");
try
{
File.AppendAllLines(path, new[] { $"[{level}]{log}" });
}
catch (IOException)
{
Console.WriteLine("Error writing the log file: " + path);
}
File.AppendAllLines(path, new[] { $"[{level}]{log}" });
}
catch (IOException)
{
Console.WriteLine("Error writing the log file: " + path);
}
}
}
Expand Down
Loading