/// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(string connectionId, string data) { var command = new ExecuteCommand { ClientId = connectionId, Code = data }; var message = Convert.ToBase64String(command.GetBytes()); var gateway = DependencyResolver.Current.GetService<RedisConnectionGateway>(); var redis = gateway.GetConnection(); return redis.Lists.AddLast(0, "queue:execute", message) .ContinueWith(t => { if (t.IsFaulted) { return Send(new { status = "error", message = t.Exception != null ? t.Exception.Message : null }); } return Send(new { status = "ok" }); }); }
public static bool IsMatch(ExecuteCommand command, ExecuteOperator<Cell> executor, Tree<Cell> parameters) { var processor = new CellProcessorBase(); processor.AddOperator(new ParseMemberName()); ((CellOperator) executor).Processor = processor; return executor.CanExecute(new TypedValue(new ExecuteContext(command, null, new TypedValue("stuff"))), parameters); }
/// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(string connectionId, string data) { var post = JsonConvert.DeserializeObject<Post>(data); var command = new ExecuteCommand { ClientId = connectionId, Code = post.Content, Classes = post.Classes, Submitted = DateTime.UtcNow, TimeoutPeriod = ExecutionTimeout }; var message = command.GetBytes(); var gateway = DependencyResolver.Current.GetService<RedisConnectionGateway>(); var redis = gateway.GetConnection(); return redis.Lists.AddLast(0, "queue:execute", message) .ContinueWith(t => { if (t.IsFaulted) { return Send(new { status = "error", message = t.Exception != null ? t.Exception.Message : null }); } return Send(new { status = "ok" }); }); }
/// <summary> /// Use this to add a new command /// </summary> /// <param name="cmd"></param> /// <param name="executeCommand"></param> void AddCommand(string cmd, ExecuteCommand executeCommand) { var newCmd = new ValidCommand(); newCmd.Cmd = cmd; newCmd.ExecuteCommand = executeCommand; mCommands.Add(newCmd); }
public SerialPortControl(ExecuteCommand command) { this.buf = new byte[1024]; this.readByte = 0; this.isReading = false; this.port = new SerialPort("COM5", 2400, Parity.Even, 8, StopBits.Two); this.port.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceived); this.executeCommand = new ExecuteCommand(command); }
private void _executeMainCompileCommand() { ExecuteCommand executeCommand = new ExecuteCommand(); Console.WriteLine("Starting rendering."); File.Delete(Path.Combine(_compilatorPathFolder, "Compilation.mp4")); string command = $"cd {_compilatorPathFolder} & ffmpeg -f concat -safe 0 -i videos.txt -c:v libx264 -preset {_renderSpeed} -crf 13 -c:a aac Compilation.mp4"; executeCommand.Execute(command); Console.WriteLine("Rendering complete."); }
public MenuItemVm(IButtonItemModel model, IShellContainerVm shellContainerVm) : base(shellContainerVm) { MenuItemBackgroundColor = new SolidColorBrush(model.Color.ToRgbColor()); MenuItemBackgroundOverColor = new SolidColorBrush(model.Color.ToRgbLightColor(20)); MenuItemBackgroundPressedColor = new SolidColorBrush(model.Color.ToRgbLightColor(-20)); MenuItemLogo = new BitmapImage(new Uri(URI_RESOURCE + model.Image)); Title = model.Title; ExecuteCommand = ReactiveCommand.Create(Observable.Return(true)); _parameters = model.Parameters; ExecuteCommand.Subscribe(_ => ShellContainerVm.ChangeCurrentView(model.Code.ToEnum(), true, false, _parameters)); }
/// <summary> /// Initializes a new instance of the <see cref="TfptController"/> class. /// </summary> public TfptWrapperController() { if (this.WorkspaceHistory.History.Count > 0) { this.tfsWorkspace = this.WorkspaceHistory.History[0]; } LoadConfig(); ui = new TfptWrapperDialog(this); commandExecuter = new ExecuteCommand(ProcessCommand); }
static void Main(string[] args) { var arguments = ParseCommandLine(args); RequiredAttributes(arguments, "databaseProvider", "codeFormatProvider", "codeHighlightProvider", "outputProvider", "action" ); var loader = new AssemblyLoader(); var dbProvider = loader.CreateTypeFromAssembly <DbProvider>(arguments["databaseProvider"], arguments); var dbCodeFormatter = loader.CreateTypeFromAssembly <DbTraceCodeFormatter>(arguments["codeFormatProvider"], arguments); var codeHighlighter = loader.CreateTypeFromAssembly <HighlightCodeProvider>(arguments["codeHighlightProvider"], arguments); var outputProvider = loader.CreateTypeFromAssembly <OutputProvider>(arguments["outputProvider"], arguments); var command = arguments["action"].ToLower().Trim(); var traceName = arguments.ContainsKey("traceFileName") ? arguments["traceFileName"] : null; switch (command) { case "generate": RequiredAttributes(arguments, "traceFileName" ); var generateCommand = new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, traceName); generateCommand.Execute(); break; case "execute": RequiredAttributes(arguments, "target" ); traceName = traceName ?? DateTime.Now.ToString("yyyyMMddHHmmss"); var startCommand = new StartCommand(outputProvider, dbProvider, traceName); startCommand.Execute(); var executeCommand = new ExecuteCommand(arguments["target"], arguments.ContainsKey("targetArgs") ? arguments["targetArgs"] : string.Empty); executeCommand.Execute(); var stopCommand = new StopCommand(dbProvider, outputProvider, traceName); stopCommand.Execute(); break; } }
/// <summary> /// Execute a command. /// </summary> /// <param name="request"> /// An <see cref="ExecuteCommand"/> message indicating the command to execute. /// </param> /// <returns> /// The command result. /// </returns> async Task <CommandResult> Execute(ExecuteCommand request) { Log.Debug("Executing '{0}' command '{1}'.", request.RequestMessage.OperationName, request.CorrelationId ); InFlightRequest inFlightRequest = CreateRequest(request.RequestMessage, replyTo: Sender); Response responseMessage = await request.Command(_client, inFlightRequest.Cancellation); return(new CommandResult(responseMessage)); }
/// <summary> /// 生成执行数据源查询与交互的执行器。 /// </summary> /// <param name="engine">数据源查询与交互引擎的实例。</param> /// <param name="command">执行查询的命令。</param> /// <returns>返回执行数据源查询与交互的执行器。</returns> public static IDbExecutor Execute(this IDbEngine engine, ExecuteCommand command) { if (engine == null) { throw new ArgumentNullException("engine"); } if (command == null) { throw new ArgumentNullException("command"); } return(engine.Owner.Injector.CreateExecutor(engine, command)); }
private static void Run() { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile( path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var appSettings = new AppSettings(); new ConfigureFromConfigurationOptions <AppSettings>(configuration.GetSection("Settings")).Configure(appSettings); using (var watcher = new FileSystemWatcher()) { watcher.Path = appSettings.Path; // @"C:\\inetpub\\wwwroot\\tronar.multiplixe\\multiplixe.comum\\multiplixe.comum.enums\\bin\\Release"; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.nupkg"; watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; watcher.Created += (object sender, FileSystemEventArgs e) => { if (e.FullPath.ToLower().Contains("release")) { Console.WriteLine(">> {0}", e.FullPath); var command = new PublishNugetPackageCommand(e.FullPath, appSettings.Token); ExecuteCommand.Execute(command); } else { Console.WriteLine("Pacote não esta em modo RELEASE"); } }; Console.WriteLine($"Ouvindo pasta {appSettings.Path} ('q' pra sair)"); while (Console.Read() != 'q') { ; } } }
public void ExecuteCanActOnCommand() { var command = new MockCommand(); var action = new ExecuteCommand(); var getItems = new GetActionsForItem(new IActOnItem[] { action }); var actionsForItem = getItems.ActionsForItem(ResultForItem(new CommandItem(command))); Assert.NotEmpty(actionsForItem); Assert.Contains(action, actionsForItem); action.ActOn(command); Assert.True(command.Acted); }
public TreeItemContext(string taskName) { this.TaskName = new ReactiveProperty <string>(taskName); ExecuteCommand.Subscribe(() => { //実行する }); DeleteCommand.Subscribe(() => { //自身を削除 }); }
private void CreateCommands() { SearchCommand = new ExecuteCommand(() => NavigationService.NavigateTo(NavigationViewNames.Search)); RemoveTab = new ExecuteCommand <int>(DoRemoveTab); RemoveTabs = new ExecuteCommand(DoRemoveTabs); PinTabToStart = new ExecuteCommand <int>(DoPinTabToStart); GoToGroup = new ExecuteCommand <object>(DoGoToGroup); GoToTabView = new ExecuteCommand <object>(DoGoToTabView); SetIsSelectionEnabled = new ExecuteCommand <object>(DoSetIsSelectionEnabled); SetSelectedItems = new ExecuteCommand <object>(DoSetSelectedItems); RefreshData = new ExecuteCommand(DoRefreshData); RefreshHistory = new ExecuteCommand(DoRefreshHistroy); }
public bool CanExecute(ExecuteCommand command) { bool result = false; _lock.Wait(); if (command != null && !string.IsNullOrEmpty(command.CommandId)) { var deviceCommand = command.Command; if (!_cache.ContainsKey(command.CommandId)) { _cache.Add(command.CommandId, new List <ExecuteCommandCacheEntry> { new ExecuteCommandCacheEntry(deviceCommand) }); result = true; } else { var entryList = _cache[command.CommandId]; if (entryList != null && deviceCommand != null) { result = true; foreach (var entry in entryList) { if (entry.Status == deviceCommand.Status) { result = false; break; } } } } Cleanup(); } _lock.Release(); if (!result) { MsgLogger.WriteLine($"drop command"); } return(result); }
public ActionResult Index2() { ExecuteCommand ex = new ExecuteCommand(); Random rand = new Random(); var usercount = ex.UserCount(); var user = ex.UserBilgi(rand.Next(1, 20)); ViewModel vm = new ViewModel(); vm.sqlFonksyonKisiSayisi = usercount; vm.procedureGetUserInfo = user; return(View(vm)); }
public async Task Initialize() { HttpClientGetStringSucceeds = true; var factory = new FakeHttpClientFactory(() => HttpClientGetStringSucceeds); WakekApplication = new WakekTestApplication(factory); await WakekApplication.SetBenchmarkDefinitionsAsync(); ExecuteCommand = new ExecuteCommand(WakekApplication, Container.Resolve <IBenchmarkExecutionFactory>(), Container.Resolve <IXmlSerializer>(), Container.Resolve <ITelemetryDataReader>(), factory); var applicationCommandExecutionContextMock = new Mock <IApplicationCommandExecutionContext>(); applicationCommandExecutionContextMock.Setup(a => a.ReportAsync(It.IsAny <IFeedbackToApplication>())) .Returns <IFeedbackToApplication>(async f => await WakekApplication.HandleFeedbackToApplicationAsync(f)); ApplicationCommandExecutionContext = applicationCommandExecutionContextMock.Object; }
public async System.Threading.Tasks.Task InsertValues() { var query = "INSERT INTO TestTable (textField) VALUES ('unit test text')"; var output = new OutputProperties(); var input = new Input { ConnectionString = connectionString, CommandOrProcedureName = query, CommandType = OracleCommandType.Command, TimeoutSeconds = 60 }; var result = await ExecuteCommand.Execute(input, output, _taskOptions); Assert.AreEqual(true, result.Success); }
public async System.Threading.Tasks.Task CreateTable() { var query = "CREATE TABLE TestTable(textField VARCHAR(255))"; var output = new OutputProperties(); var input = new Input { ConnectionString = connectionString, CommandOrProcedureName = query, CommandType = OracleCommandType.Command, TimeoutSeconds = 60 }; var result = await ExecuteCommand.Execute(input, output, _taskOptions); Assert.AreEqual(true, result.Success); }
public async System.Threading.Tasks.Task GatAndUseRefCursorToJtoken() { // Replicate of test of https://docs.oracle.com/database/121/ODPNT/featRefCursor.htm#ODPNT319 ////////////////////////////////////////////////// /// Get refcursor var oracleParam = new OracleParametersForTask { DataType = OracleParametersForTask.ParameterDataType.RefCursor, Name = "outRefPrm", Value = DBNull.Value, Size = 0 }; var output = new OutputProperties { DataReturnType = OracleCommandReturnType.Parameters }; var input = new Input { ConnectionString = connectionString, CommandOrProcedureName = "begin open :1 for select col1 from test; end;", CommandType = OracleCommandType.Command, BindParametersByName = false, TimeoutSeconds = 60 }; output.OutputParameters = new OracleParametersForTask[1]; output.OutputParameters[0] = oracleParam; var result = await ExecuteCommand.Execute(input, output, _taskOptions); ////////////////////////////////////////////////// /// Ref cursor to JToken var secondInput = new RefCursorToJTokenInput { Refcursor = result.Result[0] }; var secondResult = ExecuteCommand.RefCursorToJToken(secondInput); StringAssert.Contains(@"[{""COL1"":1.0}]", JsonConvert.SerializeObject(secondResult.Result)); }
public object OpenStreamChannel(ConnectionBase connection, ExecuteCommand executeCommand, Type parameterType) { StreamContainer streamContainer = new StreamContainer(connection.Id, parameterType); Guid streamId = Guid.NewGuid(); streamContainers.TryAdd(streamId, streamContainer); _ = connection.Send(new InitStreamResponse() { ReferenceId = executeCommand.ReferenceId, Id = streamId }); CloseOldStreamChannels(); return(streamContainer.AsyncEnumerableValue); }
public async Task <ActionResult <CommandLogDto> > PostExeuteCommand(ExecuteCommandReadDto commandDto, [FromServices] IApiCalls apiCalls) { ExecuteCommand command = _mapper.Map <ExecuteCommandReadDto, ExecuteCommand>(commandDto); if (command == null) { return(BadRequest()); } switch (command.Command) { case "update": return(await UpdateDb(apiCalls)); default: return(BadRequest()); } }
public override Command[] Process() { var command = _command; Account account = (Account)AccountRepository.Default.Get(command.AccountId); Transaction tran = (Transaction)account.GetTran(command.TransactionId); ExecuteCommand executeCommand = new ExecuteCommand(); executeCommand.AccountID = command.AccountId; executeCommand.InstrumentID = command.InstrumentId; executeCommand.TranID = command.TransactionId; XmlDocument xmlDoc = new XmlDocument(); XmlElement content = xmlDoc.CreateElement("Content"); executeCommand.Content = content; content.AppendChild(xmlDoc.ImportNode(account.ToXmlNode(), true)); content.AppendChild(xmlDoc.ImportNode(tran.GetExecuteXmlElement(), true)); return(new Command[] { executeCommand }); }
public ConcordionBuilder() { BuildListeners = new List <IConcordionBuildListener>(); SpecificationProcessingListeners = new List <ISpecificationProcessingListener>(); ResourceToCopyMap = new Dictionary <string, Resource>(); ExceptionListeners = new List <IExceptionCaughtListener>(); SpecificationLocator = new ClassNameBasedSpecificationLocator(); Source = null; Target = null; CommandRegistry = new CommandRegistry(); DocumentParser = new DocumentParser(CommandRegistry); EvaluatorFactory = new SimpleEvaluatorFactory(); SpecificationCommand = new SpecificationCommand(); AssertEqualsCommand = new AssertEqualsCommand(); AssertTrueCommand = new AssertTrueCommand(); AssertFalseCommand = new AssertFalseCommand(); ExecuteCommand = new ExecuteCommand(); RunCommand = new RunCommand(); VerifyRowsCommand = new VerifyRowsCommand(); EchoCommand = new EchoCommand(); ExceptionRenderer = new ExceptionRenderer(); WithExceptionListener(ExceptionRenderer); // Set up the commands CommandRegistry.Register("", "specification", SpecificationCommand); // Wire up the command listeners var assertResultRenderer = new AssertResultRenderer(); WithAssertEqualsListener(assertResultRenderer); WithAssertTrueListener(assertResultRenderer); WithAssertFalseListener(assertResultRenderer); WithVerifyRowsListener(new VerifyRowResultRenderer()); WithRunListener(new RunResultRenderer()); WithDocumentParsingListener(new DocumentStructureImprover()); WithDocumentParsingListener(new MetadataCreator()); WithEmbeddedCss(HtmlFramework.EMBEDDED_STYLESHEET_RESOURCE); }
/// <summary> /// 将指定的执行命令转换成完整字符串形式。 /// </summary> /// <param name="command">执行命令。</param> /// <returns>完整执行命令的字符串形式。</returns> public static string ToFullString(this ExecuteCommand command) { if (command == null) { throw new ArgumentNullException(nameof(command)); } StringBuilder builder = new StringBuilder(command.Text); if (command.Parameters != null) { builder.AppendLine(); builder.AppendLine("*** Parameters ***"); foreach (var item in command.Parameters) { builder.AppendFormat("{0}\t=\t{1}\r\n", item.Name + (item.Value == null ? string.Empty : " <" + item.Value.GetType().Name + ">"), (item.Value == null || Convert.IsDBNull(item.Value)) ? "<NULL>" : item.Value); } builder.AppendLine("*** Parameters ***"); } return(builder.ToString()); }
public static bool IsValid(this ExecuteCommand command) { bool result = false; if (command != null) { if (!string.IsNullOrEmpty(command.CommandId)) { if (!string.IsNullOrEmpty(command.SourceChannelId)) { if (command.Command != null) { result = true; } } } } return(result); }
private List <ExecuteCommand> CreateUpdateTransactions() { List <ExecuteCommand> commands = new List <ExecuteCommand>(); var objectsToUpdate = objectsAll.Where(x => x.Status == ObjectStatus.Modified); if (objectsToUpdate.Any()) { foreach (var obj in objectsToUpdate) { ExecuteCommand command = new ExecuteCommand(ExecuteCommand.CommandType.Update); command.TableName = obj.TableObject.TableName; command.ObjectsIdentifiers.Add(obj.TableObject.PrimaryKey); command.Objects = CreateDiffrentsDictionary(obj, true); if (obj.TableObject.Inheritance == InheritanceType.ClassTable) { List <ExecuteCommand> tmpCommands = new List <ExecuteCommand>(); WPOTableObject tableObj = obj.TableObject; while (tableObj.BaseTable != null) { ExecuteCommand baseTypeCommand = new ExecuteCommand(ExecuteCommand.CommandType.Update); baseTypeCommand.TableName = tableObj.BaseTable.TableName; baseTypeCommand.ObjectsIdentifiers.Add(tableObj.BaseTable.PrimaryKey); baseTypeCommand.ObjectsIdentifiers.First().Value = obj.TableObject.PrimaryKey.Value; baseTypeCommand.Objects = CreateDiffrentsDictionary(obj, true, tableObj.BaseTable.WPOObject.GetType().Name); tmpCommands.Add(baseTypeCommand); tableObj = tableObj.BaseTable; } tmpCommands.Reverse(); commands.AddRange(tmpCommands); } commands.Add(command); } } return(commands); }
public async Task <string> ExecuteAsync(string sessionId, Stream assemblyStream, bool includePerformance, CancellationToken cancellationToken) { var startMarker = Guid.NewGuid(); var endMarker = Guid.NewGuid(); var executeCommand = new ExecuteCommand( ((MemoryStream)assemblyStream).ToArray(), startMarker, endMarker, includePerformance ); var stdin = new MemoryStream(); Serializer.SerializeWithLengthPrefix(stdin, executeCommand, PrefixStyle.Base128); stdin.Seek(0, SeekOrigin.Begin); var stdout = new MemoryStream(); var savedConsoleOut = Console.Out; Console.SetOut(new StreamWriter(stdout) { AutoFlush = true }); try { Program.Run(stdin, stdout); } finally { Console.SetOut(savedConsoleOut); } stdout.Seek(0, SeekOrigin.Begin); var stdoutReader = new StdoutReader(); var outputResult = await stdoutReader.ReadOutputAsync( new MultiplexedStream(stdout, multiplexed : false), new byte[stdout.Length], Encoding.UTF8.GetBytes(startMarker.ToString()), Encoding.UTF8.GetBytes(endMarker.ToString()), cancellationToken ); return(Encoding.UTF8.GetString(outputResult.Output.Span)); }
private void _compileCoub(CoubInfo coubInfo) { if (File.Exists(Path.Combine(coubInfo.Path, "Coub.mp4"))) { Console.WriteLine($"Coub {coubInfo.Permalink} is alredy exist"); return; } ExecuteCommand executeCommand = new ExecuteCommand(); Console.WriteLine($"Compiling coub {coubInfo.Permalink}"); string command; if (File.Exists(Path.Combine(coubInfo.Path, "Audio.mp3"))) { command = $"cd {coubInfo.Path} && ffmpeg -i Video.mp4 -t {coubInfo.Duration.ToString("0.0", CultureInfo.InvariantCulture)} -lavfi \"split [original][copy];[original]scale=w=-1:h=1080:-1:flags=neighbor+bitexact+accurate_rnd+full_chroma_int+full_chroma_inp+print_info,setsar=1:1[ov];[copy]scale=w=1920+1000*iw/ih:h=ih*1920/iw+1000*ih/iw" + $":flags=neighbor+bitexact+accurate_rnd+full_chroma_int+full_chroma_inp+print_info,setsar=1:1,boxblur=luma_radius=min(h\\,w)/20:luma_power=1:chroma_radius=min(cw\\,ch)/20:chroma_power=1[blur];[blur][ov]overlay=(W-w)/2:(H-h)/2,crop=w=1920:h=1080\" " + $"-i Audio.mp3 -map 0:v -map 1:a -c:a copy Coub.mp4 -y"; executeCommand.Execute(command); } }
public LwsViewModel() { model = new LwsModel(); Output = model.Output.ToReadOnlyReactiveCollection(); EnchantGroupList.AddRange(Const.EnchantmentList.Select(item => item.Name)); ExecuteCommand.Subscribe(_ => Execute()); ExitCommand.Subscribe(_ => Exit()); SelectedGroupIndex.Subscribe(_ => { EnchantNameList.Clear(); EnchantNameList.AddRange(GetEnchantNameList().Select(i => i.Name)); SelectedNameIndex.Value = 0; }); Disposable.Add(Output); Disposable.Add(ExecuteCommand); Disposable.Add(ExitCommand); }
private static ExecuteCommand WaitForCommandFromQueue(string[] queues) { if (NeedsReset(connection)) { if (connection != null) { connection.Dispose(); } connection = GetOpenConnection(); } var message = connection.Lists.BlockingRemoveFirst(0, queues, DefaultTimeout); if (message.Result != null) { return(ExecuteCommand.Deserialize(message.Result.Item2)); } return(null); }
public TCPServer(int port, ExecuteCommand executeCommand) { this.sessions = new ArrayList(); this.sessionThreads = new ArrayList(); this.executeCommand = executeCommand; Console.WriteLine("initializing TCP server..."); Console.WriteLine("creating listener..."); this.listener = new TcpListener(port); Console.WriteLine("starting listener..."); this.listener.Start(); this.open = true; this.server = new Thread(new ThreadStart(Run)); this.server.Start(); Console.WriteLine("TCP server initialization complete, port=" + port); }
public async System.Threading.Tasks.Task CreateProcedure() { var query = @" CREATE PROCEDURE UnitTestProc (returnVal OUT VARCHAR2) AS BEGIN SELECT TEXTFIELD INTO returnVal FROM TESTTABLE WHERE ROWNUM = 1; END;"; var output = new OutputProperties(); var input = new Input { ConnectionString = connectionString, CommandOrProcedureName = query, CommandType = OracleCommandType.Command, TimeoutSeconds = 60 }; var result = await ExecuteCommand.Execute(input, output, _taskOptions); Assert.AreEqual(true, result.Success); }
public AsyncCommandQueue(object sync) { userSync = sync; if (userSync == null) { execCommand = delegate (ICommand command) { command.Execute (); }; } else { execCommand = delegate (ICommand command) { lock (userSync) { command.Execute (); } }; } eventQueue = new Queue<ICommand> (); registeredHandle = ThreadPool.RegisterWaitForSingleObject ( are, ProcessEventQueue, null, -1, false ); }
private List <ExecuteCommand> CreateDeleteTransactions() { List <ExecuteCommand> commands = new List <ExecuteCommand>(); var existsObjectsIds = objectsFromDatabase.Select(o => o.GetIdentityKey()); var objectsToDelete = objectsAll.Where(x => x.Status == ObjectStatus.Deleted && existsObjectsIds.Contains(x.GetIdentityKey())).ToList(); if (objectsToDelete.Any()) { //Group objects by types - it allows to improve perfmormance foreach (var objGroup in objectsToDelete.GroupBy(x => x.GetType())) { ExecuteCommand command = new ExecuteCommand(ExecuteCommand.CommandType.Delete); command.TableName = objGroup.First().GetTableName(); command.ObjectsIdentifiers.AddRange(objGroup.Select(x => x.GetPrimaryKey())); commands.Add(command); } } return(commands); }
/// <summary> /// Метод извлекает из конфига добавочные параметры для запуска EEGStudio /// </summary> private string TryToGetAdditionalParam(ExecuteCommand command) { string result = String.Empty; switch (command) { case ExecuteCommand.New: result = TryToGetParamFromAppSettingsByName("NewExamParams"); break; case ExecuteCommand.Resume: result = TryToGetParamFromAppSettingsByName("ResumeExamParams"); break; case ExecuteCommand.Open: result = TryToGetParamFromAppSettingsByName("OpenExamParams"); break; default: result = string.Empty; break; } return result; }
/// <summary> /// Метод запускает процесс EEGStudio по команде контроллера БД RunDynamicModuleController /// </summary> /// <param name="command">Команда контроллера</param> /// <param name="examinationContext">Идентификатор обследования</param> /// <param name="fileName">Имя файла</param> /// <param name="arguments">Дополнительные параметры: PatientData,..</param> public void Execute(ExecuteCommand command, Guid examinationContext, string fileName, params object[] arguments) { switch (command) { case ExecuteCommand.New: //Создаем новое обследование в модуле ввода if (arguments.Length > 0) { if (EEGStudioModuleMode == EEG_STUDIO_MODE.ONLY_PROCESS) throw new Exception("Module Mode Error!"); PatientData patientData = arguments[0] as PatientData; ExcuteCommand(eegStudioItems.FirstOrDefault(item => item.Mode == EEG_STUDIO_INPUT), examinationContext, fileName, true, TryToGetAdditionalParam(command), patientData); } break; case ExecuteCommand.Resume: { // Открываем существующий файл в модуле ввода if (EEGStudioModuleMode == EEG_STUDIO_MODE.ONLY_ACQUISITION || EEGStudioModuleMode == EEG_STUDIO_MODE.BOTH_MODULE) ExcuteCommand(eegStudioItems.FirstOrDefault(item => item.Mode == EEG_STUDIO_INPUT), examinationContext, fileName, false, TryToGetAdditionalParam(command)); else ExcuteCommand(eegStudioItems.FirstOrDefault(item => item.Mode == EEG_STUDIO_PROC), examinationContext, fileName, false, TryToGetAdditionalParam(command)); break; } case ExecuteCommand.Open: // Открываем существующий файл в модуле анализа { // Открываем существующий файл в модуле анализа if (EEGStudioModuleMode == EEG_STUDIO_MODE.ONLY_PROCESS || EEGStudioModuleMode == EEG_STUDIO_MODE.BOTH_MODULE) ExcuteCommand(eegStudioItems.FirstOrDefault(item => item.Mode == EEG_STUDIO_PROC), examinationContext, fileName, false, TryToGetAdditionalParam(command)); else ExcuteCommand(eegStudioItems.FirstOrDefault(item => item.Mode == EEG_STUDIO_INPUT), examinationContext, fileName, false, TryToGetAdditionalParam(command)); break; } case ExecuteCommand.Break: // Останваливаем запущенный процесс !!! НЕ РАБОТАЕТ !!! TryToClosingInputProcess(); TryToClosingProcProcess(); break; default: break; } }
public static TypedValue Make(ExecuteCommand command, TypedValue target) { return new TypedValue(new ExecuteContext(command, target)); }
public static TypedValue Make(ExecuteCommand command, object systemUnderTest, TypedValue target) { return new TypedValue(new ExecuteContext(command, systemUnderTest, target)); }
public ExecuteContext(ExecuteCommand command, object systemUnderTest, TypedValue target) { SystemUnderTest = new TypedValue(systemUnderTest); Target = target; Command = command; }
public ExecuteContext(ExecuteCommand command, TypedValue target) { Command = command; Target = target; }
/// <summary> /// Метод обрабатывает команды контроллеров БД /// </summary> /// <param name="moduleExchange">Ссылака на модуль обмена</param> /// <param name="examinationContext">Идентификатор обследования</param> /// <param name="executeCommand">Команда контроллера</param> /// <param name="arguments">Объекты параметры</param> public void Execute(ExecuteCommand command, Guid examinationContext, string fileName, params object[] arguments) { switch (command) { case ExecuteCommand.New: { if (arguments.Length > 0) { PatientData patientData = arguments[0] as PatientData; ExcuteCommand(eegSynapseExecPath, examinationContext, fileName, true, TryToGetAdditionalParam(command), patientData); } break; } case ExecuteCommand.Resume: case ExecuteCommand.Open: { ExcuteCommand(eegSynapseExecPath, examinationContext, fileName, false, TryToGetAdditionalParam(command)); } break; case ExecuteCommand.Break: //... break; default: //... break; } }
/// <summary> /// Проверяем готовность модуля /// </summary> private bool ModuleIsReady(IDynamicModule module, Guid id, ExecuteCommand command) { bool result = true; try { result = ModuleIsReadyDoVerb(module, id, command); } catch (Exception ex) { //string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string message = ex.Message; string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); result = false; } return result; }
/// <summary> /// Метод открывает существующий в БД файл обследования /// </summary> internal void ExistExaminationExecute(ExecuteCommand command, bool blocking = false) { // Получаем текущее предстваление DevExpress.ExpressApp.View view = GetCurrentView(); IObjectSpace os = view.ObjectSpace; // Проверяем сохранены ли данные на форме if (os.IsModified == true) os.CommitChanges(); IExamination examination = view.CurrentObject as IExamination; if (examination == null) new Exception("The examination is not found in the database."); if (examination.IsBusy == true) { // Если обследование уже открыто string message = CaptionHelper.GetLocalizedText("Warnings", "RequiredExaminationIsAlreadyLaunched"); XtraMessageBox.Show(message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } // Находим модуль который должен обрабатывать данное обследование IDynamicModule module = WindowsFormsModule.DynamicModuleManager. GetModuleByAssociationAttributeID("ExaminationType", examination.ExaminationSoftType.ExaminationSoftTypeId); if (module == null) throw new Exception("An error occurred while getting IDynamicModule object."); ExecuteModule(module, command, os, examination); // Блокируем доступ в БД если надо if (blocking == true) { WindowsFormsModule owner = Application.Modules.FirstOrDefault(form => form is WindowsFormsModule) as WindowsFormsModule; //owner.BlockingAccessToDatabase(module, context); } }
internal Command(IDataContainer data, CalcTargetObjects calcTargetObjs, ExecuteCommand execCommand) : base (data) { _calcTargetObjects = calcTargetObjs; _executeCommand = execCommand; }
/// <summary> /// Запускаем выполнение модуля /// </summary> private bool TryToExecuteModule(IDynamicModule module, ExecuteCommand command, string file, Guid context, PatientData patient = null) { bool result = true; try { module.Execute(command, context, file, patient); } catch (Exception) { result = false; } return result; }
private void UpdateValues(double x) { _contentTransform.X = x; if (_leftRoot.Clip != null) ((TranslateTransform)_leftRoot.Clip.Transform).X = Math.Min(x - ActualWidth, 0D); if (_rightRoot.Clip != null) ((TranslateTransform)_rightRoot.Clip.Transform).X = Math.Max(ActualWidth + x, 0D); if (x > ActualWidth * ExecuteThreshold) { _leftActionTransform.X = 15D; _executeCommand = ExecuteCommand.Left; } else { if (x < ActualWidth * -ExecuteThreshold) { _rightActionTransform.X = -15D; _executeCommand = ExecuteCommand.Right; } else { _leftActionTransform.X = x * ExecuteThreshold; _rightActionTransform.X = x * ExecuteThreshold; _executeCommand = ExecuteCommand.None; } } }
public void Execute(ExecuteCommand command, Guid context, String verb, params object[] args) { }
private static Message Convert(string exchangeCode, ExecuteCommand executeCommand) { XmlNode transactionNode = executeCommand.Content["Transaction"]; Transaction[] transactions; Order[] orders; OrderRelation[] orderRelations; //Not Need AccountNode CommandConvertor.Parse(exchangeCode,transactionNode, out transactions, out orders, out orderRelations); ExecuteMessage executeMessage = new ExecuteMessage(exchangeCode, transactions, orders, orderRelations); return executeMessage; }
//(/*IModuleExchange parent,*/ Guid context, String verb, params object[] args) public void Execute(ExecuteCommand command, Guid context, String file, params object[] args) { //IModuleExchange parent = moduleExchange; //IExamination examination = args[0] as IExamination; //RegistryKey key = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, ""); //RegistryKey target_key = key.OpenSubKey(@"Software\Mitsar\Path"); //switch (command) //{ // case ExecuteCommand.Break://"BreakExamination": // parent.ProcessMessage(context, "Terminate"); // if (activeProcess.ContainsKey(context)) // { // Process process = activeProcess[context]; // activeProcess.Remove(context); // process.Kill(); // } // break; // case ExecuteCommand.New://"NewExamination": // parent.WriteLog("Запуск приборного ПО."); // //WinEEG // if (examination.ExaminationSoftType.ExaminationSoftTypeId == new Guid(SYS_CONST.SX_EXAMINATION_TYPE_EEG_WINEEG)) // { // if (target_key != null ? target_key.GetValueNames().Contains("EegEvokedPath") : false) // { // String fileName = String.Format("{0}{1}.eeg", Convert.ToString(target_key.GetValue("EegEvokedPath")), examination.ObjectCode.Replace('/', '_')); // String patientDataFileName = Convert.ToString(target_key.GetValue("EegEvokedPath")) + "PatData.dat"; // PatientDataExtractorMEF.WritePatienData(examination, patientDataFileName, fileName); // String path = Convert.ToString(target_key.GetValue("EegEvokedPath")) + "WINEEG.exe"; // Process process = new Process(); // ProcessStartInfo ps = new ProcessStartInfo(path); // process.StartInfo = ps; // ps.Arguments = "-new"; // activeProcess.Add(context, process); // process.EnableRaisingEvents = true; // process.Exited += (object sender, System.EventArgs e) => // { // //если процесс еще не вычищен - закрываем обследование // if (activeProcess.ContainsKey(context)) // { // activeProcess.Remove(context); // try // { // if (File.Exists(fileName)) // { // using (Stream fs = new FileStream(fileName, FileMode.Open)) // { // parent.TransferData(context, "application/examination_data", fs); // } // File.Delete(fileName); // File.Delete(patientDataFileName); // } // parent.ProcessMessage(context, "Stop"); // parent.WriteLog("Завершение работы ПО"); // } // catch // { // } // } // }; // process.Start(); // } // else // { // parent.WriteLog("Не найдено приборное ПО!"); // throw new Exception("Software not found"); // } // } // //Synapse // if (examination.ExaminationSoftType.ExaminationSoftTypeId == new Guid(SYS_CONST.SX_EXAMINATION_TYPE_EEG_2000)) // { // if (target_key != null ? target_key.GetValueNames().Contains("MainEegPath") : false) // { // String fileName = String.Format("{0}{1}.mef", Convert.ToString(target_key.GetValue("MainEegPath")), examination.ObjectCode.Replace('/', '_')); // String patientDataFileName = Convert.ToString(target_key.GetValue("MainEegPath")) + "PatData.dat"; // PatientDataExtractorMEF.WritePatienData(examination, patientDataFileName, fileName); // String path = Convert.ToString(target_key.GetValue("MainEegPath")) + "eeg.exe"; // Process process = new Process(); // ProcessStartInfo ps = new ProcessStartInfo(path); // process.StartInfo = ps; // ps.Arguments = "-new -sim50"; // activeProcess.Add(context, process); // process.EnableRaisingEvents = true; // process.Exited += (object sender, System.EventArgs e) => // { // //если процесс еще не вычищен - закрываем обследование // if (activeProcess.ContainsKey(context)) // { // activeProcess.Remove(context); // try // { // if (File.Exists(fileName)) // { // using (Stream fs = new FileStream(fileName, FileMode.Open)) // { // parent.TransferData(context, "application/examination_data", fs); // } // File.Delete(fileName); // File.Delete(patientDataFileName); // } // parent.ProcessMessage(context, "Stop"); // parent.WriteLog("Завершение работы ПО"); // } // catch // { // } // } // }; // process.Start(); // } // else // { // parent.WriteLog("Не найдено приборное ПО!"); // throw new Exception("Software not found"); // } // } // break; // case ExecuteCommand.Resume://"ResumeExamination": // parent.WriteLog("Запуск приборного ПО."); // //WinEEG // //if (examination.ExaminationSoftType.ExaminationSoftTypeId == new Guid(SYS_ENUMS.SX_EXAMINATION_TYPE_EEG_WINEEG)) // //{ // // if (target_key != null ? target_key.GetValueNames().Contains("EegEvokedPath") : false) // // { // // String fileName = String.Format("{0}{1}.eeg", Convert.ToString(target_key.GetValue("EegEvokedPath")), examination.ObjectCode.Replace('/', '_')); // // String patientDataFileName = Convert.ToString(target_key.GetValue("EegEvokedPath")) + "PatData.dat"; // // WritePatienData(examination, patientDataFileName, fileName); // // String path = Convert.ToString(target_key.GetValue("EegEvokedPath")) + "WINEEG.exe"; // // Process process = new Process(); // // ProcessStartInfo ps = new ProcessStartInfo(path); // // process.StartInfo = ps; // // ps.Arguments = string.Empty/*"-new -mdbs -SIME52"*/; // // activeProcess.Add(context, process); // // process.EnableRaisingEvents = true; // // process.Exited += (object sender, System.EventArgs e) => // // { // // //если процесс еще не вычищен - закрываем обследование // // if (activeProcess.ContainsKey(context)) // // { // // activeProcess.Remove(context); // // try // // { // // if (File.Exists(fileName)) // // { // // using (Stream fs = new FileStream(fileName, FileMode.Open)) // // { // // parent.TransferData(context, "application/examination_data", fs); // // } // // File.Delete(fileName); // // File.Delete(patientDataFileName); // // } // // parent.ProcessMessage(context, "Stop"); // // parent.WriteLog("Завершение работы ПО"); // // } // // catch // // { // // } // // } // // }; // // process.Start(); // // } // // else // // { // // parent.WriteLog("Не найдено приборное ПО!"); // // throw new Exception("Software not found"); // // } // //} // //Synapse // if (examination.ExaminationSoftType.ExaminationSoftTypeId == new Guid(SYS_CONST.SX_EXAMINATION_TYPE_EEG_2000)) // { // if (target_key != null ? target_key.GetValueNames().Contains("MainEegPath") : false) // { // //String fileName = String.Format("{0}{1}.mef", Convert.ToString(target_key.GetValue("MainEegPath")), examination.ObjectCode.Replace('/', '_')); // String fileName = examination.ExaminationFile.RealFileName; // String patientDataFileName = Convert.ToString(target_key.GetValue("MainEegPath")) + "PatData.dat"; // PatientDataExtractorMEF.WritePatienData(examination, patientDataFileName, fileName); // String path = Convert.ToString(target_key.GetValue("MainEegPath")) + "eeg.exe"; // Process process = new Process(); // ProcessStartInfo ps = new ProcessStartInfo(path); // process.StartInfo = ps; // ps.Arguments = string.Format("{0} " + "-sim50", fileName); // activeProcess.Add(context, process); // process.EnableRaisingEvents = true; // process.Exited += (object sender, System.EventArgs e) => // { // //если процесс еще не вычищен - закрываем обследование // if (activeProcess.ContainsKey(context)) // { // activeProcess.Remove(context); // try // { // //if (File.Exists(fileName)) // //{ // // using (Stream fs = new FileStream(fileName, FileMode.Open)) // // { // // parent.TransferData(context, "application/examination_data", fs); // // } // // File.Delete(fileName); // // File.Delete(patientDataFileName); // //} // parent.ProcessMessage(context, "Stop"); // parent.WriteLog("Завершение работы ПО"); // } // catch // { // } // } // }; // process.Start(); // } // else // { // parent.WriteLog("Не найдено приборное ПО!"); // throw new Exception("Software not found"); // } // } // break; // case ExecuteCommand.Open://"OpenExamination": // IFileData fileData = args.Length > 0 ? args[0] as IFileData : null; // Guid id = ((DevExpress.Persistent.BaseImpl.BaseObject)fileData).Oid; // XafApplication app = (XafApplication)args[1]; // if (fileData != null) // { // OpenFile(parent, fileData, id, app); // } // break; // default: // break; //} }
private void ExecuteModule(IDynamicModule module, ExecuteCommand command, IObjectSpace os, IExamination examination) { // Определяем идентификатор приложения которое будет открывать файл обследования // Для модулей которые могут работать с несколькими приложениями Guid soft = examination.ExaminationSoftType.ExaminationSoftTypeId; // Получаем имя РЕАЛЬНОГО файла обследования из базы !!! string file = examination.ExaminationFile.RealFileName; Guid context = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid; if (System.IO.File.Exists(file) == true) {// если файл удалось найти в том месте, где он должен быть if (FileWatcher.GetFileState(file) == FileState.Close) {// если файл никем не используется т.е закрыт if (new FileInfo(file).Length == 0) {// если файл обследования по какой то причине пустой, то открываем его как новый // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); if (TryToExecuteModule(module, ExecuteCommand.New, file, context, data) == false) {// если при запуске приложения возникла ошибка // удаляем обследование если его можно удалять if (examination.AllowEmptyOrNotExistsFile == false) os.Delete(examination); string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } else {// Если файл не пустой // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; if (TryToExecuteModule(module, command, file, context) == false) { string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } } else {// если файл в момент записи открыт где то еще string message = "Ошибка доступа к файлу обследования!\nВозможно файл открыт внешним приложением или нет прав доступа"; //CaptionHelper.GetLocalizedText("Warnings", "RequiredExaminationIsAlreadyLaunched"); XtraMessageBox.Show(message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } } else // АХТУНГ !!! НАДО УДАЛЯТЬ ОБСЛЕДОВАНИЯ СОДЕРЖАШИЕ УДАЛЕННЫЕ ФАЙЛЫ ИЛИ НЕ НАДО ?!!?!?!? {// если реального файла нет - создаем новый пустой файл using (Stream stream = File.Create(file)) { }; // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); TryToExecuteModule(module, ExecuteCommand.New, file, context, data); } os.Refresh(); }
private void ExecutedCommandBtn_Click(object sender, RoutedEventArgs e) { if (ExecuteIndex > 10) return; string xmlPath = string.Empty; ComboBoxItem item = (ComboBoxItem)this.OrderTypeComboBox.SelectedItem; string seletName = item.Content.ToString(); switch (seletName) { case "DQ": xmlPath = this.GetCommandXmlPath("AutoExecute_DQ"); break; case "LMT": xmlPath = this.GetCommandXmlPath("AutoExecute_DQ"); break; } XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); XmlNode xmlTran = doc.ChildNodes[1].ChildNodes[2 * ExecuteIndex]; XmlNode xmlAccount = doc.ChildNodes[1].ChildNodes[2 * ExecuteIndex + 1]; ExecuteCommand executeCommand; executeCommand = new ExecuteCommand(ExecuteIndex); executeCommand.InstrumentID = XmlConvert.ToGuid(xmlTran.Attributes["InstrumentID"].Value); executeCommand.AccountID = XmlConvert.ToGuid(xmlTran.Attributes["AccountID"].Value); XmlDocument xmlDoc = new XmlDocument(); XmlNode content = xmlDoc.CreateElement("Execute"); xmlDoc.AppendChild(content); executeCommand.Content = content; content.AppendChild(xmlDoc.ImportNode(xmlTran, true)); content.AppendChild(xmlDoc.ImportNode(xmlAccount, true)); ManagerClient.AddCommand(executeCommand); ExecuteIndex++; }
/// <summary> /// Метод проверяет готовность модуля к работе /// </summary> private bool ModuleIsReadyDoVerb(IDynamicModule module, Guid oid, ExecuteCommand command = ExecuteCommand.Null) { bool? result = module.DoVerb(VerboseCommand.CheckReady, command) as bool?; return result ?? false; }
public static bool IsMatch(ExecuteCommand command, InvokeCommandBase executor, Tree<Cell> parameters) { var processor = new CellProcessorBase(); processor.AddOperator(new ParseMemberName()); executor.Processor = processor; return executor.CanExecute(new ExecuteContext(command, new TypedValue("stuff")), new ExecuteParameters(parameters)); }
/// <summary> /// Execute an eve command. /// </summary> public bool Execute(ExecuteCommand command) { Tracing.SendCallback("EVE.Execute", command); return ExecuteMethod("Execute", command.ToString()); }