コード例 #1
0
        public void NodesCommand(PromptOutputStyle output = PromptOutputStyle.json)
        {
            var peers = _serverContext.ConnectedPeers;

            switch (output)
            {
            case PromptOutputStyle.json:
            {
                _consoleHandler.WriteObject(
                    new
                    {
                        Count = peers.Count,
                        Nodes = peers
                                .OrderBy(u => u.Value.ConnectionDate)
                                .Select(u => new { Address = u.Key, ConnectedTime = (DateTime.UtcNow - u.Value.ConnectionDate) })
                                .ToArray()
                    }, PromptOutputStyle.json);
                break;
            }

            default:
            {
                _consoleHandler.WriteLine("Connected: " + peers.Count);

                foreach (var peer in peers.OrderBy(u => u.Value.ConnectionDate))
                {
                    _consoleHandler.WriteLine(peer.Key.ToString() + " - " +
                                              // Connected time
                                              (DateTime.UtcNow - peer.Value.ConnectionDate).ToString());
                }
                break;
            }
            }
        }
コード例 #2
0
 public void VariablesCommand()
 {
     foreach (var keyValue in _variables)
     {
         _consoleHandler.Write(keyValue.Key + "  ", ConsoleOutputStyle.Output);
         _consoleHandler.WriteLine(keyValue.Value, ConsoleOutputStyle.Information);
     }
 }
コード例 #3
0
        public void VirtualContractAddCommand(byte[] script)
        {
            var hash = new UInt160(Crypto.Default.Hash160(script));

            _scriptTable.VirtualContracts.TryAdd(hash, script);

            foreach (var h in _scriptTable.VirtualContracts.Keys)
            {
                _consoleHandler.WriteLine(h.ToString(true), h == hash ? ConsoleOutputStyle.Information : ConsoleOutputStyle.Output);
            }
        }
コード例 #4
0
        void WriteStatePercent(string title, string msg, long?value, long?max)
        {
            if (!value.HasValue || !max.HasValue)
            {
                _consoleHandler.WriteLine(title + ": " + msg + " ");
                return;
            }

            _consoleHandler.Write(title + ": " + msg + " ");

            using (var pg = _consoleHandler.CreatePercent(max.Value))
            {
                pg.Value = value.Value;
            }
        }
コード例 #5
0
ファイル: ConsoleOutput.cs プロジェクト: D3TONAT0R/HMCon
 static void WriteConsoleLine(string str)
 {
     if (consoleHandler != null)
     {
         consoleHandler.WriteLine(str);
     }
     else if (GetConsoleWindow() != IntPtr.Zero)
     {
         try
         {
             Console.CursorVisible = false;
             if (progressString != null)
             {
                 WriteProgress("", -1);
                 progressString            = null;
                 lastProgressBarUpdateTick = -1;
                 Console.SetCursorPosition(0, Console.CursorTop);
             }
             Console.Write(str);
             Console.ResetColor();
             Console.WriteLine();
         }
         catch
         {
         }
     }
 }
コード例 #6
0
        /// <summary>
        /// Make rpc call
        /// </summary>
        private async Task RpcCallCommand <T>(IPEndPoint endPoint, string method, string parameters = null, bool deserializeResult = false)
        {
            if (string.IsNullOrEmpty(parameters))
            {
                parameters = "[]";
            }

            using (HttpClient wb = new HttpClient())
            {
                var content = new StringContent
                              (
                    "{\"jsonrpc\": \"2.0\", \"method\": \"" + method + "\", \"params\": " + parameters + ", \"id\":1}", Encoding.UTF8,
                    "application/json"
                              );

                var rest = await wb.PostAsync("http://" + endPoint.Address.ToString() + ":" + endPoint.Port.ToString(), content);

                if (!rest.IsSuccessStatusCode)
                {
                    _consoleHandler.WriteLine(rest.StatusCode + " - " + rest.ReasonPhrase, ConsoleOutputStyle.Error);
                    return;
                }

                var json = JObject.Parse(await rest.Content.ReadAsStringAsync());

                if (deserializeResult)
                {
                    var obj = BinarySerializer.Default.Deserialize <T>(json["result"].Value <string>().HexToBytes());

                    if (obj is BlockHeader bh)
                    {
                        _blockSigner.Sign(bh);

                        if (bh is Block bb && bb.Transactions != null)
                        {
                            foreach (var tx in bb.Transactions)
                            {
                                _txSigner.Sign(tx);
                            }
                        }
                    }
                    else
                    {
                        if (obj is Transaction tx)
                        {
                            _txSigner.Sign(tx);
                        }
                    }

                    _consoleHandler.WriteObject(obj, PromptOutputStyle.json);
                }
                else
                {
                    _consoleHandler.WriteObject(json, PromptOutputStyle.json);
                }
            }
        }
コード例 #7
0
        public static string ReadJson(string jsonPrototypeString, IConsoleHandler consoleHandler)
        {
            try
            {
                File.WriteAllText(
                    jsonEditorFilePath,
                    jsonPrototypeString
                    );

                var process = TryStartProcess(jsonEditorFilePath);
                TryWaitForExit(process);
                string res;
                CommonHelpers.TryReadAllText(jsonEditorFilePath, out res, 120);
                return(res);
            }
            catch (Exception ex)
            {
                consoleHandler.WriteLine(
                    $"Was error '{ex.Message}' when try to use json editor. \nBut you can write json string as default.",
                    ConsoleColor.DarkRed
                    );
                consoleHandler.WriteLine("Or you can press enter to throw error upper.", ConsoleColor.DarkRed);
                if (!string.IsNullOrWhiteSpace(jsonPrototypeString))
                {
                    consoleHandler.WriteLine($"Prototype: {jsonPrototypeString}", ConsoleColor.DarkYellow);
                }
                consoleHandler.Write("Input json line: ", null);
                var res = consoleHandler.ReadLine();
                if (string.IsNullOrEmpty(res))
                {
                    throw;
                }
                else
                {
                    return(res);
                }
            }
        }
コード例 #8
0
ファイル: Prompt.cs プロジェクト: shargon/neo-sharp
        /// <inheritdoc />
        public void StartPrompt(string[] args)
        {
            // Backup shell style

            var cb = Console.BackgroundColor;
            var cf = Console.ForegroundColor;

            // Black background

            _consoleHandler.ApplyStyle(ConsoleOutputStyle.Prompt);
            _consoleHandler.Clear();

            // Start prompt

            _logger.LogInformation("Starting Prompt");
            _consoleHandler.WriteLine("Neo-Sharp", ConsoleOutputStyle.Prompt);

            if (args != null)
            {
                var easyAccess = new Dictionary <string, string[]>()
                {
                    { "-i", new string[] { "network start" } },
                    { "-s", new string[] { "network start", "log off" } },
                    { "-r", new string[] { "rpc start" } },
                };

                // Append arguments as inputs

                foreach (var arg in args.Where(u => !u.StartsWith("#")))
                {
                    if (easyAccess.TryGetValue(arg, out var newArgs))
                    {
                        _consoleHandler.AppendInputs(newArgs);
                    }
                    else
                    {
                        _consoleHandler.AppendInputs(arg);
                    }
                }
            }

            _blockchain.InitializeBlockchain().Wait();

            while (!_exit)
            {
                // Read log buffer

                while (_logs.TryTake(out var log))
                {
                    _consoleHandler.WriteLine
                    (
                        "[" + log.Level + (string.IsNullOrEmpty(log.Category) ? "" : "-" + log.Category) + "] " +
                        log.MessageWithError, _logStyle[log.Level]
                    );
                }

                // Read input

                var fullCmd = _consoleHandler.ReadFromConsole(_commandAutocompleteCache);

                if (string.IsNullOrWhiteSpace(fullCmd))
                {
                    continue;
                }

                fullCmd = _variables.Replace(fullCmd);

                _logger.LogInformation("Execute: " + fullCmd);

                Execute(fullCmd);
            }

            _consoleHandler.WriteLine("Exiting", ConsoleOutputStyle.Information);

            // Restore shell style

            Console.BackgroundColor = cb;
            Console.ForegroundColor = cf;
            _consoleHandler.Clear();
        }
コード例 #9
0
 /// <summary>
 /// Free console
 /// </summary>
 public void Dispose()
 {
     _handler.WriteLine("");
 }
コード例 #10
0
        public void WalletCreateCommand(FileInfo file)
        {
            var secureString = _consoleHandler.ReadPassword();

            _consoleHandler.ApplyStyle(ConsoleOutputStyle.Prompt);
            var confirmationString = _consoleHandler.ReadPassword("\nConfirm your password:"******"\nAddress: " + walletAccount.Address, ConsoleOutputStyle.Information);
                _consoleHandler.WriteLine("Public Key: " + _walletManager.GetPublicKeyFromNep2(walletAccount.Key, secureString), ConsoleOutputStyle.Information);
            }
            else
            {
                _consoleHandler.WriteLine("\nPasswords don't match.", ConsoleOutputStyle.Information);
            }
        }
コード例 #11
0
        public void BuildCommand(FileInfo inputPath, FileInfo outputPath)
        {
            if (outputPath.Exists)
            {
                throw new InvalidParameterException("Output file already exists");
            }
            if (!inputPath.Exists)
            {
                throw new InvalidParameterException(inputPath.FullName);
            }

            string[] dump;
            using (var p = Process.Start(new ProcessStartInfo()
            {
                FileName = "neon",
                Arguments = $"\"{inputPath.FullName}\"",
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
            }))
            {
                if (!p.Start())
                {
                    throw new Exception("Error starting neon. Make sure that neon is in your PATH variable");
                }

                dump = p.StandardOutput.ReadToEnd().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                p.WaitForExit();
            }

            foreach (var line in dump)
            {
                _consoleHandler.WriteLine(line, ConsoleOutputStyle.Log);
            }

            // Looking for .abi.json

            var tempFile = Path.ChangeExtension(inputPath.FullName, ".abi.json");

            if (File.Exists(tempFile))
            {
                try
                {
                    var json = JToken.Parse(File.ReadAllText(tempFile));
                    _consoleHandler.WriteLine(json.ToString(Formatting.Indented), ConsoleOutputStyle.Information);
                }
                catch { }
            }

            // Looking for .avm

            tempFile = Path.ChangeExtension(inputPath.FullName, ".avm");
            if (File.Exists(tempFile))
            {
                var avm = File.ReadAllBytes(tempFile);
                if (avm != null)
                {
                    File.WriteAllBytes(outputPath.FullName, avm);
                }
            }
            else
            {
                throw new InvalidParameterException("Error compiling the contract");
            }
        }