Пример #1
0
            public virtual object Execute(ICommandContext commandContext)
            {
                CommandConfig            commandConfig           = outerInstance.processEngineConfiguration.CommandExecutor.DefaultConfig.TransactionRequiresNew();
                IFailedJobCommandFactory failedJobCommandFactory = commandContext.FailedJobCommandFactory;
                ICommand <object>        cmd = failedJobCommandFactory.GetCommand(outerInstance.job.Id, exception);

                log.LogTrace($"Using FailedJobCommandFactory '{failedJobCommandFactory.GetType()}' and command of type '{cmd.GetType()}'");
                outerInstance.processEngineConfiguration.CommandExecutor.Execute(commandConfig, cmd);

                // Dispatch an event, indicating job execution failed in a
                // try-catch block, to prevent the original exception to be swallowed
                if (commandContext.EventDispatcher.Enabled)
                {
                    try
                    {
                        commandContext.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityExceptionEvent(ActivitiEventType.JOB_EXECUTION_FAILURE, outerInstance.job, exception));
                    }
                    catch (Exception ignore)
                    {
                        log.LogWarning(ignore, "Exception occurred while dispatching job failure event, ignoring.");
                    }
                }

                return(commandContext.GetResult());
            }
Пример #2
0
        /// <summary>
        /// Calls a method of the OPC server.
        /// </summary>
        private bool CallMethod(CommandConfig commandConfig, string cmdData)
        {
            Log.WriteLine(Locale.IsRussian ?
                          "Вызов метода {0}" :
                          "Call the {0} method", commandConfig.DisplayName);

            IList <object> methodResults = opcSession.Call(
                new NodeId(commandConfig.ParentNodeID),
                new NodeId(commandConfig.NodeID),
                GetMethodArgs(cmdData));

            if (methodResults == null)
            {
                Log.WriteLine(CommPhrases.ResponseOK);
            }
            else
            {
                for (int i = 0, cnt = methodResults.Count; i < cnt; i++)
                {
                    Log.WriteLine("Result[{0}] = {1}", i, methodResults[i]);
                }
            }

            Log.WriteLine(CommPhrases.ResponseOK);
            return(true);
        }
Пример #3
0
        private List <CommandConfig> GetCommands()
        {
            List <CommandConfig> commands = new List <CommandConfig>();

            string[] commandDlls = Directory.GetFiles(ConfigurationManager.AppSettings["CommandsDllPath"], "BallyTech.UI.Web.Command.*.dll");
            foreach (var item in commandDlls)
            {
                Assembly commandDll = Assembly.LoadFrom(item);

                Type[] commandTypes = commandDll.GetTypes();

                foreach (var type in commandTypes)
                {
                    Type commandType = type;
                    while (commandType != null && (commandType.Name != typeof(ProcessCommand <,>).Name && commandType.Name != typeof(ParameterizedActionCommand <>).Name && commandType.Name != typeof(RequestCommand <>).Name && commandType.Name != typeof(ExecutorCommand).Name))
                    {
                        commandType = commandType.BaseType;
                    }

                    if (commandType != null && (commandType.Name == typeof(ProcessCommand <,>).Name || commandType.Name == typeof(ExecutorCommand).Name || commandType.Name == typeof(RequestCommand <>).Name || commandType.Name == typeof(ParameterizedActionCommand <>).Name))
                    {
                        CommandConfig command = new CommandConfig();
                        command.CommandKey = type.FullName;
                        command.CommandUri = type.AssemblyQualifiedName;
                        commands.Add(command);
                    }
                }
            }

            return(commands);
        }
        /// <summary>
        /// Fires the event for the provided <seealso cref="TransactionState"/>.
        /// </summary>
        /// <param name="transactionState"> The <seealso cref="TransactionState"/> for which the listeners will be called. </param>
        /// <param name="executeInNewContext"> If true, the listeners will be called in a new command context.
        ///                            This is needed for example when firing the <seealso cref="TransactionState"/>
        ///                            event: the transacation is already committed and executing logic in the same
        ///                            context could lead to strange behaviour (for example doing a <seealso cref="DbSqlSession"/>
        ///                            would actually roll back the update (as the MyBatis context is already committed
        ///                            and the internal flags have not been correctly set). </param>
        protected internal virtual void FireTransactionEvent(TransactionState transactionState, bool executeInNewContext)
        {
            if (stateTransactionListeners == null)
            {
                return;
            }

            IList <ITransactionListener> transactionListeners = stateTransactionListeners[transactionState];

            if (transactionListeners == null)
            {
                return;
            }

            if (executeInNewContext)
            {
                ICommandExecutor commandExecutor = commandContext.ProcessEngineConfiguration.CommandExecutor;
                CommandConfig    commandConfig   = new CommandConfig(false, TransactionPropagation.REQUIRES_NEW);
                commandExecutor.Execute(commandConfig, new CommandAnonymousInnerClass(this, transactionListeners));
            }
            else
            {
                ExecuteTransactionListeners(transactionListeners, commandContext);
            }
        }
Пример #5
0
        public void CanCreateProductWithCommand_CallsRepository()
        {
            var commandRepoMock = new Mock <ICommandStateRepository>();
            var productsMock    = new Mock <IProductService>();
            var commandState    = new Fakes.CommandState();

            commandRepoMock.Setup(t => t.CreateCommandState()).Returns(commandState);

            var guid = Guid.NewGuid();
            var name = "New Project";

            var sut           = new CommandManager(commandRepoMock.Object, new DateTimeProvider());
            var commandConfig = new CommandConfig {
                Assembly = TestGlobals.Assembly, NameSpace = TestGlobals.Namespace, Name = CommandTypes.Create.ToString(), ProcessorName = TestGlobals.Entity, Processor = productsMock.Object
            };

            sut.AddConfig(commandConfig);

            var commandDto = new CommandDto {
                Entity = TestGlobals.Entity, EntityGuid = guid, Name = CommandTypes.Create.ToString(), ParametersJson = @"{name: '" + name + "'}"
            };
            var sutResult = sut.ProcessCommand(commandDto);

            productsMock.Verify(v => v.CreateProduct(guid, name), Times.Once);
        }
Пример #6
0
        public override bool loadJson(JObject jobj)
        {
            base.loadJson(jobj);
            initKVArray();
            CommandConfig cfg = ScriptConfig.Instance.getCommandConfig(id);

            if (cfg.FieldRepeat <= 1)
            {
                EexFieldReader reader = new EexFieldReader((JArray)jobj["fields"]);

                for (int i = 0; i < FieldCount; i++)
                {
                    values[i] = reader.readFieldObject(keys[i]);
                }
            }
            else
            {
                JArray jar = (JArray)jobj["array"];

                for (int i = 0; i < cfg.FieldRepeat; i++)
                {
                    EexFieldReader reader = new EexFieldReader((JArray)jar[i]);

                    Object[] objs = new Object[FieldCount];
                    for (int j = 0; j < FieldCount; j++)
                    {
                        objs[j] = reader.readFieldObject(keys[j]);
                    }
                    arrayValues[i] = objs;
                }
            }

            return(true);
        }
Пример #7
0
 public static void UpdateCommandsList()
 {
     commands = JsonConvert.DeserializeObject <CommandConfig>(File.ReadAllText(@"ClassicAssistant/Commands.json"), new JsonSerializerSettings {
         Culture = new System.Globalization.CultureInfo("pl-pl")
     });
     recognizer.LoadGrammarAsync(new Grammar(new GrammarBuilder(new Choices(commands.Command.Where(x => !x.IsConfimation).Select(x => x.CommandText).ToArray()))));
 }
Пример #8
0
        public override bool loadReader(EexBinaryReader reader)
        {
            initKVArray();
            CommandConfig cfg = ScriptConfig.Instance.getCommandConfig(Id);

            if (cfg.FieldRepeat <= 1)
            {
                for (int i = 0; i < FieldCount; i++)
                {
                    values[i] = reader.readFieldObject(keys[i]);
                }
            }
            else
            {
                for (int i = 0; i < cfg.FieldRepeat; i++)
                {
                    Object[] objs = new Object[FieldCount];
                    for (int j = 0; j < FieldCount; j++)
                    {
                        objs[j] = reader.readFieldObject(keys[j]);
                    }
                    arrayValues[i] = objs;
                }
            }

            return(true);
        }
Пример #9
0
            public override IRedisSocket GetRedisSocket(CommandPacket cmd)
            {
                if (_rw_plitting && cmd != null)
                {
                    var cmdcfg = CommandConfig.Get(cmd._command);
                    if (cmdcfg != null)
                    {
                        if (
                            (cmdcfg.Tag & CommandTag.read) == CommandTag.read &&
                            (cmdcfg.Flag & CommandFlag.@readonly) == CommandFlag.@readonly)
                        {
                            var rndkeys = _ib.GetKeys(v => v == null || v.IsAvailable && v._policy._connectionStringBuilder.Host != _masterHost);
                            if (rndkeys.Any())
                            {
                                var rndkey  = rndkeys[_rnd.Value.Next(0, rndkeys.Length)];
                                var rndpool = _ib.Get(rndkey);
                                var rndcli  = rndpool.Get();
                                var rndrds  = rndcli.Value._adapter.GetRedisSocket(null);
                                return(new DefaultRedisSocket.TempRedisSocket(rndrds, () => rndpool.Return(rndcli)));
                            }
                        }
                    }
                }
                var poolkey = _masterHost;
                var pool    = _ib.Get(poolkey);
                var cli     = pool.Get();
                var rds     = cli.Value._adapter.GetRedisSocket(null);

                return(new DefaultRedisSocket.TempRedisSocket(rds, () => pool.Return(cli)));
            }
Пример #10
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            tbLog.AppendText(DateTime.Now.ToString() + " 开始检查\r\n");
            try
            {
                CommandConfig ccfg = new CommandConfig();
                ccfg.init(tbCheckPath.Text);
                ccfg.ShowAllLog = cbAllLog.Checked;

                CommandList cl = new CommandList();
                cl.CheckFileExist      = cbFileExist.Checked;
                cl.CheckFileName       = cbFileName.Checked;
                cl.CheckJson           = cbJson.Checked;
                cl.CheckScene          = cbScene.Checked;
                cl.CheckStrings        = cbStrings.Checked;
                cl.CheckGlobalRes      = cbGlobalRes.Checked;
                cl.OutputDataReceived += DataReceived;
                if (cl.loadXml("commandlist.xml"))
                {
                    cl.runCmd(ccfg);
                }
            }
            catch (Exception ex)
            {
                logText(ex.ToString());
            }
        }
Пример #11
0
        private void LoadCustomCommands()
        {
            if (_config != null || Host.Plugins.Any(m => m.Id == Id))
            {
                return;
            }
            _config = new CommandConfig
            {
                Menus =
                {
                    new AssemblyInfoMenu()
                }
            };
            var plugin = new Plugin
            {
                Id            = Id,
                CommandConfig = _config,
                Assembly      = Assembly.GetExecutingAssembly(),
                Location      =
                    Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", ""),
                //ResourceManager = new ResourceManager(config.ResourceManager, Assembly.GetExecutingAssembly())
            };


            var manager = new CommandManager(plugin);

            manager.Load();
        }
Пример #12
0
        public override JObject toJsonObject()
        {
            CommandConfig cfg = ScriptConfig.Instance.getCommandConfig(id);
            JObject       ret = base.toJsonObject();

            if (arrayValues.GetLength(0) > 1)
            {
                JArray jar = new JArray();
                ret.Add("array", jar);

                for (int i = 0; i < arrayValues.GetLength(0); i++)
                {
                    JArray kvArr = new JArray();
                    jar.Add(kvArr);
                    for (int j = 0; j < FieldCount; j++)
                    {
                        kvArr.Add(createKV(keys[j], arrayValues[i][j]));
                    }
                }
            }
            else
            {
                JArray fields = new JArray();
                ret.Add("fields", fields);
                for (int j = 0; j < cfg.FieldIds.Length; j++)
                {
                    int fieldId  = cfg.FieldIds[j];
                    int keyIndex = j;
                    fields.Add(createKV(fieldId, values[keyIndex]));
                }
            }

            return(ret);
        }
Пример #13
0
 public object ExecuteNonQuery(CommandConfig cmd)
 {
     using (DbNetData db = CreateDbNetData())
     {
         return(db.ExecuteNonQuery(cmd));
     }
 }
Пример #14
0
 /// <summary>
 /// Creates a new command node according to the command configuration.
 /// </summary>
 private static TreeNode CreateCommandNode(CommandConfig commandConfig)
 {
     return(TreeViewExtensions.CreateNode(
                GetDisplayName(commandConfig.DisplayName, DriverPhrases.UnnamedCommand),
                ImageKey.Command,
                commandConfig));
 }
Пример #15
0
        /// <summary>
        /// Registers objects to the <see cref="container"/>
        /// </summary>
        public static void RegisterTypes()
        {
            container = new UnityContainer();
            container.RegisterType <IBot, Bot>(new PerThreadLifetimeManager());
            container.RegisterSingleton <IConnection, Connection>();

            container.RegisterType <ILogger, Logger.Logger>(new PerThreadLifetimeManager());


            // DI for discord
            container.RegisterFactory <DiscordSocketConfig>(i => SocketConfig.GetDefault(), new SingletonLifetimeManager());
            container.RegisterFactory <CommandService>(i => CommandConfig.GetDefault(), new SingletonLifetimeManager());
            container.RegisterSingleton <DiscordShardedClient>(new InjectionConstructor(typeof(DiscordSocketConfig)));
            container.RegisterSingleton <IClientLogHandler, ClientLogHandler>();
            container.RegisterSingleton <IMiscEventHandler, MiscEventHandler>();
            container.RegisterSingleton <IPrefixService, PrefixService>();
            container.RegisterSingleton <IBotListUpdater, BotListUpdater>();
            container.RegisterSingleton <DiscordBotListsUpdateTimer>();

            container.RegisterType <ICommandErrorHandler, CommandErrorHandler>(new PerThreadLifetimeManager());
            container.RegisterType <ICommandInputErrorHandler, CommandInputErrorHandler>(new PerThreadLifetimeManager());
            container.RegisterType <ICommandHandler, CommandHandler>(new PerThreadLifetimeManager());
            container.RegisterType <ISpamFilter, SpamFilter>(new PerThreadLifetimeManager());


            // DI for Entity framework
            container.RegisterType <BotContext>(new PerResolveLifetimeManager());
            container.RegisterType <IUnitOfWork, UnitOfWork>(new PerResolveLifetimeManager());
            container.RegisterType <IRequestUnitOfWork, RequestUnitOfWork>(new PerResolveLifetimeManager());
            container.RegisterType <IServerUnitOfWork, ServerUnitOfWork>(new PerResolveLifetimeManager());
            container.RegisterType <IServerRepository, ServerRepository>(new PerResolveLifetimeManager());
            container.RegisterType <IUserRepository, UserRepository>(new PerResolveLifetimeManager());
            container.RegisterType <IRequestRepository, RequestRepository>(new PerResolveLifetimeManager());
        }
Пример #16
0
 private void UpdateCommandHandlerIfExist(CommandConfig config)
 {
     if (_commandHandlers.ContainsKey(config.Id))
     {
         _commandHandlers[config.Id].Config = config;
     }
 }
Пример #17
0
        public CommandConfig LoadConfig(string configfilepath, bool otherwisedefault = true)
        {
            CommandConfig cfg = null;

            if (File.Exists(configfilepath))
            {
                cfg = configfilepath.ReadYamlFile <CommandConfig>();
            }
            if (cfg == null)
            {
                configmanager.LastConfigFilePath = null;
                if (otherwisedefault)
                {
                    cfg = new CommandConfig();
                }
            }
            if (cfg != null)
            {
                if (cfg.EnvCrossInheritRule == null)
                {
                    cfg.EnvCrossInheritRule = new Dictionary <string, Dictionary <string, List <string> > >();
                }
                cfg.EnvCrossInheritRule = ValidateEnvCrossInheritRule(cfg.EnvCrossInheritRule);
            }
            return(cfg);
        }
Пример #18
0
        public virtual void Execute(ICommandContext commandContext)
        {
            ICommandExecutor commandExecutor = commandContext.ProcessEngineConfiguration.CommandExecutor;
            CommandConfig    commandConfig   = new CommandConfig(false, TransactionPropagation.REQUIRES_NEW);

            commandExecutor.Execute(commandConfig, new CommandAnonymousInnerClass(this));
        }
Пример #19
0
        public long ExecuteInsert(CommandConfig CmdConfig, bool returnVal)
        {
            DbNetData db = dbp.GetObject();

            try
            {
                if (returnVal)
                {
                    db.ReturnAutoIncrementValue = true;
                }
                long r = db.ExecuteInsert(CmdConfig);
                if (returnVal)
                {
                    db.ReturnAutoIncrementValue = false;
                }
                return(r);
            }
            catch
            {
                throw;
            }
            finally
            {
                dbp.PutObject(db);
            }
        }
Пример #20
0
        private List<CommandConfig> GetCommands()
        {
            List<CommandConfig> commands = new List<CommandConfig>();
            string[] commandDlls = Directory.GetFiles(ConfigurationManager.AppSettings["CommandsDllPath"], "BallyTech.UI.Web.Command.*.dll");
            foreach (var item in commandDlls)
            {
                Assembly commandDll = Assembly.LoadFrom(item);
                
                Type[] commandTypes = commandDll.GetTypes();

                foreach (var type in commandTypes)
                {
                    Type commandType = type;
                    while (commandType != null && (commandType.Name != typeof(ProcessCommand<,>).Name && commandType.Name != typeof(ParameterizedActionCommand<>).Name && commandType.Name != typeof(RequestCommand<>).Name && commandType.Name != typeof(ExecutorCommand).Name))
                    {
                        commandType = commandType.BaseType;
                    }

                    if (commandType != null && (commandType.Name == typeof(ProcessCommand<,>).Name || commandType.Name == typeof(ExecutorCommand).Name || commandType.Name == typeof(RequestCommand<>).Name || commandType.Name == typeof(ParameterizedActionCommand<>).Name))
                    {
                        CommandConfig command = new CommandConfig();
                        command.CommandKey = type.FullName;
                        command.CommandUri = type.AssemblyQualifiedName;
                        commands.Add(command);
                    }
                }                
            }

            return commands;
        }
Пример #21
0
        public override void OnExecute(ICommandContext context, CommandConfig config, CommandResult result)
        {
            var actionResult = result as ExtendedActionResult;
            var paras        = Parameters.CreateDictionary(context);
            var actionItem   = ContentActions.GetItem(ContentAddress);

            if (actionItem != null)
            {
                var content = actionItem.Func(paras);
                if (content is ActionResult)
                {
                    actionResult.ActionResult = content as ActionResult;
                }
                else
                {
                    var contentResult = new ContentResult
                    {
                        Content         = content.ToString(),
                        ContentEncoding = actionItem.Encoding,
                        ContentType     = actionItem.ContentType
                    };
                    actionResult.ActionResult = contentResult;
                }
            }

            result.End(NextCommand);
            context.Execute(NextCommand);
        }
Пример #22
0
        public override void init()
        {
            initKVArray();
            CommandConfig cfg = ScriptConfig.Instance.getCommandConfig(Id);

            if (cfg.FieldRepeat <= 1)
            {
                for (int i = 0; i < FieldCount; i++)
                {
                    values[i] = newFieldValue(keys[i]);
                }
            }
            else
            {
                for (int i = 0; i < cfg.FieldRepeat; i++)
                {
                    Object[] objs = new Object[FieldCount];
                    for (int j = 0; j < FieldCount; j++)
                    {
                        objs[j] = newFieldValue(keys[j]);
                    }
                    arrayValues[i] = objs;
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Creates a new command node according to the command configuration.
        /// </summary>
        private TreeNode CreateCommandNode(CommandConfig commandConfig)
        {
            TreeNode commandNode = TreeViewUtils.CreateNode(
                GetDisplayName(commandConfig.DisplayName, KpPhrases.EmptyCommand),
                "command.png");

            commandNode.Tag = commandConfig;
            return(commandNode);
        }
Пример #24
0
        private async Task AddCommandHandlerAsync(CommandConfig config, ServiceCollection services, CommandService modules)
        {
            CommandHandler handler = new CommandHandler(_discord, services.BuildServiceProvider(), modules, config);

            AddCommandHandler(handler);
            SubscribeCommandConfigsProviderOnChanges(handler);
            ConfigsProvider?.AddCommandConfig(handler.Config);
            await _log.RaiseAsync(LogSeverity.Info, $"Command handler created for {handler.Config.Source.ToString().ToLower()} {handler.Config.Name}");
        }
Пример #25
0
        public PrintHelpCommandExecutionContext(CliConfig cliConfig, CommandConfig commandConfig)
            : base((commandArgs, output) =>
        {
            output.Write(cliConfig.HelpConfig.Printer.PrintHelp(cliConfig, commandConfig));

            return(0);
        }, null)
        {
        }
Пример #26
0
        public void TestInsert()
        {
            DbNetData db = GetDB();

            db.Open();
            string        sql = @"insert into tblStation(stationOridnal, stationName, stationRemark, stationcpConfig) values (1, 'name', 'remark', 'cp config')";
            CommandConfig cmd = new CommandConfig(sql);

            db.ExecuteScalar(cmd);
        }
Пример #27
0
 /// <summary>
 /// Shows the command properties.
 /// </summary>
 private void ShowCommandProps(CommandConfig commandConfig)
 {
     if (commandConfig != null)
     {
         txtDisplayName.Text = commandConfig.DisplayName;
         txtNodeID.Text      = commandConfig.NodeID;
         txtDataType.Text    = commandConfig.DataTypeName;
         numCmdNum.SetValue(commandConfig.CmdNum);
     }
 }
Пример #28
0
        public object ExecuteNonQuery(string sql, ListDictionary paramsDict)
        {
            CommandConfig cmd = new CommandConfig(sql);

            if (paramsDict != null)
            {
                cmd.Params = paramsDict;
            }
            return(ExecuteNonQuery(cmd));
        }
Пример #29
0
        public override void OnExecute(ICommandContext context, CommandConfig config, CommandResult result)
        {
            var viewResult = result as RedirectCommandResult;

            viewResult.ControllerName = ControllerName;
            viewResult.ActionName     = ActionName;

            result.End(NextCommand);
            context.Execute(NextCommand);
        }
Пример #30
0
        public CommandConfigEditor(IRobotWare root, CommandConfig cfg) :
            this(root)
        {
            CmdText.Text         = cfg.Text;
            CmdIco.Image         = Image.FromFile(cfg.Image);
            CmdHint.Text         = cfg.Hint;
            Macros.SelectedIndex = Macros.Items.IndexOf(cfg.SpecFileName);

            Text = "Edit: " + cfg.Text;
        }
Пример #31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public object ExecuteNonQuery(string sql, KeyValueCollection parameters)
        {
            CommandConfig cmd = new CommandConfig(sql);

            foreach (KeyValue kv in parameters)
            {
                cmd.Params.Add(kv.Key, kv.Value);
            }
            return(ExecuteNonQuery(cmd));
        }
Пример #32
0
 public static int CommandComparer(CommandConfig a, CommandConfig b)
 {
   return a.Name.CompareTo(b.Name);
 }
        private void SelectProcessingCommandsForm_Load(object sender, EventArgs e)
        {
            try
            {
                List<CommandConfig> commandConfigs = new List<CommandConfig>();

                var allCommands = Proxies.SchedulerService.GetAllProcessingCommands().Result;
                foreach (ProcessingCommand command in allCommands)
                {
                    CommandConfig commandConfig = new CommandConfig();
                    commandConfig.ProcessingCommandId = command.ProcessingCommandId;
                    commandConfig.Name = command.Name;
                    commandConfig.RunCommand = IsCommandInSchedule(_schedule, command.ProcessingCommandId);
                    commandConfigs.Add(commandConfig);
                }
                _commandsBindingSource.DataSource = commandConfigs;
                _commandsBindingSource.ResetBindings(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 public void SetUp()
 {
     _defaultNameCommand = CommandAttributeLoader.Load(typeof (DefaultName)) as CommandConfig<DefaultName>;
 }