示例#1
0
        private TcpAppCommand RegisterCommandInt(string command, string description, TcpAppServerExecuteDelegate executeCallback, params TcpAppParameter[] parameters)
        {
            if (string.IsNullOrEmpty(command))
            {
                throw new ArgumentNullException(nameof(command));
            }
            if (GetCommand(command) != null)
            {
                throw new ArgumentException("Failed to register command [" + command + "], already exist!");
            }
            if (command.Contains(" "))
            {
                throw new ArgumentException("Invalid Character in command name, space ' ' is not allowed!");
            }

            TcpAppCommand tCmd = new TcpAppCommand(command, description, executeCallback);

            foreach (TcpAppParameter a in parameters)
            {
                tCmd.AddParameter(a);
            }

            for (int x = 0; x < tCmd.Parameters.Count - 1; x++)
            {
                if (tCmd.Parameters[x].IsArray)
                {
                    throw new ArgumentException("Failed to register command [" + command +
                                                "], parameter array [" + tCmd.Parameters[x].Name + "] must be last parameter!");
                }
            }

            Commands.Add(tCmd);
            return(tCmd);
        }
示例#2
0
        public static TcpAppInputCommand CreateInputCommand(List <TcpAppCommand> commandList, string[] commandArguments)
        {
            TcpAppInputCommand result = null;

            //Process Command Keyword
            TcpAppCommand cmdHandler = commandList.FirstOrDefault(x => x.Keyword.Equals(commandArguments[0], StringComparison.InvariantCultureIgnoreCase));

            if (cmdHandler == null)
            {
                return(null);
            }

            result = new TcpAppInputCommand()
            {
                Command = cmdHandler.Clone() as TcpAppCommand
            };
            result.Arguments = commandArguments.Skip(1).ToArray(); //Arguments exclude command keyword

            //Process Parameters
            cmdHandler.ResetParametersValue();
            int argID = 0; //First Parameter

            foreach (TcpAppParameter item in cmdHandler.Parameters)
            {
                if (argID >= result.Arguments.Length)
                {
                    //Argument with no input
                    if (!item.IsOptional)
                    {
                        //Error - Missing required parameter
                        throw new ArgumentException("Missing required parameter: " + item.Name + "!");
                    }
                }
                else if (item.IsArray)
                {
                    item.Values.Clear();
                    //Parameter Array is last parameters consume all arguments in command
                    for (int m = argID; m < result.Arguments.Length; m++)
                    {
                        item.Values.Add(result.Arguments[m]);
                    }
                    break;
                }
                else
                {
                    item.Value = result.Arguments[argID]; //Assign parameter value
                }
                argID++;
            }
            return(result);
        }
示例#3
0
        internal void Client_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //Process incoming message from Client
            if (!e.ReceivedMessage.StartsWith("#TCP#"))
            {
                return;                                         //Drop message which is not using defined format.
            }
            //Parse and Execute Commands
            string[]      cmdArg     = e.ReceivedMessage.Trim().Split(' ');
            TcpAppCommand cmdHandler = GetCommand(cmdArg[1]);

            if (cmdHandler == null)
            {
                //Error - Unrecognized command.
                e.Client.WriteLineToClient(string.Format("#TCP# {0} {1} Invalid Command!",
                                                         cmdArg[1], TcpAppCommandStatus.ERR.ToString()));
                return;
            }

            TcpAppInputCommand cmdInput = new TcpAppInputCommand()
            {
                Command = cmdHandler
            };

            cmdHandler.ResetArgumentsValue();
            int argID = 2; //First Argument

            foreach (TcpAppArgument item in cmdHandler.Arguments)
            {
                if (argID >= cmdArg.Length)
                {
                    //Argument with no input
                    if (!item.IsOptional)
                    {
                        //Error - Missing required argument
                        cmdInput.OutputMessage = "Missing required argument: " + item.Name + "!";
                        WriteResultToClient(e.Client, cmdInput);
                        return;
                    }
                }
                else
                {
                    item.Value = cmdArg[argID]; //Assign argument value
                }
                argID++;
            }
            cmdInput.Command.ExecuteCallback(cmdInput); //Send result back to client.
            WriteResultToClient(e.Client, cmdInput);
        }
        /// <summary>
        /// Clone current object
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            TcpAppCommand result = new TcpAppCommand();

            result.Description     = Description;
            result.Keyword         = Keyword;
            result.ExecuteCallback = ExecuteCallback;
            result.IsSystemCommand = IsSystemCommand;
            result.UseMessageQueue = UseMessageQueue;
            foreach (TcpAppParameter p in Parameters)
            {
                result.AddParameter(p);
            }
            return(result);
        }
示例#5
0
        /// <summary>
        /// Register new command.
        /// </summary>
        /// <param name="command">Command keyword, single word.</param>
        /// <param name="description">Short description of command.</param>
        /// <param name="executeCallback">Command execution callback.</param>
        /// <returns></returns>
        public TcpAppCommand RegisterCommand(string command, string description, TcpAppServerExecuteDelegate executeCallback)
        {
            if (GetCommand(command) != null)
            {
                throw new ArgumentException("Failed to register command [" + command + "], already exist!");
            }
            if (command.Contains(" "))
            {
                throw new ArgumentException("Invalid Character in command name, space ' ' is not allowed!");
            }

            TcpAppCommand tCmd = new TcpAppCommand(command, description, executeCallback);

            Commands.Add(tCmd);
            return(tCmd);
        }
示例#6
0
        /// <summary>
        /// Execute Plugin Callback. Call by ITcpAppServerPlugin
        /// </summary>
        /// <param name="sender"></param>
        public void ExecutePluginCommand(TcpAppInputCommand sender)
        {
            sender.Status = TcpAppCommandStatus.ERR;
            string[] cmdArg = sender.Arguments.Skip(1).ToArray();

            //Process Command Keyword
            TcpAppCommand cmdHandler = GetCommand(cmdArg[0]);

            if (cmdHandler == null)
            {
                //Error - Unrecognized command.
                sender.OutputMessage = string.Format("Invalid Command: {0}!", cmdArg[0]);
                return;
            }
            sender.Command = cmdHandler;

            //Process Parameters
            cmdHandler.ResetParametersValue();
            int argID = 1; //First Parameter

            foreach (TcpAppParameter item in cmdHandler.Parameters)
            {
                if (argID >= cmdArg.Length)
                {
                    //Argument with no input
                    if (!item.IsOptional)
                    {
                        //Error - Missing required parameter
                        sender.OutputMessage = "Missing required parameter: " + item.Name + "!";
                        return;
                    }
                }
                else
                {
                    item.Value = cmdArg[argID]; //Assign parameter value
                }
                argID++;
            }

            //Execute Command.
            //Note: Error handling not required. Will handle by TcpAppServer class.
            sender.Command.ExecuteCallback(sender);
        }
示例#7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mainForm">Main Form Handle</param>
        public TcpAppServer(Form mainForm) : base()
        {
            MainForm                 = mainForm;
            MessageDelimiter         = Convert.ToByte('\n');
            base.ClientConnected    += TcpAppServer_ClientConnected;
            base.ClientDisconnected += TcpAppServer_ClientDisconnected;

            //TcpAppServer Format:
            // TX: #TCP# <Command> [Param0] ... [ParamN]
            // RX: #TCP# <Command> <Status> [Return Message]
            // Source - [email protected]:23
            // Command - Registered Command.

            //Register System Commands
            //-- APP INFO --
            RegisterCommand("TcpAppInit", "Initialize TCP Application.", delegate(TcpAppInputCommand sender)
            {
                sender.OutputMessage = string.IsNullOrEmpty(WelcomeMessage) ? Application.ProductName + " " + Application.ProductVersion : WelcomeMessage;
                sender.Status        = TcpAppCommandStatus.OK;
            });
            RegisterCommand("ProgramName?", "Get Application Name.", delegate(TcpAppInputCommand sender)
            {
                sender.OutputMessage = Application.ProductName;
                sender.Status        = TcpAppCommandStatus.OK;
            });
            RegisterCommand("ProgramVersion?", "Get Application Version.", delegate(TcpAppInputCommand sender)
            {
                sender.OutputMessage = Application.ProductVersion;
                sender.Status        = TcpAppCommandStatus.OK;
            });
            RegisterCommand("TcpAppVersion?", "Get TcpAppServer Library Version", delegate(TcpAppInputCommand sender)
            {
                sender.OutputMessage = Version.ToString();
                sender.Status        = TcpAppCommandStatus.OK;
            });
            RegisterCommand("GetFunctionList", "Get list of registered functions.", delegate(TcpAppInputCommand sender)
            {
                foreach (TcpAppCommand x in Commands)
                {
                    sender.OutputMessage += x.Keyword;
                    //foreach(TcpAppArgument a in x.Arguments)
                    //{
                    //    sender.OutputMessage += "/" + a.Name;
                    //}
                    sender.OutputMessage += " ";
                }
                sender.Status = TcpAppCommandStatus.OK;
            });

            //-- GUI Control --
            string ErrMainFormNull = "Main Form not assigned!";

            RegisterCommand("MinimizeWindow", "Minimize Application Window.", delegate(TcpAppInputCommand sender)
            {
                if (MainForm != null)
                {
                    MainForm.WindowState = FormWindowState.Minimized;
                    sender.Status        = TcpAppCommandStatus.OK;
                }
                else
                {
                    sender.OutputMessage = ErrMainFormNull;
                }
            });
            RegisterCommand("RestoreWindow", "Restore Application Window.", delegate(TcpAppInputCommand sender)
            {
                if (MainForm != null)
                {
                    MainForm.WindowState = FormWindowState.Normal;
                    sender.Status        = TcpAppCommandStatus.OK;
                }
                else
                {
                    sender.OutputMessage = ErrMainFormNull;
                }
            });
            RegisterCommand("BringToFront", "Set Application Window as Top Most.", delegate(TcpAppInputCommand sender)
            {
                if (MainForm != null)
                {
                    MainForm.BringToFront();
                    sender.Status = TcpAppCommandStatus.OK;
                }
                else
                {
                    sender.OutputMessage = ErrMainFormNull;
                }
            });
            TcpAppCommand cmd = RegisterCommand("SetWindowPosition", "Set Window Position.", delegate(TcpAppInputCommand sender)
            {
                if (MainForm != null)
                {
                    MainForm.Location = new System.Drawing.Point(
                        Convert.ToInt16(sender.Command.Argument("XPos").Value),
                        Convert.ToInt16(sender.Command.Argument("YPos").Value));
                    sender.Status = TcpAppCommandStatus.OK;
                }
                else
                {
                    sender.OutputMessage = ErrMainFormNull;
                }
            });

            cmd.AddArgument(new TcpAppArgument("X", "Upper left X coordinate of main form.", 0, false));
            cmd.AddArgument(new TcpAppArgument("Y", "Upper left Y coordinate of main form.", 0, false));

            //-- User Interaction --
            RegisterCommand("Help", "Show help screen.", ShowHelp);
        }
        private void Client_ProcessReceivedMessage(TcpServerConnection client, string message, byte[] messageBytes)
        {
            //Parse and Execute Commands
            string[] cmdArg = TcpAppCommon.ParseCommand(message.Trim());

            //Process Command Keyword
            TcpAppCommand cmdHandler = GetCommand(cmdArg[0]);

            if (cmdHandler == null)
            {
                //Error - Unrecognized command.
                client.WriteLineToClient(string.Format("{0} {1} Invalid Command!",
                                                       cmdArg[0], TcpAppCommandStatus.ERR.ToString()));
                return;
            }
            TcpAppInputCommand cmdInput = new TcpAppInputCommand()
            {
                Command = cmdHandler
            };

            cmdInput.Arguments = cmdArg.Skip(1).ToArray(); //Move to TcpAppInputCommand

            //Process Parameters
            cmdHandler.ResetParametersValue();
            int argID = 1; //First Parameter

            foreach (TcpAppParameter item in cmdHandler.Parameters)
            {
                if (argID >= cmdArg.Length)
                {
                    //Argument with no input
                    if (!item.IsOptional)
                    {
                        //Error - Missing required parameter
                        cmdInput.OutputMessage = "Missing required parameter: " + item.Name + "!";
                        WriteResultToClient(client, cmdInput);
                        return;
                    }
                }
                else
                {
                    item.Value = cmdArg[argID]; //Assign parameter value
                }
                argID++;
            }

            //Execute Commands
            try
            {
                cmdInput.Command.ExecuteCallback(cmdInput);
            }
            catch (Exception ex)
            {
                //Catch and report all execution error
                cmdInput.OutputMessage = "Exception Raised! " + ex.Message;
                cmdInput.Status        = TcpAppCommandStatus.ERR; //Force status to error, make sure no surprise.
            }
            finally
            {
                WriteResultToClient(client, cmdInput); //Send result back to client.
            }
        }