public async Task <ICommandDeliveryResult> Receive( HandleCommand <T> handle, TimeSpan?timeout = null) { timeout = timeout ?? Settings.For <T> .Default.ReceiveTimeout; var stopAt = clock.Now() + timeout; ICommandDeliveryResult result = null; using (Subscribe(async delivery => { result = await handle(delivery); return(result); })) { while (result == null && clock.Now() <= stopAt) { var timeUntilNextActionIsDue = clock.TimeUntilNextActionIsDue; if (timeUntilNextActionIsDue == null) { return(null); } await clock.Wait(timeUntilNextActionIsDue.Value); } } return(result); }
private Maybe <Task> Handle(HandleCommand hc) { if (hc.Command.Message is TMessage m) { _action(m); return(Task.CompletedTask); } return(None <Task> .Value); }
public User(Connection conn, World world, string name) { Connection = conn; Command = new HandleCommand(this); World = world; Name = name; Player = new Player(name); Inventory = new Inventory(); Inventory.setCarryCapacity(Player.Stats.Strength); CurrRoomId = 0001; }
public Command(CommandKeys key, AccessLevel accessLevel, HandleCommand handleCommand, string summary, string syntax, string argumentHelp) { async = true; Key = key; AccessLevel = accessLevel; HandleCommand = handleCommand; HandleSynchronousCommand = null; Summary = summary; Syntax = syntax; ArgumentHelp = argumentHelp; }
static int Main(string[] args) { MConfigOptions options = new MConfigOptions(); options.Parse(args); if (!String.IsNullOrEmpty(options.ConfigFile)) { configPaths [3] = options.ConfigFile; } Configuration config = new Configuration(); try { config.Load(configPaths); } catch (Exception ex) { PrintException(ex, "Failed to load configuration files:"); return(1); } string[] commandArguments = options.PlainArguments; if (commandArguments == null || commandArguments.Length == 0) { options.UsageCommands(); DisplayList("Default config files:", config.DefaultConfigFiles); Console.WriteLine(); DisplayList("Available features:", config.Features); return(1); } HandleCommand commandHandler = FindCommandHandler(commandArguments [0]); if (commandHandler == null) { Console.Error.WriteLine("Unknown command '{0}'", commandArguments [0]); return(1); } IDefaultConfigFileContainer[] containers = config.GetHandlersForInterface <IDefaultConfigFileContainer> (); if (containers != null && containers.Length > 0) { foreach (IDefaultConfigFileContainer c in containers) { c.OverwriteFile += new OverwriteFileEventHandler(OnOverwriteFile); } } return(commandHandler(options, config)); }
public override Task <ICommandDeliveryResult> Handle(HandleCommand <TChannel> handlerDelegate, ICommandDelivery <TChannel> delivery) { if (handlerDelegate == null) { throw new ArgumentNullException(nameof(handlerDelegate)); } if (delivery == null) { throw new ArgumentNullException(nameof(delivery)); } return(handlerDelegate(delivery)); }
public async Task <ICommandDeliveryResult> Receive( HandleCommand <T> handle, TimeSpan?timeout = null) { var received = await messageReceiver.ReceiveAsync( 1, timeout ?? Settings.For <T> .Default.ReceiveTimeout); var message = received?.SingleOrDefault(); if (message != null) { return(await HandleMessage(handle, message)); } return(null); }
/** * Handler for a sequence of CharStringCommands. * * @param sequence of CharStringCommands * */ public List <float> HandleSequence(List <object> sequence, HandleCommand handleCommand) { var stack = new List <float>(); for (int i = 0; i < sequence.Count; i++) { var obj = sequence[i]; if (obj is CharStringCommand charStringCommand) { List <float> results = handleCommand(stack, charStringCommand); stack.Clear(); // this is basically returning the new stack stack.AddRange(results); } else { stack.Add(Convert.ToSingle(obj)); } } return(stack.ToList()); }
public IDisposable Subscribe(HandleCommand <T> handle) { lock (subscribers) { if (isDisposed) { ThrowObjectDisposed(); } subscribers.Add(handle); } return(Disposable.Create(() => { lock (subscribers) { subscribers.Remove(handle); } })); }
private async Task <ICommandDeliveryResult> HandleMessage( HandleCommand <T> onNext, Message message) { var commandDelivery = message.ToCommandDelivery <T>(); var result = await onNext(commandDelivery); switch (result) { case RetryDeliveryResult <T> _: break; case CancelDeliveryResult <T> _: case CompleteDeliveryResult <T> _: await messageReceiver.CompleteAsync(message.SystemProperties.LockToken); break; } return(result); }
public IDisposable Subscribe(HandleCommand <T> handle) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } messageReceiver.RegisterMessageHandler( async(message, cancellationToken) => { await HandleMessage(handle, message); }, new MessageHandlerOptions( async args => { await HandleError(args); }) { AutoComplete = false, MaxConcurrentCalls = 1 }); return(Disposable.Empty); }
public static void DefineCommand(string command, HandleCommand handler) { CommandHandlers[command] = handler; }
public async Task <ICommandDeliveryResult> Receive(HandleCommand <T> handle, TimeSpan?timeout = null) { return(await receive(handle, timeout)); }
public CommandHandler(string[] names, HandleCommand handler) { this.Names = names; this.Handler = handler; }
private void doChat(Connection connection) { int requestCount = 0; while (true) { byte[] size; byte[] bytesFrom; string dataFromClient = null; string serverResponse = null; Stopwatch timer = new Stopwatch(); timer.Start(); try { requestCount++; if (connection.clientSocket == null || !connection.clientSocket.Connected || connection.disconnected) { try { connection.clientSocket.Close(); } catch { } break; } string IPAddress = ((IPEndPoint)connection.clientSocket.Client.RemoteEndPoint).Address.ToString(); connection.networkStream = connection.clientSocket.GetStream(); size = new byte[4]; if (connection.networkStream.Read(size, 0, size.Length) == 0) { Console.WriteLine("Request == 0"); Thread.Sleep(1000); continue; } else if (BitConverter.ToInt32(size, 0) == 0) { serverResponse = "Too Small of a Request [" + BitConverter.ToInt32(size, 0) + "]"; } else if (BitConverter.ToInt32(size, 0) > 1048576) { serverResponse = "Too Large of a Request [" + BitConverter.ToInt32(size, 0) + "]"; } else { bytesFrom = new byte[BitConverter.ToInt32(size, 0)]; Console.WriteLine("ExpectedSize: " + BitConverter.ToInt32(size, 0) + " bytesFrom Length: " + bytesFrom.Length); connection.networkStream.Read(bytesFrom, 0, bytesFrom.Length); dataFromClient = Encoding.ASCII.GetString(bytesFrom); Console.WriteLine("Raw Data: " + dataFromClient); serverResponse = HandleCommand.ParseCommand(connection.clientSocket, dataFromClient); } //Byte Streams byte[] outStream = Encoding.ASCII.GetBytes(serverResponse); byte[] outSize = BitConverter.GetBytes(outStream.Length); //Network Streams connection.networkStream.Write(outSize, 0, outSize.Length); connection.networkStream.Write(outStream, 0, outStream.Length); connection.networkStream.Flush(); Console.WriteLine(">> Size=" + BitConverter.ToInt32(outSize, 0) + " Response: " + serverResponse); connection.timeout = DateTime.Now; } catch (Exception ex) { Console.WriteLine(">> " + ex.ToString()); connection.disconnected = true; break; } Console.WriteLine(timer.Elapsed.TotalMilliseconds + "ms"); timer.Reset(); } }
private string HandleData(string data) { if (data == "Start") { return(this.Handle.ToString()); } else if (data == "Stop") { return("OK"); } else if (data == "Auto") { bool threadalive = false; try { if (InfomationStartup.AutoThread.IsAlive) { threadalive = true; } } catch { } if (!threadalive) { InfomationStartup.AutoThread = new Thread(() => { try { HandleCommand.Auto(this.Width, this.Height, this.Visible); } catch (Exception e) { InfomationStartup.Response = "Auto Error"; try { File.AppendAllText(Application.StartupPath + "//logs.txt", DateTime.Now.ToString() + ":" + e.Message + Environment.NewLine); } catch { try { File.WriteAllText(Application.StartupPath + "//logs.txt", DateTime.Now.ToString() + ":" + e.Message + Environment.NewLine); } catch { } } } }); InfomationStartup.AutoThread.Start(); return("OK"); } } else if (data == "CheckData") { return(InfomationStartup.Response + "|" + InfomationStartup.Captcha.ToString()); } else if (data == "StopAuto") { try { InfomationStartup.AutoThread.Abort(); } catch { } return("OK"); } else if (data == "Hide") { this.Invoke((MethodInvoker) delegate() { this.Visible = false; Application.DoEvents(); }); return("OK"); } else if (data == "Show") { this.Invoke((MethodInvoker) delegate() { this.Visible = true; Application.DoEvents(); }); return("OK"); } else if (Regex.IsMatch(data, "^clickcaptcha")) { this.Invoke((MethodInvoker) delegate() { this.Visible = true; string[] widthheight = data.Split('|'); this.Width = Convert.ToInt32(widthheight[1]); this.Height = Convert.ToInt32(widthheight[2]); InfomationStartup.ClickRecaptcha = true; Application.DoEvents(); }); return("OK"); } return("null"); }
public AnonymousCommandHandler(HandleCommand <T> handle) => this.handle = handle ?? throw new ArgumentNullException(nameof(handle));
private static void DefineCommand(string command, HandleCommand handler) { CommandHandlers[command.ToLower()] = handler; }
public static void DefineCommand(string command, HandleCommand handler) => CommandHandlers[command.ToLower()] = handler;
/// <summary> /// Add a new command by key /// </summary> /// <param name="key">The key to identify the command</param> /// <param name="command">The command object defining the commands behaviour</param> public static void AddCommand(CommandKeys keys, HandleCommand commandHandler, AccessLevel accessLevel, string summary, string syntax, string argumentHelp) { Command cmd = new Command(keys, accessLevel, commandHandler, summary, syntax, argumentHelp); commands.Add(cmd); }
private async Task Handle(ExecuteCommand m) { HandleCommand h = new HandleCommand(m.Command, m.Context); await Services.Send <HandleCommand, Task>(h).To <ICommandHandler>(); }
public IDisposable Subscribe(HandleCommand <T> handle) { return(subscribe(handle)); }
public void RegisterHandler <T>(HandleCommand <T> handler) => _handlers.Add(handler);
public Task <ICommandDeliveryResult> Receive(HandleCommand <T> handle, TimeSpan?timeout = null) => throw new NotImplementedException();
public IDisposable Subscribe(HandleCommand <T> handle) => throw new NotImplementedException();
public abstract Task <ICommandDeliveryResult> Handle(HandleCommand <T> handlerDelegate, ICommandDelivery <T> delivery);
private void Handler(object param) { var client = (Socket)param; if (SystemInfo.Platform == Platform.Windows) { client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); } client.LingerState = new LingerOption(false, 0); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); lock (Clients) { Clients.Add(client); } ClientConnected?.Invoke(client); var rxString = string.Empty; //client.ReceiveTimeout = 30000; while (client.IsBound && client.Connected) { try { var rxData = new byte[2048]; int rxLen; try { rxLen = client.Receive(rxData, 0, rxData.Length, SocketFlags.None); } catch (SocketException ex) { Debug.WriteLine(ex.Message); break; } if (rxLen == 0) { break; } var rxStr = UseEncoding.GetString(rxData, 0, rxLen); // ReSharper disable once ForCanBeConvertedToForeach for (var cx = 0; cx < rxStr.Length; cx++) { rxString += rxStr[cx]; foreach (var eoc in Eoc) { if (rxString.IndexOf(eoc, StringComparison.InvariantCulture) == -1) { continue; } rxString = rxString.Replace(eoc, string.Empty); if (!string.IsNullOrEmpty(StartOfCommand)) { var start = rxString.IndexOf(StartOfCommand, StringComparison.Ordinal); rxString = (start >= 0) ? rxString.Substring(start + 1) : string.Empty; } if (!string.IsNullOrEmpty(rxString) || HandleEmptyCommands) { if (client.Connected) { HandleCommand?.Invoke(client, rxString); } } rxString = string.Empty; break; } } } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.ConnectionReset) { Trace.TraceError(ex.Message); } break; } catch (ObjectDisposedException ex) { Trace.TraceError(ex.Message); break; } catch (PlatformNotSupportedException ex) { Trace.TraceError(ex.Message); break; } catch (ThreadAbortException ex) { Trace.TraceError(ex.Message); break; } } try { client.Shutdown(SocketShutdown.Both); client.Disconnect(false); } catch (SocketException) { } catch (ObjectDisposedException) { } catch (PlatformNotSupportedException) { } ClientDisconnected?.Invoke(client); lock (Clients) { Clients.Remove(client); } }
public UIMenuCommand(KeyCode keyCode, string description, HandleCommand commandCallback) { this.description = description; this.keyCode = keyCode; this.commandCallback = commandCallback; }
public CommandHandler (string[] names, HandleCommand handler) { this.Names = names; this.Handler = handler; }
public static ICommandHandler <T> Create <T>(HandleCommand <T> handle) => new AnonymousCommandHandler <T>(handle);