public async Task<ExecutionResult> ExecuteAsync(Schema schema, object root, string query, string operationName, Inputs inputs = null) { var document = _documentBuilder.Build(query); var result = new ExecutionResult(); var validationResult = _documentValidator.IsValid(schema, document, operationName); if (validationResult.IsValid) { var context = BuildExecutionContext(schema, root, document, operationName, inputs); if (context.Errors.Any()) { result.Errors = context.Errors; return result; } result.Data = await ExecuteOperation(context); result.Errors = context.Errors; } else { result.Data = null; result.Errors = validationResult.Errors; } return result; }
public ExecutionResult Process(object message, Type messageType) { var totalResult = new ExecutionResult(); IMessageConfiguration messageConfiguration = _configuration.GetMessageConfiguration(messageType); IEnumerable<ICommandConfiguration> commandConfigurations = messageConfiguration.GetApplicableCommands(message); foreach (ICommandConfiguration commandConfiguration in commandConfigurations) { object commandMessage = _mappingEngine.MapUiMessageToCommandMessage(message, messageType, commandConfiguration.CommandMessageType); commandConfiguration.Initialize(commandMessage, totalResult); ExecutionResult results = _commandInvoker.Process(commandMessage, commandConfiguration); totalResult.MergeWith(results); if (!totalResult.Successful) { _unitOfWork.Invalidate(); break; } } return totalResult; }
private InvocationResult(ExecutionResult result, TimeSpan? rescheduleIn, JobContinuation continuation, Exception exception) { Result = result; RescheduleIn = rescheduleIn; Continuation = continuation; Exception = exception; ConsistencyCheck(); }
public static ExecutionResult CompileAndRun(string code) { var result = new ExecutionResult(); var CompilerParams = new CompilerParameters { GenerateInMemory = true, TreatWarningsAsErrors = false, GenerateExecutable = false, CompilerOptions = "/optimize" }; string[] references = {"System.dll", "mscorlib.dll", "System.Core.dll"}; string[] externalReferences = { @"Autohaus.Data.dll", @"Sitecore.Kernel.dll", @"Sitecore.Buckets.dll", @"Sitecore.ContentSearch.dll", @"Sitecore.ContentSearch.Linq.dll" }; for (int i = 0; i < externalReferences.Length; i++) externalReferences[i] = Path.Combine(Path.GetDirectoryName(HttpContext.Current.Request.PhysicalApplicationPath + "bin\\"), externalReferences[i]); CompilerParams.ReferencedAssemblies.AddRange(externalReferences); CompilerParams.ReferencedAssemblies.AddRange(references); var provider = new CSharpCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, new[] {code}); if (compile.Errors.HasErrors) { result.Messages.AddRange(compile.Errors); return result; } Module module = compile.CompiledAssembly.GetModules()[0]; Type mt = null; MethodInfo methInfo = null; if (module != null) { mt = module.GetType("Autohaus.Web.Runner"); } if (mt != null) { methInfo = mt.GetMethod("Run"); } if (methInfo == null) return result; var stopwatch = new Stopwatch(); stopwatch.Start(); result.ResultSet = methInfo.Invoke(null, new object[0]) as IEnumerable<object>; stopwatch.Stop(); result.TimeTaken = stopwatch.ElapsedMilliseconds; return result; }
static List<ErrorMessage> Messages(ExecutionResult result) { return result.Messages.Select(msg => new ErrorMessage { InvalidProperty = msg.IncorrectAttribute, Message = msg.MessageText }) .ToList(); }
public void ResultTest() { var target = new ExecutionResult<String>(); var expected = RandomValueEx.GetRandomString(); target.Result = expected; target.Result.Should() .Be( expected ); }
public void ExceptionTest() { var target = new ExecutionResult<String>(); var expected = new NotImplementedException(); target.Exception = expected; target.Exception.Should() .BeSameAs( expected ); }
public void CtorTest() { var target = new ExecutionResult<String>(); target.Exception.Should() .BeNull(); target.Result.Should() .BeNull(); }
/// <summary> /// ctor /// </summary> /// <param name="order">Order for monitoring of execution</param> public OrderMonitor(O2GOrderRow order) { mOrder = order; mTrades = new List<O2GTradeRow>(); mClosedTrades = new List<O2GClosedTradeRow>(); mState = OrderState.OrderExecuting; mResult = ExecutionResult.Executing; mTotalAmount = 0; mRejectAmount = 0; mRejectMessage = ""; }
async Task<ExecutionResult> StartAsyncTask(bool debugMessages) { execresult = ExecutionResult.ERR_NO_ERRORS; var fileExt = fileIO.GetFileNames().Where(i => i.Contains(".")).Select(i => i.Substring(i.LastIndexOf("."))) .First(i => KnownExtensions.Contains(i.ToLower())); var fnames = fileIO.GetFileNames(); var story_name = fnames.First(i => i.ToLower().EndsWith(fileExt.ToLower())); if (story_name.Length == 0) { return await Task.FromResult(ExecutionResult.ERR_BADFILE); } var mem = new List<byte>(); var fd = fileIO.FOpen(story_name, "rb"); using (var strm = (await fileIO.GetStreamReaderAsync(fd)).AsStream()) { while (true) { var buffer = new byte[4096]; var countRead = strm.Read(buffer, 0, 4096); mem.AddRange(buffer); if (countRead <= 0) break; } } var fe = new Zmachine.FrontEnd(runtime); fe.LoadStory(new Zmachine.ImmutableArray<byte>(mem.ToArray())); //execresult = await game_begin(); //if (execresult != ExecutionResult.ERR_NO_ERRORS) // return execresult; fe.Zmachine.Restart(); //execresult = await game_restart(); //if (execresult != ExecutionResult.ERR_NO_ERRORS) // return execresult; for (;;) { await fe.Zmachine.Run(); if (!fe.Done) break; } return await Task.FromResult(execresult); }
public void ParseResult(IList<string> lines) { if (lines.Count > 0) { CurrentBranch = lines[0].Replace("On branch ", ""); ExecutionResult = ExecutionResult.Success; } else { ExecutionResult = ExecutionResult.NoRepository; } }
public static void MergeWith(this ModelStateDictionary modelStateDictionary, ExecutionResult executionResult) { if (executionResult == null) return; executionResult .Errors .Select(error => error.Value) .Each(msgGroup => msgGroup .Messages .Each(msg => modelStateDictionary.AddModelError(msgGroup.PropertyName, msg))); }
/// <summary> /// Merge all error found in an application message into the current validation dictionary /// </summary> /// <param name="validationDictionary">instance of IValidationDictionary</param> /// <param name="executionResult">instance of IApplicationMessage</param> /// <param name="fromMessageCategory">look for error messages from this category</param> /// <returns></returns> public static IValidationDictionary Merge(this IValidationDictionary validationDictionary, ExecutionResult executionResult, MessageCategory fromMessageCategory = MessageCategory.BrokenBusinessRule) { if ((validationDictionary != null) && (executionResult != null) && !executionResult.IsSuccessFull) { var propertyName = executionResult[fromMessageCategory].PropertyName; executionResult[fromMessageCategory] .Messages .Each(errorMessage => validationDictionary.AddError(propertyName, errorMessage)); } return validationDictionary; }
/// <summary> /// ctor /// </summary> /// <param name="order">Order for monitoring of execution</param> /// <param name="iNetPositionAmount">Initial amount of trade</param> public OrderMonitorNetting(O2GOrderRow order, int iNetPositionAmount) { mOrder = order; mTrades = new List<O2GTradeRow>(); mUpdatedTrades = new List<O2GTradeRow>(); mClosedTrades = new List<O2GClosedTradeRow>(); mState = OrderState.OrderExecuting; mResult = ExecutionResult.Executing; mInitialAmount = iNetPositionAmount; mTotalAmount = 0; mRejectAmount = 0; mRejectMessage = ""; }
public async Task<ExecutionResult> ExecuteAsync( ISchema schema, object root, string query, string operationName, Inputs inputs = null, CancellationToken cancellationToken = default(CancellationToken), IEnumerable<IValidationRule> rules = null) { var result = new ExecutionResult(); try { var document = _documentBuilder.Build(query); var validationResult = _documentValidator.Validate(query, schema, document, rules); if (validationResult.IsValid) { var context = BuildExecutionContext(schema, root, document, operationName, inputs, cancellationToken); if (context.Errors.Any()) { result.Errors = context.Errors; return result; } result.Data = await ExecuteOperationAsync(context).ConfigureAwait(false); if (context.Errors.Any()) { result.Errors = context.Errors; } } else { result.Data = null; result.Errors = validationResult.Errors; } return result; } catch (Exception exc) { if (result.Errors == null) { result.Errors = new ExecutionErrors(); } result.Data = null; result.Errors.Add(new ExecutionError(exc.Message, exc)); return result; } }
public static string GetVersion() { Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "diff3"; p.StartInfo.Arguments = "--version"; p.StartInfo.CreateNoWindow = true; p.Start(); p.WaitForExit(); ExecutionResult result = new ExecutionResult(p); Debug.WriteLine(result.StandardOutput); return result.StandardOutput; }
public static string GetRawMerge(string oursPath, string commonPath, string theirPath) { Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "diff3/bin/diff3.exe"; p.StartInfo.Arguments = "-m " + oursPath + " "+commonPath+" "+theirPath; p.StartInfo.CreateNoWindow = true; p.Start(); p.WaitForExit(); ExecutionResult result = new ExecutionResult(p); if (result.ExitCode == 2)//0 and 1 are ok { throw new ApplicationException("Got error "+result.ExitCode + " " +result.StandardOutput +" "+ result.StandardError); } Debug.WriteLine(result.StandardOutput); return result.StandardOutput; }
public static void MergeWith(this ModelStateDictionary modelStateDictionary, ExecutionResult executionResult) { if (executionResult == null) return; var messageGroups = executionResult .Errors .Select(e => e.Value); foreach (var messageGroup in messageGroups) { foreach (var propertyName in messageGroup.PropertyNames) { foreach (var errorMessage in messageGroup.Messages) { modelStateDictionary.AddModelError(propertyName,errorMessage); } } } }
public ExecutionResult AssertQuery( ISchema schema, string query, ExecutionResult expectedExecutionResult, Inputs inputs, object root, object userContext = null, CancellationToken cancellationToken = default(CancellationToken), IEnumerable<IValidationRule> rules = null) { var runResult = Executer.ExecuteAsync( schema, root, query, null, inputs, userContext, cancellationToken, rules ).Result; var writtenResult = Writer.Write(runResult); var expectedResult = Writer.Write(expectedExecutionResult); #if DEBUG Console.WriteLine(writtenResult); #endif string additionalInfo = null; if (runResult.Errors?.Any() == true) { additionalInfo = string.Join(Environment.NewLine, runResult.Errors .Where(x => x.InnerException is GraphQLSyntaxErrorException) .Select(x => x.InnerException.Message)); } writtenResult.ShouldBe(expectedResult, additionalInfo); return runResult; }
public override NodeTreeOutput Tick(out ExecutionResult executionResult, ExecutionResult childResult) { ((UnityEngine.Transform)refObject.GetValue()).parent = setter.GetValue(); executionResult = ExecutionResult.Success; return(null); }
public override ExecutionResult Run(IStepExecutionContext context) { Value2 = Value1 + 1; return(ExecutionResult.Next()); }
public async Task <ActionResult> _PaymentDetail(Payment model, IEnumerable <HttpPostedFileBase> files) { if (model.Is_Settlement) { if (ModelState.ContainsKey("Payee_Type")) { ModelState["Payee_Type"].Errors.Clear(); } if (ModelState.ContainsKey("Payee_Contact_Name")) { ModelState["Payee_Contact_Name"].Errors.Clear(); } if (ModelState.ContainsKey("Date_Invoice_Received")) { ModelState["Date_Invoice_Received"].Errors.Clear(); } if (ModelState.ContainsKey("Payee_Account_Name")) { ModelState["Payee_Account_Name"].Errors.Clear(); } } else { if (ModelState.ContainsKey("Payment_Amount")) { ModelState["Payment_Amount"].Errors.Clear(); } if (ModelState.ContainsKey("Payment_Date")) { ModelState["Payment_Date"].Errors.Clear(); } } if (ModelState.IsValid) { documentService = new DocumentService(); exeResult = new ExecutionResult(); if (Session[SessionHelper.PaymentAttachment] != null) { files = (IEnumerable <HttpPostedFileBase>)Session[SessionHelper.PaymentAttachment]; } ClaimTeamLoginModel client = (ClaimTeamLoginModel)Session[SessionHelper.claimTeamLogin]; if (model.Is_Settlement && model.Payment_Amount.HasValue) { model.Total_Gross = (decimal)model.Payment_Amount; model.Total_Net = (decimal)model.Payment_Amount; } // if (model.IsNew) // { exeResult = await documentService.CreatePaymentDetailRecord(model, client.UserId, files); //} //else //documentService.CreateFileNoteRecord(model.CreatedBy_Id_Fn, model.ShortDescription_Fn, model.Detail_Fn, model.ClaimId_Fn, model.FileNoteDate_Fn.Value); Session[SessionHelper.PaymentAttachment] = null; } return(Json("success", JsonRequestBehavior.AllowGet)); }
public async Task Transfer(string?memo, bool error) { NineChroniclesNodeService service = StandaloneContextFx.NineChroniclesNodeService !; Currency goldCurrency = new GoldCurrencyState( (Dictionary)BlockChain.GetState(GoldCurrencyState.Address) ).Currency; Address senderAddress = service.MinerPrivateKey !.ToAddress(); var store = service.Store; await BlockChain.MineBlock(service.MinerPrivateKey); await BlockChain.MineBlock(service.MinerPrivateKey); // 10 + 10 (mining rewards) Assert.Equal( 20 * goldCurrency, BlockChain.GetBalance(senderAddress, goldCurrency) ); var recipientKey = new PrivateKey(); Address recipient = recipientKey.ToAddress(); long txNonce = BlockChain.GetNextTxNonce(senderAddress); var args = $"recipient: \"{recipient}\", txNonce: {txNonce}, amount: \"17.5\""; if (!(memo is null)) { args += $"memo: \"{memo}\""; } var query = $"mutation {{ transfer({args}) }}"; ExecutionResult result = await ExecuteQueryAsync(query); if (error) { Assert.NotNull(result.Errors); } else { Assert.Null(result.Errors); var stagedTxIds = BlockChain.GetStagedTransactionIds().ToImmutableList(); Assert.Single(stagedTxIds); string transferTxIdString = stagedTxIds.Single().ToString(); TxId transferTxId = new TxId(ByteUtil.ParseHex(transferTxIdString)); Transaction <NCAction>?tx = BlockChain.StagePolicy.Get(BlockChain, transferTxId, false); Assert.NotNull(tx); Assert.IsType <TransferAsset>(tx !.Actions.Single().InnerAction); TransferAsset transferAsset = (TransferAsset)tx.Actions.Single().InnerAction; Assert.Equal(memo, transferAsset.Memo); var expectedResult = new Dictionary <string, object> { ["transfer"] = transferTxIdString, }; Assert.Equal(expectedResult, result.Data); await BlockChain.MineBlock(recipientKey); // 10 + 10 - 17.5(transfer) Assert.Equal( FungibleAssetValue.Parse(goldCurrency, "2.5"), BlockChain.GetBalance(senderAddress, goldCurrency) ); // 0 + 17.5(transfer) + 10(mining reward) Assert.Equal( FungibleAssetValue.Parse(goldCurrency, "27.5"), BlockChain.GetBalance(recipient, goldCurrency) ); } }
public override ExecutionResult Run(IStepExecutionContext context) { Console.WriteLine("Hello world"); return(ExecutionResult.Next()); }
async Task<ExecutionResult> execute_instruction() { execresult = ExecutionResult.ERR_NO_ERRORS; byte currentInstruction = memory[program_counter++]; ushort at; short m; short n; uint u = program_counter - 1; var nbuf = new byte[5]; int argc; instruction_use[currentInstruction] |= 0x01; if ((currentInstruction & 0x80) != 0) { if (currentInstruction >= 0xC0 || currentInstruction == 0xBE) { // variable if (currentInstruction == 0xBE) { currentInstruction = memory[program_counter++]; } at = (ushort)(memory[program_counter++] << 8); if (currentInstruction == 0xEC || currentInstruction == 0xFA) { at |= memory[program_counter++]; } else { at |= 0x00FF; } if ((at & 0xC000) == 0xC000) { argc = 0; } else if ((at & 0x3000) == 0x3000) { argc = 1; } else if ((at & 0x0C00) == 0x0C00) { argc = 2; } else if ((at & 0x0300) == 0x0300) { argc = 3; } else if ((at & 0x00C0) == 0x00C0) { argc = 4; } else if ((at & 0x0030) == 0x0030) { argc = 5; } else if ((at & 0x000C) == 0x000C) { argc = 6; } else if ((at & 0x0003) == 0x0003) { argc = 7; } else { argc = 8; } } else { // short at = (ushort)((currentInstruction << 10) | 0x3FFF); argc = (currentInstruction < 0xB0) ? 1 : 0; if (argc != 0) { currentInstruction &= 0x8F; } } } else { // long at = 0x5FFF; if ((currentInstruction & 0x20) != 0) { at ^= 0x3000; } if ((currentInstruction & 0x40) != 0) { at ^= 0xC000; } currentInstruction &= 0x1F; currentInstruction |= 0xC0; argc = 2; } if (break_on) { if (continuing == u || continuing == program_counter) { continuing = 0; } else { if (instruction_bkpt[currentInstruction] != 0) { program_counter = u; await debugger(); return execresult; } for (n = 0; n < 16; n++) { if (address_bkpt[n] == u) { program_counter = u; await debugger(); return execresult; } } } } for (n = 0; n < 8; n++) { switch ((at >> (14 - n * 2)) & 3) { case 0: // large inst_args[n] = (ushort)(memory[program_counter++] << 8); inst_args[n] |= memory[program_counter++]; break; case 1: // small inst_args[n] = memory[program_counter++]; break; case 2: // variable inst_args[n] = fetch(memory[program_counter++]); break; case 3: // omit inst_args[n] = 0; break; } } instruction_use[currentInstruction] |= (byte)(argc != 0 ? 0x04 : 0x02); lastdebug = false; switch (currentInstruction) { case 0x00: // Save game or auxiliary file if (argc != 0) { storei(aux_save()); } else { await game_save(memory[program_counter++]); } break; case 0x01: // Restore game or auxiliary file storei(argc != 0 && auxfile != null ? aux_restore() : 0); if (argc == 0) { await game_restore(); } break; case 0x02: // Logical shift if ((short) inst_args[1] > 0) { storei(inst_args[0] << inst_args[1]); } else { storei(inst_args[0] >> -inst_args[1]); } break; case 0x03: // Arithmetic shift if ((short) inst_args[1] > 0) { storei((short) inst_args[0] << (short) inst_args[1]); } else { storei((short) inst_args[0] >> -(short) inst_args[1]); } break; case 0x04: // Set font await text_flush(); if (execresult != ExecutionResult.ERR_NO_ERRORS) return execresult; storei((inst_args[inst_args_index] == 1 || inst_args[inst_args_index] == 4) ? 4 : 0); //if (opts['t'] == 0) //{ // Console.Write(inst_args == 3 ? 14 : 15); //} break; case 0x08: // Set margins if (!window ) { lmargin = inst_args[0]; rmargin = inst_args[1]; if (zmachineVersion == 5) { write16(40, inst_args[0]); } if (zmachineVersion == 5) { write16(41, inst_args[1]); } while (cur_column < (int)inst_args[0]) { runtime.Write(' '); //Console.Write(32); cur_column++; } } break; case 0x09: // Save undo buffer if (allow_undo) { //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(u_frames, frames, sizeof(StackFrame)); Array.Copy(u_frames, frames, 1); //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(u_stack, stack, sizeof(ushort)); Array.Copy(u_stack, stack, 1); //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(undomem, memory + 0x40, static_start - 0x40); Array.Copy(undomem, 0, memory, 0x40, (int)static_start - 0x40); u_frameptr = frameptr; u_stackptr = stackptr; u_program_counter = program_counter; storei(1); } else { storei(-1); } break; case 0x0A: // Restore undo buffer if (allow_undo) { //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(frames, u_frames, sizeof(StackFrame)); Array.Copy(frames, u_frames, 1); //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(stack, u_stack, sizeof(ushort)); Array.Copy(stack, u_stack, 1); //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(memory + 0x40, undomem, static_start - 0x40); Array.Copy(memory, 0x40, undomem, 0, (int) static_start - 0x40); frameptr = u_frameptr; stackptr = u_stackptr; program_counter = u_program_counter; storei((argc != 0 && zmachineVersion > 8) ? inst_args[0] : 2); } else { storei(-1); } break; case 0x0B: // Call byte address program_counter++; enter_routine(inst_args[inst_args_index], true, argc - 1); break; case 0x0C: // Get reference to stack or local variables if (inst_args != null) { storei(stackptr - 1); } else { storei(frames[(int)frameptr].start + inst_args[inst_args_index - 1]); } break; case 0x0D: // Read through stack/locals reference storei(stack[inst_args[inst_args_index]]); break; case 0x0E: // Write through stack/locals reference if (inst_args[inst_args_index] < 1024) { stack[inst_args[inst_args_index]] = inst_args[1]; } break; case 0x0F: // Read byte from long property u = property_address(inst_args[0], (byte)inst_args[1]); storei(memory[u]); break; case 0x1D: // Read word from long property u = property_address(inst_args[0], (byte) inst_args[1]); storei(read16((int)u)); break; case 0x80: // Jump if zero branch(inst_args[inst_args_index] == 0 ); break; case 0x81: // Sibling storei(sibling(inst_args[inst_args_index])); branch(sibling(inst_args[inst_args_index]) != 0); break; case 0x82: // Child storei(child(inst_args[inst_args_index])); branch(child(inst_args[inst_args_index]) != 0); break; case 0x83: // Parent storei(parent(inst_args[inst_args_index])); break; case 0x84: // Property length currentInstruction = memory[inst_args[inst_args_index] - 1]; storei(zmachineVersion < 4 ? (currentInstruction >> 5) + 1: ( (currentInstruction & 0x80) != 0 ? ( (currentInstruction & 63) == 0 ? 64 : ((currentInstruction >> 6) +1) ) : ((currentInstruction >> 6) + 1) ) ); break; case 0x85: // Increment store((byte) inst_args[inst_args_index], (byte)(fetch((byte) inst_args[inst_args_index]) + 1)); break; case 0x86: // Decrement store((byte) inst_args[inst_args_index], (byte) fetch((byte) inst_args[inst_args_index]) - 1); break; case 0x87: // Print by byte address text_print(inst_args[inst_args_index]); break; case 0x88: // Call routine if (inst_args[inst_args_index] != 0) { program_counter++; enter_routine((uint)((inst_args[inst_args_index] << packed_shift) + routine_start), true, argc - 1); } else { storei(0); } break; case 0x89: // Remove object insert_object(inst_args[inst_args_index], 0); break; case 0x8A: // Print short name of object //text_print(obj_prop_addr((uint)(inst_args[inst_args_index] + 1))); text_print(Frotz.Generic.ZObject.object_name((ushort)(inst_args[inst_args_index] + 1))); break; case 0x8B: // Return exit_routine(inst_args[inst_args_index]); break; case 0x8C: // Unconditional jump program_counter += (uint)((short) inst_args[inst_args_index] - 2); break; case 0x8D: // Print by packed address text_print((uint)((inst_args[inst_args_index] << packed_shift) + text_start)); break; case 0x8E: // Load variable at = fetch((byte) inst_args[inst_args_index]); store((byte) inst_args[inst_args_index], at); // if it popped from the stack, please put it back on storei(at); break; case 0x8F: // Not // Call routine and discard result if (zmachineVersion > 4) { if (inst_args[inst_args_index] != 0) { enter_routine((uint) ((inst_args[inst_args_index] << packed_shift) + routine_start), false, argc - 1); } } else { storei(~inst_args[inst_args_index]); } break; case 0xB0: // Return 1 exit_routine(1); break; case 0xB1: // Return 0 exit_routine(0); break; case 0xB2: // Print literal program_counter = text_print(program_counter); break; case 0xB3: // Print literal and return program_counter = text_print(program_counter); char_print(13); exit_routine(1); break; case 0xB4: // No operation //NOP break; case 0xB5: // Save if (zmachineVersion > 3) { await game_save(memory[program_counter++]); } else { await game_save(0); } break; case 0xB6: // Restore if (zmachineVersion > 3) { storei(0); } else { branch(false); } await game_restore(); break; case 0xB7: // Restart game_restart(); break; case 0xB8: // Return from stack exit_routine((ushort) stack[stackptr - 1]); break; case 0xB9: // Discard from stack // Catch if (zmachineVersion > 4) { storei(frameptr); } else { stackptr--; } break; case 0xBA: // Quit await text_flush(); return await Task.FromResult(ExecutionResult.ERR_STATE_QUIT); break; case 0xBB: // Line break char_print(13); break; case 0xBC: // Show status //NOP break; case 0xBD: // Verify checksum branch(verify_checksum()); break; case 0xBF: // Check if game disc is original branch(original); break; case 0xC1: // Branch if equal for (n = 1; n < argc; n++) { if (inst_args[inst_args_index] == inst_args[n]) { branch(true); break; } } if (n == argc) { branch(false); } break; case 0xC2: // Jump if less branch((short) inst_args[0] < (short) inst_args[1]); break; case 0xC3: // Jump if greater branch((short) inst_args[0] > (short) inst_args[1]); break; case 0xC4: // Decrement and branch if less store((byte)inst_args[inst_args_index], n = (short)(fetch((byte)inst_args[inst_args_index]) - 1)); branch(n < (short) inst_args[1]); break; case 0xC5: // Increment and branch if greater store((byte)inst_args[inst_args_index], n = (short)(fetch((byte) inst_args[inst_args_index]) + 1)); branch(n > (short) inst_args[1]); break; case 0xC6: // Check if one object is the parent of the other branch(parent(inst_args[0]) == inst_args[1]); break; case 0xC7: // Test bitmap branch((inst_args[0] & inst_args[1]) == inst_args[1]); break; case 0xC8: // Bitwise OR storei(inst_args[0] | inst_args[1]); break; case 0xC9: // Bitwise AND storei(inst_args[0] & inst_args[1]); break; case 0xCA: // Test attributes branch( (memory[attribute(inst_args[inst_args_index]) + (inst_args[1] >> 3)] & (0x80 >> (inst_args[1] & 7))) != 0); break; case 0xCB: // Set attribute memory[(int)(attribute(inst_args[inst_args_index]) + (inst_args[1] >> 3))] |= (byte)(0x80 >> (inst_args[1] & 7)); break; case 0xCC: // Clear attribute memory[(int)(attribute(inst_args[inst_args_index]) + (inst_args[1] >> 3))] &= (byte)(~(0x80 >> (inst_args[1] & 7))); break; case 0xCD: // Store to variable fetch((byte) inst_args[0]); store((byte) inst_args[0], inst_args[1]); break; case 0xCE: // Insert object insert_object(inst_args[0], inst_args[1]); break; case 0xCF: // Read 16-bit number from RAM/ROM storei(read16(inst_args[0] + ((short) inst_args[1] << 1))); break; case 0xD0: // Read 8-bit number from RAM/ROM storei(memory[inst_args[0] + (short) inst_args[1]]); break; case 0xD1: // Read property if ((u = (uint) property_address(inst_args[0], (byte) inst_args[1])) != 0) { storei(cur_prop_size == 1 ? memory[u] : read16((int)u)); } else { storei(read16((int)(object_table + (inst_args[1] << 1) - 2))); } break; case 0xD2: // Get address of property storei((int) property_address(inst_args[0], (byte) inst_args[1])); break; case 0xD3: // Find next property if (inst_args[1] != 0) { u = property_address(inst_args[0], (byte) inst_args[1]); u += cur_prop_size; storei(memory[u] & (zmachineVersion > 8 && ((memory[u] & 128) != 0) ? 127 : zmachineVersion > 3 ? 63 : 31)); } else { u = (uint)obj_prop_addr((uint)inst_args[0]); u += (uint) ((memory[(int)u] << 1) + 1); storei(memory[u] & (zmachineVersion > 8 && ((memory[u] & 128) != 0) ? 127 : zmachineVersion > 3 ? 63 : 31)); } break; case 0xD4: // Addition storei((short) inst_args[0] + (short) inst_args[1]); break; case 0xD5: // Subtraction storei((short) inst_args[0] - (short) inst_args[1]); break; case 0xD6: // Multiplication storei((short) inst_args[0] * (short) inst_args[1]); break; case 0xD7: // Division if (inst_args[1] != 0) { n = (short)((short) inst_args[0] / (short) inst_args[1]); } else { runtime.Debug.LogError("\n*** Division by zero\n{0}\n", currentInstruction); } storei(n); break; case 0xD8: // Modulo if (inst_args[1] != 0) { n = (short) ((short) inst_args[0] % (short) inst_args[1]); } else { runtime.Debug.LogError("\n*** Division by zero\n{0}\n", currentInstruction); } storei(n); break; case 0xD9: // Call routine if (inst_args[inst_args_index] != 0) { program_counter++; enter_routine((uint)(inst_args[inst_args_index] << packed_shift) + routine_start, true, argc - 1); } else { storei(0); } break; case 0xDA: // Call routine and discard result if (inst_args[inst_args_index] != 0) { enter_routine((uint)(inst_args[inst_args_index] << packed_shift) + routine_start, false, argc - 1); } break; case 0xDB: // Set colors //NOP break; case 0xDC: // Throw frameptr = inst_args[1]; exit_routine(inst_args[inst_args_index]); break; case 0xDD: // Bitwise XOR storei(inst_args[0] ^ inst_args[1]); break; case 0xE0: // Call routine // Read from extended RAM if (zmachineVersion > 8) { u = (uint)((inst_args[0] << address_shift) + (inst_args[1] << 1) + inst_args[2]); storei(read16((int)u)); } else if (inst_args[inst_args_index] != 0) { program_counter++; enter_routine((uint)(inst_args[inst_args_index] << packed_shift) + routine_start, true, argc - 1); } else { storei(0); } break; case 0xE1: // Write 16-bit number to RAM write16(inst_args[0] + ((short) inst_args[1] << 1), inst_args[2]); break; case 0xE2: // Write 8-bit number to RAM memory[inst_args[0] + (short) inst_args[1]] = (byte) inst_args[2]; break; case 0xE3: // Write property u = property_address(inst_args[0], (byte) inst_args[1]); if (cur_prop_size == 1) { memory[u] = (byte) inst_args[2]; } else { write16((int)u, inst_args[2]); } break; case 0xE4: // Read line of input n = await line_input(); if (execresult != ExecutionResult.ERR_NO_ERRORS) return execresult; if (zmachineVersion > 4 && !lastdebug) { storei(n); } break; case 0xE5: // Print character char_print((byte)inst_args[inst_args_index]); break; case 0xE6: // Print number n = (short) inst_args[inst_args_index]; if (n == -32768) { char_print('-'); char_print('3'); char_print('2'); char_print('7'); char_print('6'); char_print('8'); } else { nbuf[0] = nbuf[1] = nbuf[2] = nbuf[3] = nbuf[4] = 0; if (n < 0) { char_print('-'); n *= -1; } nbuf[4] = (byte)( (n % 10) | '0'); if ((n /= 10) != 0) { nbuf[3] = (byte) ((n % 10) | '0'); } if ((n /= 10) != 0) { nbuf[2] = (byte) ((n % 10) | '0'); } if ((n /= 10) != 0) { nbuf[1] = (byte) ((n % 10) | '0'); } if ((n /= 10) != 0) { nbuf[0] = (byte) ((n % 10) | '0'); } char_print(nbuf[0]); char_print(nbuf[1]); char_print(nbuf[2]); char_print(nbuf[3]); char_print(nbuf[4]); } break; case 0xE7: // Random number generator if ((short) inst_args[inst_args_index] > 0) { storei(get_random((short) inst_args[inst_args_index])); } else { randomize((ushort)(-(short) inst_args[inst_args_index])); storei(0); } break; case 0xE8: // Push to stack stack[stackptr++] = inst_args[inst_args_index]; break; case 0xE9: // Pop from stack if (inst_args[inst_args_index] != 0) { store((byte) inst_args[inst_args_index], stack[--stackptr]); } else { stack[stackptr - 2] = stack[stackptr - 1]; stackptr--; } break; case 0xEA: // Split window //NOP break; case 0xEB: // Set active window window = inst_args[inst_args_index] != 0; break; case 0xEC: // Call routine if (inst_args[inst_args_index] != 0) { program_counter++; enter_routine((uint)(inst_args[inst_args_index] << packed_shift) + routine_start, true, argc - 1); } else { storei(0); } break; case 0xED: // Clear window if (inst_args[inst_args_index] != 1) { runtime.Write('\n'); textptr = 0; cur_row = 2; cur_column = 0; while (cur_column < lmargin) { runtime.Write((char)32); cur_column++; } } break; case 0xEE: // Erase line //NOP break; case 0xEF: // Set cursor position //NOP break; case 0xF0: // Get cursor position if (window) { memory[inst_args[inst_args_index]] = (byte)sc_rows; memory[inst_args[inst_args_index + 1]] = (byte) (cur_column + 1); } else { memory[inst_args[inst_args_index]] = 0; memory[inst_args[inst_args_index + 1]] = 0; } break; case 0xF1: // Set text style //NOP break; case 0xF2: // Buffer mode buffering = inst_args[inst_args_index] != 0; break; case 0xF3: // Select output stream switch_output((short) inst_args[inst_args_index]); break; case 0xF4: // Select input stream if (inlog != 0) { from_log = inst_args[inst_args_index] != 0; } break; case 0xF5: // Sound effects //runtime.Write((char)7); //Console.Write(7); break; case 0xF6: // Read a single character n = (short)(await char_input()); if (execresult != ExecutionResult.ERR_NO_ERRORS) return execresult; if (lastdebug) { storei(n); } break; case 0xF7: // Scan a table if (argc < 4) { inst_args[3] = 0x82; } u = inst_args[1]; while (inst_args[2] != 0) { if (inst_args[0] == ((inst_args[3] & 0x80) != 0 ? read16((int)u) : memory[u])) break; u += (uint)inst_args[3] & 0x7F; inst_args[2]--; } storei((int) (inst_args[2] != 0 ? u : 0)); branch(inst_args[2] != 0); break; case 0xF8: // Not storei(~inst_args[inst_args_index]); break; case 0xF9: // Call routine and discard results // Write extended RAM if (zmachineVersion > 8) { u = ((uint)inst_args[0] << address_shift) + ((uint) inst_args[1] << 1) + (uint)inst_args[2]; write16((int)u, inst_args[3]); } else if (inst_args[inst_args_index] != 0) { enter_routine((uint) ((inst_args[inst_args_index] << packed_shift) + routine_start), false, argc - 1); } break; case 0xFA: // Call routine and discard results if (inst_args[inst_args_index] != 0) { enter_routine((uint) ((inst_args[inst_args_index] << packed_shift) + routine_start), false, argc - 1); } break; case 0xFB: // Tokenise text if (argc < 4) { inst_args[3] = 0; } if (argc < 3) { inst_args[2] = 0; } tokenise((uint)(inst_args[0] + 2), inst_args[2], inst_args[1], memory[inst_args[0] + 1], inst_args[3]); break; case 0xFC: // Encode text in dictionary format var buffr = new byte[255]; Array.Copy(memory, (int) (inst_args[0] + inst_args[2]), buffr, 0, 256); ulong execute_instruction_y = dictionary_encode(buffr, inst_args[1]); write16(inst_args[3], (ushort)(execute_instruction_y >> 16)); write16(inst_args[3] + 2, (ushort) (execute_instruction_y >> 8)); write16(inst_args[3] + 4, (ushort) execute_instruction_y); break; case 0xFD: // Copy a table if (inst_args[1] == 0) { // zero! while (inst_args[2] != 0) { memory[inst_args[0] + --inst_args[2]] = 0; } } else if ((short) inst_args[2] > 0 && inst_args[1] > inst_args[0]) { // backward! m = (short) inst_args[2]; while (m-- != 0) { memory[inst_args[1] + m] = memory[inst_args[0] + m]; } } else { // forward! if ((short) inst_args[2] < 0) { inst_args[2] = (ushort) (inst_args[2] * -1); } m = 0; while (m < (short) inst_args[2]) { memory[inst_args[1] + m] = memory[inst_args[0] + m]; m++; } } break; case 0xFE: // Print a rectangle of text make_rectangle(inst_args[0], inst_args[1], argc > 2 ? inst_args[2] : 1, argc > 3 ? (short) inst_args[3] : 0); // (I assume the skip is signed, since many other things are, and +32768 isn't useful anyways.) break; case 0xFF: // Check argument count branch(frames[frameptr].argc >= (byte) inst_args[inst_args_index]); break; default: runtime.Debug.LogError("\n*** Invalid instruction: {0:X2} (near {1:X6})\n", currentInstruction, program_counter); return await Task.FromResult(ExecutionResult.ERR_UNKNOWN); break; } return await Task.FromResult(execresult); }
public virtual void ExecutionResult(C context, ExecutionResult mystruct) { }
public bool ExportExecutionDetailsToRQM(BusinessFlow businessFlow, ref string result, bool exectutedFromAutomateTab = false, PublishToALMConfig publishToALMConfig = null) { result = string.Empty; string bfExportedID = GetExportedIDString(businessFlow.ExternalID, "RQMID"); if (string.IsNullOrEmpty(bfExportedID) || bfExportedID.Equals("0")) { result = GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " is missing ExternalID, cannot export RQM TestPlan execution results without External ID"; return(false); } if (businessFlow.ActivitiesGroups.Count == 0) { result = GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " Must have at least one " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup); return(false); } LoginDTO loginData = new LoginDTO() { User = ALMCore.DefaultAlmConfig.ALMUserName, Password = ALMCore.DefaultAlmConfig.ALMPassword, Server = ALMCore.DefaultAlmConfig.ALMServerURL }; // // get data about execution records per current test plan - start RQMTestPlan testPlan = new RQMTestPlan(); string importConfigTemplate = System.IO.Path.Combine(RQMCore.ConfigPackageFolderPath, "RQM_Import", "RQM_ImportConfigs_Template.xml"); if (File.Exists(importConfigTemplate)) { XmlSerializer serializer = new XmlSerializer(typeof(RQMProjectListConfiguration)); FileStream fs = new FileStream(importConfigTemplate, FileMode.Open); XmlReader reader = XmlReader.Create(fs); RQMProjectListConfiguration RQMProjectList; RQMProjectList = (RQMProjectListConfiguration)serializer.Deserialize(reader); fs.Close(); RQMProject currentRQMProjectMapping; if (RQMProjectList.RQMProjects.Count > 0) { currentRQMProjectMapping = RQMProjectList.RQMProjects.Where(x => x.Name == ALMCore.DefaultAlmConfig.ALMProjectName || x.Name == "DefaultProjectName").FirstOrDefault(); if (currentRQMProjectMapping != null) { testPlan = RQMConnect.Instance.GetRQMTestPlanByIdByProject(ALMCore.DefaultAlmConfig.ALMServerURL, ALMCore.DefaultAlmConfig.ALMUserName, ALMCore.DefaultAlmConfig.ALMPassword, ALMCore.DefaultAlmConfig.ALMProjectName, GetExportedIDString(businessFlow.ExternalID, "RQMID")); if (testPlan == null) { result = "Recent Testing Plan not exists in connected RQM project."; return(false); } testPlan.RQMExecutionRecords = RQMConnect.Instance.GetExecutionRecordsByTestPlan(loginData, reader, currentRQMProjectMapping, RQMCore.ALMProjectGroupName, RQMCore.ALMProjectGuid, testPlan.URLPathVersioned); } } } // get data about execution records per current test plan - finish List <ExecutionResult> exeResultList = new List <ExecutionResult>(); foreach (ActivitiesGroup activGroup in businessFlow.ActivitiesGroups) { if ((publishToALMConfig.FilterStatus == FilterByStatus.OnlyPassed && activGroup.RunStatus == eActivitiesGroupRunStatus.Passed) || (publishToALMConfig.FilterStatus == FilterByStatus.OnlyFailed && activGroup.RunStatus == eActivitiesGroupRunStatus.Failed) || publishToALMConfig.FilterStatus == FilterByStatus.All) { ExecutionResult exeResult = GetExeResultforAg(businessFlow, bfExportedID, activGroup, ref result, testPlan); if (exeResult != null) { exeResultList.Add(exeResult); } else { return(false); } } } ResultInfo resultInfo = new ResultInfo(); // // Updating of Execution Record Results (test plan level) try { resultInfo = RQMConnect.Instance.RQMRep.ExportExecutionResult(loginData, exeResultList, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName); } catch { Reporter.ToLog(eLogLevel.ERROR, "Failed to Update Execution Record Results"); } // // Creating Test Suite Log (per test suite) try { foreach (RQMTestSuite rQMTestSuite in testPlan.TestSuites) { if ((rQMTestSuite.ACL_TestSuite_Copy != null) && (rQMTestSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.ACL_TestSuiteLog_Copy != null)) { resultInfo = RQMConnect.Instance.RQMRep.CreateTestSuiteLog(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, rQMTestSuite.ACL_TestSuite_Copy, rQMTestSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.ACL_TestSuiteLog_Copy); } } } catch { Reporter.ToLog(eLogLevel.ERROR, "Failed to Update Execution Record Results"); } // // Attaching of Activity Groups Reports try { // Attach ActivityGroup Report if needed if ((publishToALMConfig.ToAttachActivitiesGroupReport) || (exectutedFromAutomateTab)) { foreach (ActivitiesGroup activGroup in businessFlow.ActivitiesGroups) { try { ACL_Data_Contract.Activity currentActivity = GetTestCaseFromActivityGroup(activGroup); ACL_Data_Contract.Attachment reportAttachment = new ACL_Data_Contract.Attachment(); string activityGroupName = PathHelper.CleanInValidPathChars(activGroup.Name); if ((activGroup.TempReportFolder != null) && (activGroup.TempReportFolder != string.Empty) && (System.IO.Directory.Exists(activGroup.TempReportFolder))) { //Creating the Zip file - start string targetZipPath = System.IO.Directory.GetParent(activGroup.TempReportFolder).ToString(); string zipFileName = targetZipPath + "\\" + activityGroupName.ToString().Replace(" ", "_") + "_GingerHTMLReport.zip"; if (!System.IO.File.Exists(zipFileName)) { ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName); } else { System.IO.File.Delete(zipFileName); ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName); } System.IO.Directory.Delete(activGroup.TempReportFolder, true); //Creating the Zip file - finish //Attaching Zip file - start reportAttachment.ClientFileName = activityGroupName.ToString().Replace(" ", "_") + "_GingerHTMLReport.zip"; reportAttachment.ServerLocation = targetZipPath + @"\" + reportAttachment.ClientFileName; reportAttachment.CreatedBy = Environment.UserName; currentActivity.EntityId = Convert.ToInt32(GetExportedIDString(activGroup.ExternalID.ToString(), "RQMID")); currentActivity.ExportedID = (long)currentActivity.EntityId; currentActivity.ActivityData.AttachmentsColl = new Attachments(); currentActivity.ActivityData.AttachmentsColl.Add(reportAttachment); string exportJarFilePath = Assembly.GetExecutingAssembly().Location.Replace(@"GingerCore.dll", "") + @"ALM\\RQM\\JAVA"; RQMConnect.Instance.RQMRep.UploadAttachmetToRQMAndGetIds(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity, exportJarFilePath); RQMConnect.Instance.RQMRep.UpdateTestCaseWithNewAttachmentID(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity); //Attaching Zip file - finish System.IO.File.Delete(zipFileName); } } catch { Reporter.ToLog(eLogLevel.ERROR, "Failed to attach report Per ActivityGroup - " + activGroup.Name); } } } } catch (Exception e) { resultInfo.ErrorCode = 1; result = e.ToString(); } if (resultInfo.ErrorCode == 0) { result = "Export execution details to RQM performed successfully."; return(true); } else { result = resultInfo.ErrorDesc; } Reporter.ToLog(eLogLevel.ERROR, "Failed to export execution details to RQM/ALM"); return(false); }
/// <summary> /// Initializes an instance of <see cref="StandardErrorValidationException"/>. /// </summary> public StandardErrorValidationException(ExecutionResult executionResult) : base(executionResult, CreateExceptionMessage(executionResult)) { }
public Task <IExecutionResult> PublishAsync(ICommandBus commandBus, CancellationToken cancellationToken) { var result = ExecutionResult.Failed("not run from here"); return(Task.FromResult(result)); }
//private readonly IApplicationTaskLogic _applicationWorkflow; //public CreateAppStep(IApplicationTaskLogic applicationWorkflow) //{ // _applicationWorkflow = applicationWorkflow; //} public override ExecutionResult Run(IStepExecutionContext context) { //_applicationWorkflow.InsertLoanApplicationTaskUser(ApplicationId, UserId, Role, Status).Wait(); // WorkflowId = context.Workflow.Id; return(ExecutionResult.Next()); }
public static ExecutionResult ExecuteActions(List <Action> actions) { ExecutionResult fastBuildResult = ExecutionResult.TasksSucceeded; CompilationActions = null; LinkerActions = null; if (actions.Count <= 0) { return(fastBuildResult); } if (IsAvailable() == false) { return(ExecutionResult.Unavailable); } List <Action> unassignedObjects = new List <Action>(); List <Action> unassignedLinks = new List <Action>(); List <Action> miscActions = actions.Where(a => a.ActionType != ActionType.Compile && a.ActionType != ActionType.Link).ToList(); Dictionary <Action, BuildComponent> fastbuildActions = new Dictionary <Action, BuildComponent>(); DeresponsifyActions(actions); CompilationActions = GatherActionsObjects(actions.Where(a => a.ActionType == ActionType.Compile), ref unassignedObjects, ref fastbuildActions); LinkerActions = GatherActionsLink(actions.Where(a => a.ActionType == ActionType.Link), ref unassignedLinks, ref fastbuildActions); ResolveDependencies(CompilationActions, LinkerActions, fastbuildActions); Log.TraceInformation("Actions: " + actions.Count + " - Unassigned: " + unassignedObjects.Count); Log.TraceInformation("Misc Actions - FBuild: " + miscActions.Count); Log.TraceInformation("Objects - FBuild: " + CompilationActions.Count + " -- Local: " + unassignedObjects.Count); var lg = 0; if (LinkerActions != null) { lg = LinkerActions.Count; } Log.TraceInformation("Link - FBuild: " + lg + " -- Local: " + unassignedLinks.Count); if (unassignedLinks.Count > 0) { throw new Exception("Error, unaccounted for lib! Cannot guarantee there will be no prerequisite issues. Fix it"); } if (unassignedObjects.Count > 0) { var actionThreadDictionary = new Dictionary <Action, ActionThread>(); ExecuteLocalActions(unassignedObjects, actionThreadDictionary, unassignedObjects.Count); } if (FASTBuildConfiguration.UseSinglePassCompilation) { RunFBuild(BuildStep.CompileAndLink, GenerateFBuildFileString(BuildStep.CompileAndLink, CompilationActions.Concat(LinkerActions).ToList())); } else { if (CompilationActions.Any()) { fastBuildResult = RunFBuild(BuildStep.CompileObjects, GenerateFBuildFileString(BuildStep.CompileObjects, CompilationActions)); } if (fastBuildResult == ExecutionResult.TasksSucceeded) { if (LinkerActions != null && LinkerActions.Any()) { if (!BuildConfiguration.bFastbuildNoLinking) { fastBuildResult = RunFBuild(BuildStep.Link, GenerateFBuildFileString(BuildStep.Link, LinkerActions)); } } } } return(fastBuildResult); }
static ExecutionResult ExecuteInspectors(InspectionOptions options) { bool anyFailed = false; try { var dispatch = new InspectorDispatch(); var searchService = new NugetSearchService(options.PackagesRepoUrl, options.NugetConfigPath); var inspectionResults = dispatch.Inspect(options, searchService); if (inspectionResults != null) { foreach (var result in inspectionResults) { try { if (result.ResultName != null) { Console.WriteLine("Inspection: " + result.ResultName); } if (result.Status == InspectionResult.ResultStatus.Success) { Console.WriteLine("Inspection Result: Success"); var writer = new InspectionResultJsonWriter(result); writer.Write(); Console.WriteLine("Info file created at {0}", writer.FilePath()); } else { Console.WriteLine("Inspection Result: Error"); if (result.Exception != null) { Console.WriteLine("Exception:"); Console.WriteLine(result.Exception); anyFailed = true; } } } catch (Exception e) { Console.WriteLine("Error processing inspection result."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); anyFailed = true; } } } } catch (Exception e) { Console.WriteLine("Error iterating inspection results."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); anyFailed = true; } if (anyFailed) { return(ExecutionResult.Failed()); } else { return(ExecutionResult.Succeeded()); } }
public TestsResultResponse(ExecutionResult status, string description) { this.result = status; this.ResultDescription = description; }
public PreExecutedResolverResult(ExecutionResult executionResult) { _data = executionResult.Data; _errors = executionResult.Errors; _extensions = executionResult.Extensions; }
public override ExecutionResult Run(IStepExecutionContext context) { TaskCTicker++; return(ExecutionResult.Next()); }
public async Task CompletesWithResultMessageIfThereIsAnException(ExecutionResult result) { // Arrange var cts = new CancellationTokenSource(); var runner = new TestableJobRunner(TimeSpan.FromSeconds(5)); var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary<string, string>()); var exception = new Exception("BORK!"); runner.MockDispatcher .Setup(d => d.Dispatch(It.IsAny<InvocationContext>())) .Completes(() => { runner.VirtualClock.Advance(TimeSpan.FromDays(365)); // Wow this is a long job ;) return new InvocationResult(result, exception); }) .Verifiable(); // Act await runner.Dispatch(invocation, cts.Token); // Assert runner.MockQueue.Verify(q => q.Complete(invocation, result, exception.ToString(), null)); }
private ExecutionResult GetExeResultforAg(BusinessFlow businessFlow, string bfExportedID, ActivitiesGroup activGroup, ref string result, RQMTestPlan testPlan) { try { LoginDTO loginData = new LoginDTO() { User = ALMCore.DefaultAlmConfig.ALMUserName, Password = ALMCore.DefaultAlmConfig.ALMPassword, Server = ALMCore.DefaultAlmConfig.ALMServerURL }; if (string.IsNullOrEmpty(activGroup.ExternalID)) { result = "At " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + ", is missing ExternalID, cannot export RQM TestPlan execution results without External ID"; return(null); } ExecutionResult exeResult = new ExecutionResult { TestPlanExportID = bfExportedID }; List <Activity> relevantActivities = new List <Activity>(); relevantActivities = businessFlow.Activities.Where(x => x.ActivitiesGroupID == activGroup.FileName).ToList(); exeResult.ExecutionStep = new List <ExecutionStep>(); string txExportID = GetExportedIDString(activGroup.ExternalID, "RQMID"); string tsExportID = GetExportedIDString(activGroup.ExternalID, "RQMScriptID"); string erExportID = GetExportedIDString(activGroup.ExternalID, "RQMRecordID"); if ((activGroup.TestSuiteId != null) && (activGroup.TestSuiteId != string.Empty)) { // check if test suite execution record is exists per current Test Suite ID // if not exists to create it and than procced to work on just created RQMTestSuite testSuite = testPlan.TestSuites.Where(z => z.RQMID == activGroup.TestSuiteId).FirstOrDefault(); if ((testSuite != null) && (testSuite.RQMID != null) && (testSuite.URLPathVersioned != null) && (testSuite.RQMID != string.Empty) && (testSuite.URLPathVersioned != string.Empty)) { try { ResultInfo resultInfo; // check if execution record of testSuite exist. If not - to create it if ((testSuite.TestSuiteExecutionRecord == null) || (testSuite.TestSuiteExecutionRecord.RQMID == null) || (testSuite.TestSuiteExecutionRecord.URLPathVersioned == string.Empty)) { testSuite.ACL_TestSuite_Copy = new TestSuite(); testSuite.ACL_TestSuite_Copy.TestSuiteName = testSuite.Name; testSuite.ACL_TestSuite_Copy.TestSuiteExportID = testSuite.RQMID; resultInfo = RQMConnect.Instance.RQMRep.CreateTestSuiteExecutionRecord(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, testSuite.ACL_TestSuite_Copy, bfExportedID, businessFlow.Name.ToString()); if (resultInfo.IsSuccess) { if (testSuite.TestSuiteExecutionRecord == null) { testSuite.TestSuiteExecutionRecord = new RQMTestSuiteExecutionRecord(); } testSuite.TestSuiteExecutionRecord.RQMID = testSuite.ACL_TestSuite_Copy.TestSuiteExecutionRecordExportID; testSuite.TestSuiteExecutionRecord.URLPathVersioned = testSuite.ACL_TestSuite_Copy.TestSuiteExecutionRecordExportUri; } } else { testSuite.ACL_TestSuite_Copy = new TestSuite(); testSuite.ACL_TestSuite_Copy.TestSuiteName = testSuite.Name; testSuite.ACL_TestSuite_Copy.TestSuiteExportID = testSuite.RQMID; testSuite.ACL_TestSuite_Copy.TestSuiteExecutionRecordExportID = testSuite.TestSuiteExecutionRecord.RQMID; testSuite.ACL_TestSuite_Copy.TestSuiteExecutionRecordExportUri = testSuite.TestSuiteExecutionRecord.URLPathVersioned; } // after creating of execution record at RQM and as object at Ginger (or checking that it's exists) // need to create testsuiteLOG on it and add test caseexecution records on it Ginger (the objects at RQM will be created after loop) ACL_Data_Contract.Activity currentActivity = GetTestCaseFromActivityGroup(activGroup); resultInfo = RQMConnect.Instance.RQMRep.CreateExecutionRecordPerActivityWithInTestSuite(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity, bfExportedID, businessFlow.Name, testSuite.Name.ToString()); if (resultInfo.IsSuccess) { if ((testSuite.TestSuiteExecutionRecord.TestSuiteResults == null) || (testSuite.TestSuiteExecutionRecord.TestSuiteResults.Count == 0) || (testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult == null)) { testSuite.TestSuiteExecutionRecord.TestSuiteResults = new ObservableList <RQMTestSuiteResults>(); testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult = new RQMTestSuiteResults(); testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.RQMExecutionRecords = new ObservableList <RQMExecutionRecord>(); testSuite.TestSuiteExecutionRecord.TestSuiteResults.Add(testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult); } RQMExecutionRecord executionRecord = new RQMExecutionRecord(currentActivity.ExportedTcExecutionRecId.ToString(), currentActivity.ExportedTestScriptId.ToString(), currentActivity.ExportedID.ToString()); testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.RQMExecutionRecords.Add(executionRecord); testSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.ACL_TestSuiteLog_Copy.TestSuiteLogExecutionRecords.Add(exeResult); exeResult.ExpectedResultName = currentActivity.EntityName; erExportID = executionRecord.RQMID; currentActivity.ExportedID = long.Parse(executionRecord.RQMID); string atsID = GetExportedIDString(activGroup.ExternalID, "AtsID"); if (atsID == "0") { atsID = string.Empty; } activGroup.ExternalID = "RQMID=" + txExportID + "|RQMScriptID=" + tsExportID + "|RQMRecordID=" + erExportID + "|AtsID=" + atsID; } } catch { } } else { } } else if (string.IsNullOrEmpty(erExportID) || erExportID.Equals("0") || !testPlan.RQMExecutionRecords.Select(z => z.RQMID).ToList().Contains(erExportID)) { ResultInfo resultInfo; ACL_Data_Contract.Activity currentActivity = GetTestCaseFromActivityGroup(activGroup); try { // check if executionRecordID exist in RQM but still was not updated in business flow XML RQMExecutionRecord currentExecutionRecord = testPlan.RQMExecutionRecords.Where(y => y.RelatedTestCaseRqmID == txExportID && y.RelatedTestScriptRqmID == tsExportID).ToList().FirstOrDefault(); if (currentExecutionRecord != null) { erExportID = currentExecutionRecord.RQMID; } else { // if executionRecord not updated and not exists - so create one in RQM and update BussinesFlow object (this may be not saved due not existed "autosave" functionality) resultInfo = RQMConnect.Instance.RQMRep.CreateExecutionRecordPerActivity(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity, bfExportedID, businessFlow.Name); if (!currentActivity.ExportedTcExecutionRecId.Equals("0")) { string atsID = GetExportedIDString(activGroup.ExternalID, "AtsID"); if (atsID == "0") { atsID = string.Empty; } erExportID = currentActivity.ExportedTcExecutionRecId.ToString(); activGroup.ExternalID = "RQMID=" + txExportID + "|RQMScriptID=" + tsExportID + "|RQMRecordID=" + erExportID + "|AtsID=" + atsID; ; } } } catch { Reporter.ToLog(eLogLevel.ERROR, "Failed to create Execution Record Per Activity - " + currentActivity.EntityName); } } if (string.IsNullOrEmpty(txExportID) || string.IsNullOrEmpty(tsExportID) || string.IsNullOrEmpty(erExportID) || txExportID.Equals("0") || tsExportID.Equals("0") || erExportID.Equals("0")) { result = "At " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + ", is missing ExternalID, cannot export RQM TestPlan execution results without Extrnal ID"; return(null); } exeResult.TestCaseExportID = txExportID; exeResult.TestScriptExportID = tsExportID; exeResult.ExecutionRecordExportID = erExportID; int i = 1; foreach (Activity act in relevantActivities) { ExecutionStep exeStep = new ExecutionStep { StepExpResults = act.Expected, StepOrderId = i, EntityDesc = act.ActivityName, }; i++; switch (act.Status) { case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.Failed; string errors = string.Empty; List <IAct> failedActs = act.Acts.Where(x => x.Status == Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed).ToList(); foreach (IAct action in failedActs) { errors += action.Error + Environment.NewLine; } exeStep.StepActualResult = errors; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Passed: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.Passed; exeStep.StepActualResult = "Passed as expected"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.NA: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.NA; exeStep.StepActualResult = "NA"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Pending: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.In_Progress; exeStep.StepActualResult = "Was not executed"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Running: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.In_Progress; exeStep.StepActualResult = "Not Completed"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.Outscoped; exeStep.StepActualResult = "Skipped"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Blocked: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.Blocked; exeStep.StepActualResult = "Blocked"; break; case Amdocs.Ginger.CoreNET.Execution.eRunStatus.Stopped: exeStep.StepStatus = ACL_Data_Contract.ExecutoinStatus.Inconclusive; exeStep.StepActualResult = "Stopped"; break; } exeResult.ExecutionStep.Add(exeStep); } return(exeResult); } catch (Exception ex) { result = "Unexpected error occurred- " + ex.Message; Reporter.ToLog(eLogLevel.ERROR, "Failed to export execution details to RQM/ALM", ex); return(null); } }
private static string GetExecutionResultOutput (ExecutionResult result) { string output = ""; if (!string.IsNullOrEmpty (result.output)) { output += "\n"; output += result.output; } if (!string.IsNullOrEmpty (result.error)) { output += "\n"; output += result.error; } if (result.exception != null) { output += "\n"; output += result.exception.Message; } return output; }
async Task<ExecutionResult> game_restart() { execresult = ExecutionResult.ERR_NO_ERRORS; await Task.Run(() => { int addr = 64; stackptr = frameptr = 0; program_counter = restart_address; fileIO.ClearErr(story); fileIO.FSeek(story, 64, FSeekOffset.SEEK_SET); var buffer = new byte[1024]; while (!fileIO.FEof(story)) { var readBytes = fileIO.FRead(buffer, 1024, 1, story); Array.Copy((byte[])readBytes.Data, 0, memory, addr, readBytes.Length); if (readBytes.Length == 0) break; addr += 1024; } }); return execresult; }
public async Task InvokeAsync(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { await _next(context); return; } // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/ // Inspiration: https://github.com/graphql/express-graphql/blob/master/src/index.js var httpRequest = context.Request; var httpResponse = context.Response; var writer = context.RequestServices.GetRequiredService <IDocumentWriter>(); var cancellationToken = GetCancellationToken(context); // GraphQL HTTP only supports GET and POST methods bool isGet = HttpMethods.IsGet(httpRequest.Method); bool isPost = HttpMethods.IsPost(httpRequest.Method); if (!isGet && !isPost) { httpResponse.Headers["Allow"] = "GET, POST"; await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, $"Invalid HTTP method. Only GET and POST are supported. {DOCS_URL}", httpStatusCode : 405 // Method Not Allowed ); return; } // Parse POST body GraphQLRequest bodyGQLRequest = null; GraphQLRequest[] bodyGQLBatchRequest = null; if (isPost) { if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader)) { await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed."); return; } switch (mediaTypeHeader.MediaType) { case MediaType.JSON: var deserializationResult = await _deserializer.DeserializeFromJsonBodyAsync(httpRequest, cancellationToken); if (!deserializationResult.IsSuccessful) { await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, "Body text could not be parsed. Body text should start with '{' for normal graphql query or with '[' for batched query."); return; } bodyGQLRequest = deserializationResult.Single; bodyGQLBatchRequest = deserializationResult.Batch; break; case MediaType.GRAPH_QL: bodyGQLRequest = await DeserializeFromGraphBodyAsync(httpRequest.Body); break; case MediaType.FORM: var formCollection = await httpRequest.ReadFormAsync(); bodyGQLRequest = DeserializeFromFormBody(formCollection); break; default: await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{MediaType.JSON}', '{MediaType.GRAPH_QL}' or '{MediaType.FORM}'. {DOCS_URL}"); return; } } // If we don't have a batch request, parse the query from URL too to determine the actual request to run. // Query string params take priority. GraphQLRequest gqlRequest = null; if (bodyGQLBatchRequest == null) { var urlGQLRequest = DeserializeFromQueryString(httpRequest.Query); gqlRequest = new GraphQLRequest { Query = urlGQLRequest.Query ?? bodyGQLRequest?.Query, Inputs = urlGQLRequest.Inputs ?? bodyGQLRequest?.Inputs, Extensions = urlGQLRequest.Extensions ?? bodyGQLRequest?.Extensions, OperationName = urlGQLRequest.OperationName ?? bodyGQLRequest?.OperationName }; } // Prepare context and execute var userContextBuilder = context.RequestServices.GetService <IUserContextBuilder>(); var userContext = userContextBuilder == null ? new Dictionary <string, object>() // in order to allow resolvers to exchange their state through this object : await userContextBuilder.BuildUserContext(context); var executer = context.RequestServices.GetRequiredService <IGraphQLExecuter <TSchema> >(); // Normal execution with single graphql request if (bodyGQLBatchRequest == null) { var stopwatch = ValueStopwatch.StartNew(); await RequestExecutingAsync(gqlRequest); var result = await ExecuteRequestAsync(gqlRequest, userContext, executer, context.RequestServices, cancellationToken); await RequestExecutedAsync(new GraphQLRequestExecutionResult(gqlRequest, result, stopwatch.Elapsed)); await WriteResponseAsync(httpResponse, writer, cancellationToken, result); } // Execute multiple graphql requests in one batch else { var executionResults = new ExecutionResult[bodyGQLBatchRequest.Length]; for (int i = 0; i < bodyGQLBatchRequest.Length; ++i) { var gqlRequestInBatch = bodyGQLBatchRequest[i]; var stopwatch = ValueStopwatch.StartNew(); await RequestExecutingAsync(gqlRequestInBatch, i); var result = await ExecuteRequestAsync(gqlRequestInBatch, userContext, executer, context.RequestServices, cancellationToken); await RequestExecutedAsync(new GraphQLRequestExecutionResult(gqlRequestInBatch, result, stopwatch.Elapsed, i)); executionResults[i] = result; } await WriteResponseAsync(httpResponse, writer, cancellationToken, executionResults); } }
public override ExecutionResult Run(IStepExecutionContext context) { _myService.DoTheThings(); return(ExecutionResult.Next()); }
public async Task<ExecutionResult> ExecuteAsync(ExecutionOptions config) { var metrics = new Metrics(); metrics.Start(config.OperationName); config.FieldMiddleware.ApplyTo(config.Schema); var result = new ExecutionResult { Query = config.Query }; try { if (!config.Schema.Initialized) { using (metrics.Subject("schema", "Initializing schema")) { config.Schema.Initialize(); } } var document = config.Document; using (metrics.Subject("document", "Building document")) { if (document == null) { document = _documentBuilder.Build(config.Query); } } result.Document = document; var operation = GetOperation(config.OperationName, document); result.Operation = operation; metrics.SetOperationName(operation?.Name); if (config.ComplexityConfiguration != null) { using (metrics.Subject("document", "Analyzing complexity")) _complexityAnalyzer.Validate(document, config.ComplexityConfiguration); } IValidationResult validationResult; using (metrics.Subject("document", "Validating document")) { validationResult = _documentValidator.Validate( config.Query, config.Schema, document, config.ValidationRules, config.UserContext); } foreach (var listener in config.Listeners) { await listener.AfterValidationAsync( config.UserContext, validationResult, config.CancellationToken) .ConfigureAwait(false); } if (validationResult.IsValid) { var context = BuildExecutionContext( config.Schema, config.Root, document, operation, config.Inputs, config.UserContext, config.CancellationToken, metrics); if (context.Errors.Any()) { result.Errors = context.Errors; return result; } using (metrics.Subject("execution", "Executing operation")) { foreach (var listener in config.Listeners) { await listener.BeforeExecutionAsync(config.UserContext, config.CancellationToken).ConfigureAwait(false); } var task = ExecuteOperationAsync(context).ConfigureAwait(false); foreach (var listener in config.Listeners) { await listener.BeforeExecutionAwaitedAsync(config.UserContext, config.CancellationToken).ConfigureAwait(false); } result.Data = await task; foreach (var listener in config.Listeners) { await listener.AfterExecutionAsync(config.UserContext, config.CancellationToken).ConfigureAwait(false); } } if (context.Errors.Any()) { result.Errors = context.Errors; } } else { result.Data = null; result.Errors = validationResult.Errors; } return result; } catch (Exception exc) { if (result.Errors == null) { result.Errors = new ExecutionErrors(); } result.Data = null; result.Errors.Add(new ExecutionError(exc.Message, exc)); return result; } finally { result.Perf = metrics.Finish().ToArray(); } }
public XDocument Transform(ExecutionResult executionResult) { return(new XDocument( new XElement("assemblies", executionResult.AssemblyResults.Select(Assembly)))); }
public ExecutionResult ValidateCommand(object commandMessage, ICommandConfiguration commandConfiguration) { var totalResult = new ExecutionResult(); IEnumerable<ValidationRuleInstance> ruleInstances = commandConfiguration.GetValidationRules(); foreach (ValidationRuleInstance instance in ruleInstances) { if (instance.ShouldApply != null) if (!(bool) instance.ShouldApply.DynamicInvoke(commandMessage)) continue; Delegate compile = instance.ToCheckExpression.Compile(); object input = compile.DynamicInvoke(new object[] {commandMessage}); bool stopProcessing = false; if (instance.ArrayRule) { var enumerable = (IEnumerable) input; int i = 0; foreach (object item in enumerable) { if (item == null) continue; IValidationRule rule = _ruleFactory.ConstructRule(instance); string result = rule.IsValid(item); bool ruleFailed = result != null; if (ruleFailed) { var indexedUiExpression = new IndexReplacerVisitor(i).Visit(instance.UIAttributeExpression); totalResult.AddMessage(result, instance.ToCheckExpression, (LambdaExpression)indexedUiExpression, instance.ToCompareExpression); if (rule.StopProcessing) { stopProcessing = true; break; } } i++; } } else { IValidationRule rule = _ruleFactory.ConstructRule(instance); if (rule is ICrossReferencedValidationRule) { Delegate toCompareDelegate = instance.ToCompareExpression.Compile(); object toCompare = toCompareDelegate.DynamicInvoke(new object[] {commandMessage}); ((ICrossReferencedValidationRule) rule).ToCompare = toCompare; } string result = rule.IsValid(input); bool ruleFailed = result != null; if (ruleFailed) { totalResult.AddMessage(result, instance.ToCheckExpression, instance.UIAttributeExpression, instance.ToCompareExpression); if (rule.StopProcessing) { break; } } } if (stopProcessing) break; } return totalResult; }
public void CallSayHelloFunction() { using (ExecutionResult er = this.Caller.SayHello()) { } }
public override ExecutionResult Run(IStepExecutionContext context) { Console.WriteLine("goodby!!"); return(ExecutionResult.Next()); }
public override NodeTreeOutput Tick(out ExecutionResult executionResult, ExecutionResult childResult) { Calculate(); executionResult = ExecutionResult.Success; return(null); }
public ExecutionResult CompileAndExecute(string userId) { string environmentPath = _root + userId + _ds; var progLang = GetProgramingLanguage(environmentPath); string languageCompiler = null, sourceFileExtension = null, languageRuntime, runableFileExtension; bool interpretedLanguage = false; if (progLang == ProgramingLanguage.CSharp) { languageCompiler = "csc"; sourceFileExtension = ".cs"; languageRuntime = ""; runableFileExtension = ".exe"; } else if (progLang == ProgramingLanguage.Java) { languageCompiler = "javac"; sourceFileExtension = ".java"; languageRuntime = "java"; runableFileExtension = ""; } else if (progLang == ProgramingLanguage.Python) { interpretedLanguage = true; languageRuntime = "python"; runableFileExtension = ".py"; } else { throw new ExecutionServiceException("Unsupported programing language."); } if (!interpretedLanguage) { CompileCode(environmentPath, languageCompiler, sourceFileExtension); } var testCases = GetTestCases(environmentPath); foreach (var testCase in testCases) { ExecuteTestCase(testCase, environmentPath, languageRuntime, runableFileExtension); } var result = new ExecutionResult { FailedTestCount = testCases.Count(t => !t.IsSuccessful), SuccessfulTestCount = testCases.Count(t => t.IsSuccessful), TestCases = testCases.Where(t => !t.IsHidden) .Select(t => new ExecutionTestResult { No = t.No, IsSuccessful = t.IsSuccessful, UserOutput = t.UserOutput }) }; Console.WriteLine("********************************************************"); Console.WriteLine("ID : " + userId + " / Score : " + result.SuccessfulTestCount); foreach (var testCase in testCases) { Console.WriteLine("TestCase No : " + testCase.No + " / Argument : " + testCase.Arguments + " / Expected : " + testCase.ExpectedOutput + " / UserOutput : " + testCase.UserOutput + " / isHidden : " + testCase.IsHidden); } Console.WriteLine("********************************************************"); return(result); #region LOCAL FUNCTION DECLERATIONS ProgramingLanguage GetProgramingLanguage(string environmentPath) { if (!File.Exists(environmentPath + _ds + _environmentSettings)) { throw new ExecutionServiceException("EnvironmentSettings file does not exist."); } string progLang = File.ReadAllText(environmentPath + _environmentSettings, Encoding.UTF8); ProgramingLanguage result; if (!Enum.TryParse(progLang, out result)) { throw new ExecutionServiceException("Undefined programing language."); } return(result); } void CompileCode(string environmentPath, string languageCompiler, string sourceFileExtension) { var processInfo = new ProcessStartInfo("cmd", "/c cd " + environmentPath + " & " + languageCompiler + " " + _mainFileName + sourceFileExtension) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var process = new Process { StartInfo = processInfo }; process.Start(); DateTime timer = DateTime.Now.AddSeconds(compileTimeLimit); // 5 saniye çalışma süresi atanıyor. while (!process.WaitForExit(200)) { // calismasi için ayrilan sureyi kontrol ediyor. if (timer < DateTime.Now) { process.Kill(); throw new ExecutionServiceException("Code took too long to compile."); } } string error = process.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { throw new ExecutionServiceException("Code didn't compile."); } string output = process.StandardOutput.ReadToEnd(); if (output.Contains("error")) { throw new ExecutionServiceException(output); } } IEnumerable <ExecutionTestCase> GetTestCases(string environmentPath) { var testCases = new List <ExecutionTestCase>(); string[] ExecutionTestCases = null; if (File.Exists(environmentPath + _ds + _testCases)) { ExecutionTestCases = File.ReadAllText(environmentPath + _testCases, Encoding.UTF8).Split(new string[] { _spliter }, StringSplitOptions.None); } for (int i = 0; i < ExecutionTestCases.Length - 1; i += 4) { testCases.Add(new ExecutionTestCase { No = int.Parse(ExecutionTestCases[i]), Arguments = ExecutionTestCases[i + 1], ExpectedOutput = ExecutionTestCases[i + 2], IsHidden = bool.Parse(ExecutionTestCases[i + 3]), UserOutput = null }); } return(testCases); } void ExecuteTestCase(ExecutionTestCase testCase, string environmentPath, string languageRuntime, string runableFileExtension) { // create the ProcessStartInfo using "cmd" as the program to be run, // and "/c " as the parameters. // Incidentally, /c tells cmd that we want it to execute the command that follows, // and then exit. var runCommand = languageRuntime + " " + _mainFileName + runableFileExtension; var processInfo = new ProcessStartInfo("cmd", "/c " + "cd " + environmentPath + " & " + runCommand + " " + testCase.Arguments); // The following commands are needed to redirect the standard output. // This means that it will be redirected to the Process.StandardOutput StreamReader. processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.UseShellExecute = false; // Do not create the black window. processInfo.CreateNoWindow = true; // Now we create a process, assign its ProcessStartInfo and start it Process proc = new Process(); proc.StartInfo = processInfo; proc.Start(); DateTime timer = DateTime.Now.AddSeconds(executeTimeLimit); // 5 saniye çalışma süresi atanıyor. while (!proc.WaitForExit(250)) { // calismasi için ayrilan sureyi kontrol ediyor. if (timer < DateTime.Now) { proc.Kill(); throw new ExecutionServiceException("Code took too long to execute."); //return kod 5 saniyeden uzun sürdü. ***** } } // Get the output into a string string consoleOutput = proc.StandardOutput.ReadToEnd(); //Console.WriteLine(consoleOutput); string error = proc.StandardError.ReadToEnd(); consoleOutput = consoleOutput.Replace("\r", ""); if (!string.IsNullOrEmpty(error)) { testCase.UserOutput = error; } else { testCase.UserOutput = consoleOutput; if (testCase.ExpectedOutput.Equals(consoleOutput)) { testCase.IsSuccessful = true; } } } #endregion }
public void ProcessExecutionResult(WorkflowInstance workflow, WorkflowDefinition def, ExecutionPointer pointer, WorkflowStep step, ExecutionResult result, WorkflowExecutorResult workflowResult) { pointer.PersistenceData = result.PersistenceData; pointer.Outcome = result.OutcomeValue; if (result.SleepFor.HasValue) { pointer.SleepUntil = _datetimeProvider.Now.ToUniversalTime().Add(result.SleepFor.Value); pointer.Status = PointerStatus.Sleeping; } if (!string.IsNullOrEmpty(result.EventName)) { pointer.EventName = result.EventName; pointer.EventKey = result.EventKey; pointer.Active = false; pointer.Status = PointerStatus.WaitingForEvent; workflowResult.Subscriptions.Add(new EventSubscription() { WorkflowId = workflow.Id, StepId = pointer.StepId, EventName = pointer.EventName, EventKey = pointer.EventKey, SubscribeAsOf = result.EventAsOf }); } if (result.Proceed) { pointer.Active = false; pointer.EndTime = _datetimeProvider.Now.ToUniversalTime(); pointer.Status = PointerStatus.Complete; foreach (var outcomeTarget in step.Outcomes.Where(x => object.Equals(x.GetValue(workflow.Data), result.OutcomeValue) || x.GetValue(workflow.Data) == null)) { workflow.ExecutionPointers.Add(_pointerFactory.BuildNextPointer(def, pointer, outcomeTarget)); } _eventPublisher.PublishNotification(new StepCompleted() { EventTimeUtc = _datetimeProvider.Now, Reference = workflow.Reference, ExecutionPointerId = pointer.Id, StepId = step.Id, WorkflowInstanceId = workflow.Id, WorkflowDefinitionId = workflow.WorkflowDefinitionId, Version = workflow.Version }); } else { foreach (var branch in result.BranchValues) { foreach (var childDefId in step.Children) { workflow.ExecutionPointers.Add(_pointerFactory.BuildChildPointer(def, pointer, childDefId, branch)); } } } }
public override ExecutionResult Run(IStepExecutionContext context) { logger.LogInformation("Undoing Task 3"); return(ExecutionResult.Next()); }
private void SetResult(bool bSuccess) { if (bSuccess) { if (mRejectAmount == 0) mResult = ExecutionResult.Executed; else mResult = (mTrades.Count == 0 && mClosedTrades.Count == 0) ? ExecutionResult.FullyRejected : ExecutionResult.PartialRejected; } else mResult = ExecutionResult.Canceled; if (OrderCompleted != null) OrderCompleted(this, EventArgs.Empty); }
/// <summary> /// Reports the outputs of process execution after post process to distinguish between produced outputs and /// outputs from cache when assigning affinity for IPC pips /// </summary> public void ReportProcessExecutionOutputs(ProcessRunnablePip runnableProcess, ExecutionResult executionResult) { Contract.Assert(runnableProcess.Step == PipExecutionStep.PostProcess); if (executionResult.Converged || runnableProcess.Process.IsStartOrShutdownKind) { // Converged results are cached so they are not considered for as execution outputs // Service start/shutdown pip outputs are not considered for IPC pip affinity return; } foreach (var directoryOutput in executionResult.DirectoryOutputs) { m_executedProcessOutputs.Add(directoryOutput.directoryArtifact); } foreach (var output in executionResult.OutputContent) { m_executedProcessOutputs.Add(output.fileArtifact); } }
public TestsResultResponse() { this.result = ExecutionResult.Failed; this.ResultDescription = string.Empty; }
public ascx_WSDL_Creation_and_Execution buildGui() { var topPanel = this.add_Panel(); topPanel.insert_Below(100).add_LogViewer(); //var assemblyInvoke = topPanel.add_Control<O2.External.SharpDevelop.Ascx.ascx_AssemblyInvoke>(); //assemblyInvoke.loadAssembly("OnlineStorage.dll".assembly()); //var methodProperties = topPanel.add_DataGridView(); TestWebServices = topPanel.insert_Above(22).add_ComboBox(); WsdlLocation = topPanel.insert_Above(22) .add_LabelAndTextAndButton("Load Custom WSDL from location (file or url)", "", "Load", (value) => open(value)) .control <TextBox>(); ExtraWsdlParameres = topPanel.insert_Above(22).add_Label("Extra wsdl.exe parameters").left(WsdlLocation.Left).top(2) .append_TextBox("").align_Right(topPanel); Methods_TreeView = topPanel.insert_Left(300, "Soap Methods").add_TreeView().sort(); ExecutionResult = topPanel.insert_Below(150).add_GroupBox("Web Service Invocation Response Data").add_TextArea(); ExecutionResult_Properties = ExecutionResult.insert_Right().add_PropertyGrid().helpVisible(false); ExecutionResult_TreeView = ExecutionResult_Properties.insert_Below().add_TreeView(); ExecuteSoapRequest_Button = topPanel.insert_Below(40) .add_Button("Execute Soap request") .font_bold() .fill(); var methodProperties = topPanel.add_GroupBox("Request Data").add_Control <ctrl_ObjectViewer>(); //methodProperties.showSerializedString().createObjectWhenNull().simpleView(); methodProperties.createObjectWhenNull().simpleView(); Methods_TreeView.afterSelect <MethodInfo>( (methodInfo) => { CurrentMethod = methodInfo; "Current Method: {0}".info(CurrentMethod.Name); "Current Method: Signature = {0}".info(CurrentMethod.str()); "Current Method: DeclaringType = {0}".info(CurrentMethod.DeclaringType.FullName); SoapParametersObject = methodInfo.create_LiveObject_From_MethodInfo_Parameters("Soap_Invocation_Parameters"); if (SoapParametersObject.notNull()) { methodProperties.visible(true); methodProperties.show(SoapParametersObject); } else { methodProperties.visible(false); } //new O2FormsReflectionASCX().loadMethodInfoParametersInDataGridView(methodInfo, methodProperties); }); ExecuteSoapRequest_Button.onClick( () => { //var parameters = new O2FormsReflectionASCX().getParameterObjectsFromDataGridColumn(methodProperties, "Value"); var invocationParameters = new List <object>(); foreach (var property in SoapParametersObject.type().properties()) { invocationParameters.add(SoapParametersObject.property(property.Name)); } ExecutionResult.set_Text("[{0}] Executing method : {1}".line().format(DateTime.Now, CurrentMethod.Name)); var liveObject = CurrentMethod.DeclaringType.ctor(); ExecutionResult.append_Line("Created dynamic proxy object of type: {0}".format(liveObject)); try { var o2Timer = new O2Timer("Method execution time: ").start(); ResultObject = CurrentMethod.Invoke(liveObject, invocationParameters.ToArray()); ExecutionResult.append_Line("Method execution time: {0}".format(o2Timer.stop())); ExecutionResult.append_Line("Method Executed OK, here is the return value:"); ExecutionResult.append_Line(ResultObject.str().lineBeforeAndAfter()); ExecutionResult_Properties.show(ResultObject); //ExecutionResult_TreeView.xmlShow(ResultObject.serialize()); } //catch(System.Web.Services.Protocols.SoapException ex) //{ //} catch (Exception ex) { if (ex.InnerException.notNull()) { var detail = (ex.InnerException.property("Detail") as System.Xml.XmlElement); if (detail.notNull()) { ExecutionResult.append_Line(detail.OuterXml); } ExecutionResult.append_Line(ex.InnerException.Message); ExecutionResult.append_Line(ex.InnerException.StackTrace); } else { ex.log(); } //show.info(ex); //ex.details(); } //currentMethod.invoke(parameters); ExecutionResult.append_Line("Execution complete"); }); Methods_TreeView.insert_Below(20) .add_CheckBox("Show Full Method Signatures", 0, 0, (value) => ShowFullMethodSignatures = value) .autoSize() .parent <Panel>() .add_CheckBox("Cache WSDL Dll", 0, 200, (value) => Cache_WSDL_Dll = value) .autoSize() .check(); //.append_Link("Delete cached compiled dll", deleteCachedFile); ExecutionResult.insert_Below(20) .add_Link("View serialized string of response object", 0, 0, () => { var serializedResponse = ResultObject.serialize(false); if (serializedResponse.notNull()) { "".showInCodeViewer().set_Text(serializedResponse, "a.xml"); } }); addScriptingSupport(); add_TestWebServices(); return(this); }
public ExecutionResult HandleMessage(string message, Player player) { if (player.PlayerFlag != PlayerFlag.LOAD_GAME.ToString()) { player.PlayerMenuContext = player.PlayerFlag.ToString(); player.PlayerFlag = PlayerFlag.LOAD_GAME.ToString(); return(ExecutionResultHelper.SingleMessage("Select a game save to load", GetOptions(player))); } else if (message == Messages.Return) { player.PlayerMenuContext2 = "0"; if (player.PlayerMenuContext == PlayerFlag.GAME_MENU.ToString()) { return(MessageHandlerHelpers.ReturnToGameMenu(player, "")); } return(MessageHandlerHelpers.ReturnToMainMenu(player)); } else if (message.StartsWith("<")) { if (int.TryParse(player.PlayerMenuContext2, out int pageNumber)) { if (pageNumber <= 0) { pageNumber = 1; } player.PlayerMenuContext2 = "" + (pageNumber - 1); } else { player.PlayerMenuContext2 = "0"; } return(ExecutionResultHelper.SingleMessage("Select a game save to load", GetOptions(player))); } else if (message.StartsWith(">")) { if (int.TryParse(player.PlayerMenuContext2, out int pageNumber)) { if (pageNumber < 0) { pageNumber = 0; } player.PlayerMenuContext2 = "" + (pageNumber + 1); } else { player.PlayerMenuContext2 = "" + player.GameSaves.Count / PageSize; } return(ExecutionResultHelper.SingleMessage("Select a game save to load", GetOptions(player))); } else { var saveIdString = message.Split(' ')[0]; if (!int.TryParse(saveIdString, out var saveId)) { return(ExecutionResultHelper.SingleMessage("Invalid save specified", GetOptions(player))); } var gameSave = _gameSaveService.GetGameSaveById(saveId, player.PlayerId)?.PlayerGameSave; if (gameSave == null) { return(ExecutionResultHelper.SingleMessage($"Save with ID {saveId} is invalid. Either it doesn't exist, or it doesn't belong to you!", GetOptions(player))); } player.PlayerMenuContext2 = "0"; player.ActiveGameSave.GameName = gameSave.GameName; player.ActiveGameSave.GameSaveData = gameSave.GameSaveData.Select(a => new PlayerGameSaveData { Name = a.Name, Value = a.Value }).ToList(); player.ActiveGameSave.StateId = gameSave.StateId; player.ActiveGameSave.FrameStack = gameSave.FrameStack.Select(a => new PlayerFrameStack { CreatedDate = a.CreatedDate, FunctionName = a.FunctionName, ReturnStateId = a.ReturnStateId, Save = player.ActiveGameSave, SaveId = player.ActiveGameSave.SaveId }).ToList(); player.PlayerFlag = PlayerFlag.IN_GAME.ToString(); var games = _gameStore.ListGames(); var playerState = player.ActiveGameSave; var gameFound = games.Where(a => a.GameName == playerState.GameName).FirstOrDefault(); var state = gameFound.FindStateById(playerState.StateId); var execResult = new ExecutionResult { MessagesToShow = new List <MessageResult> { new MessageResult { Message = _textParsing.ParseText(playerState, state.StateText) } }, OptionsToShow = _gameProcessor.GetCurrentOptions(playerState, gameFound, state) }; execResult.OptionsToShow.Add("-Menu-"); return(execResult); } }
public override ExecutionResult Run(IStepExecutionContext context) { TaskATicker++; return(ExecutionResult.Outcome(true)); }
public async Task EnqueuesARescheduleIfTheResultRequestsIt(ExecutionResult result) { // Arrange var cts = new CancellationTokenSource(); var runner = new TestableJobRunner(TimeSpan.FromSeconds(5)); var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary<string, string>()); var repeat = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary<string,string>()); runner.MockDispatcher .Setup(d => d.Dispatch(It.IsAny<InvocationContext>())) .Completes(new InvocationResult(result, result == ExecutionResult.Faulted ? new Exception() : null, TimeSpan.FromDays(365))) .Verifiable(); runner.MockQueue .Setup(q => q.Enqueue("test", Constants.Source_RepeatingJob, It.IsAny<Dictionary<string, string>>(), TimeSpan.FromDays(365), null)) .Completes(repeat); // Act await runner.Dispatch(invocation, cts.Token); // Assert runner.MockQueue.Verify(q => q.Enqueue(invocation.Job, Constants.Source_RepeatingJob, invocation.Payload, TimeSpan.FromDays(365), null)); }
public static ExecutionResult ExecuteActions(List <Action> Actions) { ExecutionResult SNDBSResult = ExecutionResult.TasksSucceeded; if (Actions.Count > 0) { string SCERoot = Environment.GetEnvironmentVariable("SCE_ROOT_DIR"); string SNDBSExecutable = Path.Combine(SCERoot, "Common/SN-DBS/bin/dbsbuild.exe"); // Check that SN-DBS is available bool bSNDBSExists = File.Exists(SNDBSExecutable); if (bSNDBSExists == false) { return(ExecutionResult.Unavailable); } // Use WMI to figure out physical cores, excluding hyper threading. int NumCores = 0; if (!Utils.IsRunningOnMono) { try { using (var Mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor")) { var MosCollection = Mos.Get(); foreach (var Item in MosCollection) { NumCores += int.Parse(Item["NumberOfCores"].ToString()); } } } catch (Exception Ex) { Log.TraceWarning("Unable to get the number of Cores: {0}", Ex.ToString()); Log.TraceWarning("Falling back to processor count."); } } // On some systems this requires a hot fix to work so we fall back to using the (logical) processor count. if (NumCores == 0) { NumCores = System.Environment.ProcessorCount; } // The number of actions to execute in parallel is trying to keep the CPU busy enough in presence of I/O stalls. MaxActionsToExecuteInParallel = 0; // The CPU has more logical cores than physical ones, aka uses hyper-threading. if (NumCores < System.Environment.ProcessorCount) { MaxActionsToExecuteInParallel = (int)(NumCores * BuildConfiguration.ProcessorCountMultiplier); } // No hyper-threading. Only kicking off a task per CPU to keep machine responsive. else { MaxActionsToExecuteInParallel = NumCores; } MaxActionsToExecuteInParallel = Math.Min(MaxActionsToExecuteInParallel, BuildConfiguration.MaxProcessorCount); JobNumber = 1; Dictionary <Action, ActionThread> ActionThreadDictionary = new Dictionary <Action, ActionThread>(); while (true) { bool bUnexecutedActions = false; foreach (Action Action in Actions) { ActionThread ActionThread = null; bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread); if (bFoundActionProcess == false) { bUnexecutedActions = true; ExecutionResult CompileResult = ExecuteActions(Actions, ActionThreadDictionary); if (CompileResult != ExecutionResult.TasksSucceeded) { return(ExecutionResult.TasksFailed); } break; } } if (bUnexecutedActions == false) { break; } } Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "-------- Begin Detailed Action Stats ----------------------------------------------------------"); Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "^Action Type^Duration (seconds)^Tool^Task^Using PCH"); double TotalThreadSeconds = 0; // Check whether any of the tasks failed and log action stats if wanted. foreach (KeyValuePair <Action, ActionThread> ActionProcess in ActionThreadDictionary) { Action Action = ActionProcess.Key; ActionThread ActionThread = ActionProcess.Value; // Check for pending actions, preemptive failure if (ActionThread == null) { SNDBSResult = ExecutionResult.TasksFailed; continue; } // Check for executed action but general failure if (ActionThread.ExitCode != 0) { SNDBSResult = ExecutionResult.TasksFailed; } // Log CPU time, tool and task. double ThreadSeconds = Action.Duration.TotalSeconds; Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "^{0}^{1:0.00}^{2}^{3}^{4}", Action.ActionType.ToString(), ThreadSeconds, Path.GetFileName(Action.CommandPath), Action.StatusDescription, Action.bIsUsingPCH); // Update statistics switch (Action.ActionType) { case ActionType.BuildProject: UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds; break; case ActionType.Compile: UnrealBuildTool.TotalCompileTime += ThreadSeconds; break; case ActionType.CreateAppBundle: UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds; break; case ActionType.GenerateDebugInfo: UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds; break; case ActionType.Link: UnrealBuildTool.TotalLinkTime += ThreadSeconds; break; default: UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds; break; } // Keep track of total thread seconds spent on tasks. TotalThreadSeconds += ThreadSeconds; } Log.TraceInformation("-------- End Detailed Actions Stats -----------------------------------------------------------"); // Log total CPU seconds and numbers of processors involved in tasks. Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo, TraceEventType.Information, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds); } return(SNDBSResult); }
private static ExecutionResult Execute (string command, params string[] arguments) { Process process = new Process (); process.EnableRaisingEvents = true; process.StartInfo.FileName = command; process.StartInfo.Arguments = string.Join (" ", arguments, 0, arguments.Length); // flags to be able to read build script output process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; ExecutionResult result = new ExecutionResult (); try { process.Start (); process.WaitForExit (); result.output = process.StandardOutput.ReadToEnd (); result.error = process.StandardError.ReadToEnd (); result.success = string.IsNullOrEmpty (result.error); } catch (System.Exception exception) { result.exception = exception; result.success = false; } return result; }
internal static ExecutionResult ExecuteLocalActions(List <Action> InLocalActions, Dictionary <Action, ActionThread> InActionThreadDictionary, int TotalNumJobs) { // Time to sleep after each iteration of the loop in order to not busy wait. const float LoopSleepTime = 0.1f; ExecutionResult LocalActionsResult = ExecutionResult.TasksSucceeded; while (true) { // Count the number of pending and still executing actions. int NumUnexecutedActions = 0; int NumExecutingActions = 0; foreach (Action Action in InLocalActions) { ActionThread ActionThread = null; bool bFoundActionProcess = InActionThreadDictionary.TryGetValue(Action, out ActionThread); if (bFoundActionProcess == false) { NumUnexecutedActions++; } else if (ActionThread != null) { if (ActionThread.bComplete == false) { NumUnexecutedActions++; NumExecutingActions++; } } } // If there aren't any pending actions left, we're done executing. if (NumUnexecutedActions == 0) { break; } // If there are fewer actions executing than the maximum, look for pending actions that don't have any outdated // prerequisites. foreach (Action Action in InLocalActions) { ActionThread ActionProcess = null; bool bFoundActionProcess = InActionThreadDictionary.TryGetValue(Action, out ActionProcess); if (bFoundActionProcess == false) { if (NumExecutingActions < Math.Max(1, MaxActionsToExecuteInParallel)) { // Determine whether there are any prerequisites of the action that are outdated. bool bHasOutdatedPrerequisites = false; bool bHasFailedPrerequisites = false; foreach (FileItem PrerequisiteItem in Action.PrerequisiteItems) { if (PrerequisiteItem.ProducingAction != null && InLocalActions.Contains(PrerequisiteItem.ProducingAction)) { ActionThread PrerequisiteProcess = null; bool bFoundPrerequisiteProcess = InActionThreadDictionary.TryGetValue(PrerequisiteItem.ProducingAction, out PrerequisiteProcess); if (bFoundPrerequisiteProcess == true) { if (PrerequisiteProcess == null) { bHasFailedPrerequisites = true; } else if (PrerequisiteProcess.bComplete == false) { bHasOutdatedPrerequisites = true; } else if (PrerequisiteProcess.ExitCode != 0) { bHasFailedPrerequisites = true; } } else { bHasOutdatedPrerequisites = true; } } } // If there are any failed prerequisites of this action, don't execute it. if (bHasFailedPrerequisites) { // Add a null entry in the dictionary for this action. InActionThreadDictionary.Add(Action, null); } // If there aren't any outdated prerequisites of this action, execute it. else if (!bHasOutdatedPrerequisites) { ActionThread ActionThread = new ActionThread(Action, JobNumber, TotalNumJobs); ActionThread.Run(); InActionThreadDictionary.Add(Action, ActionThread); NumExecutingActions++; JobNumber++; } } } } System.Threading.Thread.Sleep(TimeSpan.FromSeconds(LoopSleepTime)); } return(LocalActionsResult); }