예제 #1
0
        /// <summary>
        /// Execute Plugin Callback. Call by ITcpAppServerPlugin
        /// </summary>
        /// <param name="commandArguments">Command keyword and arguments in string array.</param>
        public TcpAppInputCommand GetPluginCommand(string [] commandArguments)
        {
            if (commandArguments == null)
            {
                throw new ArgumentNullException(nameof(commandArguments), "Invalid command / empty string!");
            }

            TcpAppInputCommand command = TcpAppCommon.CreateInputCommand(Commands, commandArguments);

            if (command == null)
            {
                throw new ArgumentException("Unknown command: " + commandArguments.FirstOrDefault());
            }
            return(command);
        }
        private void ShowHelp(TcpAppInputCommand sender)
        {
            string        aliasName = sender.Command.Parameter("Alias").Value;
            List <string> lines     = null;

            if (aliasName == "-")
            {
                //Print Help Screen - Write to sender.OutputMessage
                lines = new List <string>
                {
                    "TCP Aplication Server Version " + Version.ToString(),
                    " ",
                    "==== USAGE ====",
                    "  SEND: <Command> [Param0] ... [ParamN]",
                    "  RECV: <Command> <Status> [Return Message]",
                    " ",
                    " Notes:",
                    "  <> = Required parameters",
                    "  [] = Optional parameters",
                    " ",
                };

                lines.AddRange(TcpAppCommon.PrintCommandHelpContents(Commands));
                sender.OutputMessage = string.Join("\r\n", lines.ToArray());
                sender.Status        = TcpAppCommandStatus.OK;
            }
            else
            {
                //Get Help Content for selected object.
                ITcpAppServerPlugin plugin = Plugins.FirstOrDefault(x => string.Compare(x.Alias, sender.Command.Parameter("Alias").Value, true) == 0);
                if (plugin == null)
                {
                    sender.Status        = TcpAppCommandStatus.ERR;
                    sender.OutputMessage = "Object [" + aliasName + "] not exist!";
                }
                else
                {
                    plugin.ShowHelp(sender);
                }
            }
        }
예제 #3
0
 /// <summary>
 /// Print help screen for selected plugin components.
 /// </summary>
 /// <param name="sender"></param>
 public void ShowHelp(TcpAppInputCommand sender)
 {
     sender.OutputMessage = string.Join("\r\n", TcpAppCommon.PrintCommandHelpContents(Commands));
     sender.Status        = TcpAppCommandStatus.OK;
 }
        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.
            }
        }
예제 #5
0
        private void Client_ProcessReceivedMessage(TcpServerConnection client, string message, byte[] messageBytes)
        {
            //Parse and Execute Commands
            string[] cmdArg = TcpAppCommon.ParseCommand(message.Trim());
            try
            {
                //Register Client Connection
                TcpAppServerConnection ptrClient = AppClients.FirstOrDefault(x => x.Connection == client);
                if (ptrClient == null)
                {
                    //Reconstruct device which had already signed out
                    ptrClient = AddClientToAppClientsList(client);
                }
                Debug.WriteLine("AppServer[" + ptrClient.Name + "]-RX: " + message);

                TcpAppInputCommand inputCommand = TcpAppCommon.CreateInputCommand(Commands, cmdArg);
                if (inputCommand != null)
                {
                    inputCommand.AppClient = ptrClient;
                }
                else//Command keyword not exist
                {
                    //Check if command keyword is alias name
                    ITcpAppServerPlugin plugin = _Plugins.FirstOrDefault(x => string.Compare(x.Alias, cmdArg[0], true) == 0);
                    if (plugin != null)
                    {
                        //Execute plugin command
                        inputCommand           = plugin.GetPluginCommand(cmdArg.Skip(1).ToArray());
                        inputCommand.AppClient = ptrClient;
                        BeforeExecutePluginCommand?.Invoke(this, new TcpAppServerExEventArgs(ptrClient)
                        {
                            Plugin = plugin
                        });
                    }
                    else
                    {
                        //Error - Unrecognized command.
                        inputCommand = new TcpAppInputCommand()
                        {
                            Status        = TcpAppCommandStatus.ERR,
                            OutputMessage = "Invalid Command " + cmdArg[0]
                        };
                        WriteResultToClient(ptrClient, inputCommand);
                        return;
                    }
                }

                //Verify Client had signed in.
                if (!inputCommand.AppClient.SignedIn && !inputCommand.Command.IsSystemCommand)
                {
                    throw new Exception("Client not signed in! Execute SignIn first.");
                }

                if (inputCommand.Command.UseMessageQueue && !inputCommand.Command.IsSystemCommand)
                {
                    //Single thread execution, post message to message queue.
                    lock (CommandQueue)
                    {
                        inputCommand.ID = inputCommand.GetHashCode();
                        if (ptrClient.NextQueuedCommand == null)
                        {
                            ptrClient.NextQueuedCommand = inputCommand;                                      //Set pointer to next queued command.
                        }
                        //Add Command to Queue
                        CommandQueue.Add(inputCommand);
                        CommandQueueWaitSignal?.Set();
                        inputCommand.OutputMessage = inputCommand.ID.ToString();
                        inputCommand.Status        = TcpAppCommandStatus.QUEUED;
                    }
                }
                else if (inputCommand.Command.IsSystemCommand)
                {
                    inputCommand.ExecuteCallback();
                }
                else
                {
                    //Execute command, wait until return
                    if (ExecutionTimeout == 0)
                    {
                        inputCommand.ExecuteCallback();
                    }
                    //Execute command, terminate on timeout
                    else
                    {
                        ptrClient.ExecuteCommandAsync(inputCommand, ExecutionTimeout);
                    }
                }

                WriteResultToClient(ptrClient, inputCommand); //Send result back to client.
            }
            catch (Exception ex)
            {
                WriteExceptionErrorToClient(client, ex);
            }
        }
예제 #6
0
        private void ShowHelp(TcpAppInputCommand sender)
        {
            string        aliasName = sender.Command.Parameter("Plugin").Value;
            List <string> lines     = null;

            if (aliasName == "-")
            {
                lines = new List <string>
                {
                    "[ TCP Aplication Server V" + Version.ToString() + " ]",
                    " ",
                    "==== USAGE ====",
                    "  Execute Tcp App Server Command:",
                    "  SEND: <Command> [Param0] ... [ParamN]",
                    "  RECV: <Status> [Return Message]",
                    " ",
                    "  Execute plugin Command:",
                    "  SEND: <Alias> <Command> [Param0] ... [ParamN]",
                    "  RECV: <Status> [Return Message]",
                    " ",
                    "  Notes:",
                    "   Command are not case sensitive.",
                    "   <> = Required parameters",
                    "   [] = Optional parameters",
                    " ",
                };

                //Insert Application Header if defined.
                string header = OnShowHelpGetApplicationHeader();
                if (!string.IsNullOrEmpty(header))
                {
                    lines.Insert(0, header);
                }

                lines.AddRange(TcpAppCommon.PrintCommandHelpContents(Commands));

                //Print registered plugins
                if (PluginTypes.Count > 0)
                {
                    lines.Add("[ PLUGINS ]");
                    lines.AddRange(PluginTypes.Select(x => string.Format(" {0, -20}  {1}", x.Name, x.Description)).ToArray());
                    lines.Add(" ");
                }

                if (_Plugins.Count > 0)
                {
                    lines.Add("[ OBJECTS ]");
                    lines.AddRange(_Plugins.Select(x => string.Format(" {0, -20}  {1}", x.Alias, "(" + PluginTypes.FirstOrDefault(n => n.Type == x.GetType())?.Name + ")")).ToArray());
                }

                sender.OutputMessage = string.Join(TcpAppCommon.NewLine, lines.ToArray());
                sender.Status        = TcpAppCommandStatus.OK;
            }
            else
            {
                //Get Help Content for selected object.
                string pluginName              = sender.Command.Parameter("Plugin").Value;
                ITcpAppServerPlugin    plugin  = null;
                TcpAppServerPluginType ptrType = PluginTypes.FirstOrDefault(x => x.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase));
                if (ptrType != null)
                {
                    //Get help by type
                    Type pluginType = ptrType.Type;
                    plugin = _Plugins.FirstOrDefault(x => x.GetType() == pluginType);
                    if (plugin != null)
                    {
                        //Show Help using existing object
                        plugin.ShowHelp(sender);
                        return;
                    }

                    //Create instance and show help, dispose after use
                    plugin = Activator.CreateInstance(pluginType) as ITcpAppServerPlugin;
                    plugin.ShowHelp(sender);
                    plugin.DisposeRequest();
                    plugin = null;
                    return;
                }
                else
                {
                    //Get help by alias name
                    plugin = _Plugins.FirstOrDefault(x => string.Compare(x.Alias, pluginName, true) == 0);
                    if (plugin != null)
                    {
                        plugin.ShowHelp(sender);
                        return;
                    }
                }
                sender.Status        = TcpAppCommandStatus.ERR;
                sender.OutputMessage = "Object [" + aliasName + "] not exist!";
            }
        }