/// <summary> /// Initializes console properties and sets up environment. /// </summary> internal virtual void Start() { Initialize(); In = string.Empty; Out = new ConsoleWriter(); consoleBuffer = Header; if (consoleBuffer != "") Out.WriteLine(consoleBuffer); scrollPosition = Vector2.zero; ID = IDCount++; this.consoleID = "window" + ID; history = new List<string>(); }
/// <summary> /// Raised when a new Bar Arrives from the Gateway /// </summary> /// <param name="bar">TradeHub Bar Message</param> private void OnLiveBarArrived(Bar bar) { try { if (Logger.IsInfoEnabled) { Logger.Info("Bar Arrived for Market Data Simulator: " + bar, _type.FullName, "OnLiveBarArrived"); } // Raise Bar Event if (BarArrived != null) { string key = bar.Security.Symbol + bar.MarketDataProvider; Tuple <string, string> subscribedBar = _subscribedBars[key]; BarArrived(bar, subscribedBar.Item1); } } catch (Exception exception) { ConsoleWriter.WriteLine(ConsoleColor.DarkRed, exception.ToString()); Logger.Error(exception, _type.FullName, "OnLiveBarArrived"); } }
public ConsoleCommandResult Execute(ParameterCollection parameterCollection) { switch (parameterCollection[0]) { case "check": int id = Convert.ToInt32(parameterCollection[1]); BucketListRepository repo = new BucketListRepository(); bool isChecked = repo.Check(id); if (isChecked) { ConsoleWriter.WriteLine($"Checked entry with Id {id}", ConsoleColor.Green); } else { ConsoleWriter.WriteLine($"Could not check entry with Id {id}", ConsoleColor.Yellow); } break; default: return(ConsoleCommandResult.BadInvoke); } return(ConsoleCommandResult.Success); }
/// <summary> /// Called when New Bar is received /// </summary> /// <param name="bar">TradeHub Bar containing latest info</param> public override void OnBarArrived(Bar bar) { try { ConsoleWriter.WriteLine(ConsoleColor.Green, "New bar received : " + bar); if (Logger.IsInfoEnabled) { Logger.Info("New bar received : " + bar, _type.FullName, "OnBarArrived"); } Task.Factory.StartNew(() => { InitiateTrade(bar); }, TaskCreationOptions.PreferFairness); //ThreadPool.QueueUserWorkItem(new WaitCallback(InitiateTrade),bar); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "OnBarArrived"); } }
static void Main() { var input = ConsoleReader.ReadLine(); var gameController = new GameController(); var result = new StringBuilder(); while (!input.Equals("Enough! Pull back!")) { try { gameController.GiveInputToGameController(input); } catch (ArgumentException arg) { result.AppendLine(arg.Message); } input = ConsoleReader.ReadLine(); } var finalResult = gameController.RequestResult(result.ToString()); ConsoleWriter.WriteLine(finalResult); }
private string UserChoseReplace(string project, string oldReference, List <string> withSameName) { ConsoleWriter.WriteWarning($"{project}\n\tMultiple choise for replace '{oldReference}':"); withSameName = new[] { "don't replace" }.Concat(withSameName).ToList(); for (int i = 0; i < withSameName.Count; i++) { ConsoleWriter.WriteLine($"\t{i}. {withSameName[i].Replace("/", "\\")}"); } ConsoleWriter.WriteLine($"Print 0-{withSameName.Count - 1} for choose"); var answer = Console.ReadLine(); int index; if (int.TryParse(answer, out index)) { answer = index <= 0 || index >= withSameName.Count() ? null : withSameName[index]; } else { answer = null; } return(answer); }
public void Print() { if (NoYamlModules.Any()) { ConsoleWriter.WriteWarning("No 'install' section in modules:"); foreach (var m in NoYamlModules) { ConsoleWriter.WriteBuildWarning("\t- " + m); } } foreach (var key in Replaced.Keys) { if (!Replaced[key].Any()) { continue; } ConsoleWriter.WriteOk(key + " replaces:"); foreach (var value in Replaced[key]) { ConsoleWriter.WriteLine("\t" + value); } } foreach (var key in NotFound.Keys) { if (!NotFound[key].Any()) { continue; } ConsoleWriter.WriteError(key + "\n\tnot found references in install/artifacts section of any module:"); foreach (var value in NotFound[key]) { ConsoleWriter.WriteLine("\t" + value); } } }
/// <summary> /// Sends market order to the Order Execution Service /// </summary> /// <param name="orderSide">Order side on which to open position</param> /// <param name="symbol">Symbol on which to send order</param> /// <param name="price"> </param> /// <param name="dateTime"> </param> private void SendLimitOrder(string orderSide, string symbol, decimal price, DateTime dateTime) { try { if (!orderSide.Equals(TradeHubConstants.OrderSide.NONE)) { _entryOrderSent = true; ConsoleWriter.WriteLine(ConsoleColor.Green, "Sending" + orderSide + " limit order."); if (Logger.IsInfoEnabled) { Logger.Info("Sending" + orderSide + " entry order.", _type.FullName, "SendLimtOrder"); } // Get new unique ID var id = (_orderId++).ToString("X"); Security security = new Security { Symbol = symbol }; // Create new Limit Order LimitOrder limitOrder = OrderMessage.GenerateLimitOrder(id, security, TradeHubConstants.OrderSide.BUY, 100, price , _orderExecutionProvider); limitOrder.OrderDateTime = dateTime; // Send Limit Order to OEE SendOrder(limitOrder); } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "SendLimtOrder"); } }
/// <summary> /// Called when Order Execution is received /// </summary> /// <param name="execution">TradeHub Execution</param> public override void OnExecutionArrived(Execution execution) { try { ConsoleWriter.WriteLine(ConsoleColor.Green, "Order Execution received : " + execution); if (Logger.IsInfoEnabled) { Logger.Info("Order Execution received : " + execution, _type.FullName, "OnExecutionArrived"); } // Resart trading algo on full fill of Exit order if (execution.Fill.LeavesQuantity.Equals(0)) { if (_entryOrderSent) { _entryOrderSent = false; // Get Order Side for Exit Order var orderSide = execution.Order.OrderSide.Equals(TradeHubConstants.OrderSide.BUY) ? TradeHubConstants.OrderSide.SELL : TradeHubConstants.OrderSide.BUY; // Send Exit Order SendExitOrder(orderSide, execution.Order.Security.Symbol); } else if (_exitOrderSent) { _exitOrderSent = false; } } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "OnExecutionArrived"); } }
private void PrintStatus(GitRepository repo) { try { if (!repo.HasLocalChanges() && repo.ShowUnpushedCommits().Length == 0) { return; } ConsoleWriter.WriteInfo(repo.ModuleName); if (repo.HasLocalChanges()) { ConsoleWriter.WriteLine(repo.ShowLocalChanges()); } if (repo.ShowUnpushedCommits().Length > 0) { ConsoleWriter.WriteLine(repo.ShowUnpushedCommits()); } } catch (Exception) { // ignored } }
/// <summary> /// Raised when Order with status New/Submitted is received /// </summary> /// <param name="order">TradeHub Order</param> private void OnNewArrived(Order order) { try { if (Logger.IsInfoEnabled) { Logger.Info("Order Status New received.", _type.FullName, "OnNewArrived"); } Order origOrder; if (_newOrders.TryGetValue(order.OrderID, out origOrder)) { // Remove from waiting map _newOrders.Remove(order.OrderID); // Add to Accepted orders map _acceptedOrders.Add(order.OrderID, origOrder); origOrder.OrderStatus = TradeHubConstants.OrderStatus.SUBMITTED; // Raise Event if (NewArrived != null) { NewArrived((Order)origOrder.Clone()); } return; } ConsoleWriter.WriteLine(ConsoleColor.Red, "No request received for Order with ID: " + order.OrderID); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "OnNewArrived"); } }
/// <summary> /// Sends Limit Order on the given Order Execution Provider /// </summary> /// <param name="limitOrder">TradeHub LimitOrder</param> public void SendLimitOrder(LimitOrder limitOrder) { try { if (Logger.IsInfoEnabled) { Logger.Info("Limit Order request received: " + limitOrder, _type.FullName, "SendLimitOrder"); ConsoleWriter.WriteLine(ConsoleColor.Green, "Limit order request received: " + limitOrder); } // Add to new orders map if (!(_newOrders.ContainsKey(limitOrder.OrderID) || _acceptedOrders.ContainsKey(limitOrder.OrderID))) { _newOrders.Add(limitOrder.OrderID, limitOrder); { Order order = new Order(TradeHubConstants.OrderExecutionProvider.Simulated); // Add Order ID order.OrderID = limitOrder.OrderID; // Set Order status order.OrderStatus = TradeHubConstants.OrderStatus.SUBMITTED; // Send information OnNewArrived(order); } return; } ConsoleWriter.WriteLine(ConsoleColor.Red, "Order with same ID already exists"); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "SendLimitOrder"); } }
private void CreatePositionMessage(string[] message) { try { //create Position if (ValidatePositionFields(message)) { Position position = new Position(); position.Provider = TradeHubConstants.OrderExecutionProvider.Simulated; position.Security = new Security() { Symbol = message[1] }; position.Quantity = long.Parse(message[2]); position.ExitValue = decimal.Parse(message[3]); position.Price = decimal.Parse(message[4]); position.AvgBuyPrice = decimal.Parse(message[5]); position.AvgSellPrice = decimal.Parse(message[6]); position.IsOpen = position.Quantity != 0; position.Type = (position.Quantity > 0) ? PositionType.Long : PositionType.Short; if (position.Quantity == 0) { position.Type = PositionType.Flat; } if (PositionArrived != null) { PositionArrived(position); } } } catch (Exception exception) { ConsoleWriter.WriteLine(ConsoleColor.DarkRed, exception.ToString()); Logger.Error(exception, _type.FullName, "CreatePositionMessage"); } }
public void Run() { IReader reader = new ConsoleReader(); IWriter writer = new ConsoleWriter(); string input = reader.ReadLine(); GameController gameController = new GameController(); StringBuilder result = new StringBuilder(); while (!input.Equals("Enough! Pull back!")) { try { gameController.GiveInputToGameController(input); } catch (ArgumentException) { } input = reader.ReadLine(); } result.AppendLine(gameController.RequestResult()); writer.WriteLine(result.ToString().Trim()); }
public void ShowHighScores(ICollection <HighScore> highScores) { StringBuilder highScoresStringBuilder = new StringBuilder(); if (highScores.Count > 0) { highScoresStringBuilder.AppendLine(Constants.Highscores); highScoresStringBuilder.AppendLine(Constants.BestHighScoresProperties); foreach (var h in highScores) { highScoresStringBuilder.AppendLine($"{h.User.Name,-10} | {h.Points,-5}"); } } else { highScoresStringBuilder.AppendLine(Constants.NoScoresToShow); } highScoresStringBuilder.AppendLine(); highScoresStringBuilder.AppendLine(Constants.EscapeToReturnToPreviousMenu); ConsoleWriter.WriteLine(highScoresStringBuilder.ToString()); while (Console.ReadKey().Key != ConsoleKey.Escape) { } }
public void Solve(ConsoleReader cr, ConsoleWriter cw) { int n = cr; int m = cr; var g = new SccGraph(n); for (int i = 0; i < m; i++) { int u = cr; int v = cr; g.AddEdge(u, v); } var scc = g.SCC(); cw.WriteLine(scc.Length); foreach (var v in scc) { cw.StreamWriter.Write(v.Length); cw.StreamWriter.Write(' '); cw.WriteLineJoin(v); } }
private void RestoreBackup(string backupName) { string fileToRestore = $@"{BackupDirectoryName}\{backupName}{BackupFileExtension}"; FileInfo foundBackup = new FileInfo(fileToRestore); if (!foundBackup.Exists) { ConsoleWriter.WriteLine($"Cannot find backup with name {backupName}", ConsoleColor.Yellow); return; } if (File.Exists($@"{this._currentDirectory}\BucketList.db")) { ConsoleWriter.WriteLine("Restoring this backup will erase the current database. Continue? (y/n)", ConsoleColor.Red); ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key != ConsoleKey.Y) { return; } } try { FileInfo copiedFile = foundBackup.CopyTo($@"{this._currentDirectory}\BucketList.db", true); if (!copiedFile.Exists) { throw new FileNotFoundException(); } ConsoleWriter.WriteLine("Backup successfully restored"); } catch { ConsoleWriter.WriteLine($"Could not restore backup {backupName}", ConsoleColor.Red); } }
/// <summary> /// Unsubscribe Market data message /// </summary> public bool UnsubscribeTickData(Unsubscribe request) { try { if (Logger.IsInfoEnabled) { Logger.Info("Tick data unsusbcription request recieved for: " + request, _type.FullName, "UnsubscribeTickData"); } ConsoleWriter.WriteLine(ConsoleColor.Green, "Unsusbcribe request received for: " + request); // Remove Security from the List _subscribedSecurities.Remove(request.Security); return(true); } catch (Exception exception) { ConsoleWriter.WriteLine(ConsoleColor.DarkRed, exception.ToString()); Logger.Error(exception, _type.FullName, "UnsubscribeTickData"); return(false); } }
/// <summary> /// Return the corresponding process object based on the type of jenkins instance. /// </summary> /// <param name="fileName">the filename to be ran</param> /// <param name="arguments">the arguments for the process</param> /// <returns>the corresponding process type, based on the jenkins instance</returns> private object GetProcessTypeForCurrentSession(string fileName, string arguments) { try { if (!IsParentProcessRunningInUserSession()) { Process process = new Process(); InitProcess(process, fileName, arguments); return(process); } ConsoleWriter.WriteLine("Starting ParallelRunner from service session!"); // the process must be started in the user session ElevatedProcess elevatedProcess = new ElevatedProcess(fileName, arguments, Helper.GetSTInstallPath()); return(elevatedProcess); } catch (Exception) { return(null); } }
private void DispatchCommand(List <string> commandParams) { string command = commandParams[0]; commandParams.Remove(command); if (command == "RegisterHarvester") { string result = draftManager.RegisterHarvester(commandParams); outputWriter.WriteLine(result); } else if (command == "RegisterProvider") { string result = draftManager.RegisterProvider(commandParams); outputWriter.WriteLine(result); } else if (command == "Day") { string result = draftManager.Day(); outputWriter.WriteLine(result); } else if (command == "Mode") { string result = draftManager.Mode(commandParams); outputWriter.WriteLine(result); } else if (command == "Check") { string result = draftManager.Check(commandParams); outputWriter.WriteLine(result); } else if (command == Constants.INPUT_TERMINATING_COMMAND) { string result = draftManager.ShutDown(); outputWriter.WriteLine(result); this.isRunning = false; } }
/// <summary> /// протестировать на основе примеров из файла samples.txt /// </summary> public void TestSamples() { bool first = true; foreach (var line in File.ReadAllLines(Path.Combine(AppContext.BaseDirectory, "samples.txt"), System.Text.Encoding.UTF8)) { var str = line.Trim(); if (str.Length != 0) { if (str.StartsWith("#")) { // комментарий if (first) { first = false; } else { writer.WriteLine(); } writer.WriteLine("┌──────────────────────────────────────────────────────────────┐"); writer.WriteLine($"│ {str.Substring(1).TrimStart(),-60} │"); writer.WriteLine("└──────────────────────────────────────────────────────────────┘"); writer.WriteLine(); } else { var data = str.Split(new char[] { ' ', '\t' }, 2); if (int.TryParse(data[0], out var number)) { ParseNumber(data[1].TrimStart(), number); } } } } }
private static void PrintHelpFooter() { ConsoleWriter.WriteLine("Cement. 2017."); }
public MobilePhone(ConsoleWriter writer) { _writer = writer; _writer.WriteLine("Starting work with Mobile Phone", ConsoleColor.Cyan); }
public SearchPlaylistScreen() { var writer = new ConsoleWriter(0); writer.WriteLine( "Buscar playlist\n" + "---------------\n" ); if (playlistService.Count() > 0) { writer.Write("Escribe el ID o el Nombre de tu playlist: "); string option; string name = ""; option = ReadLine(); writer.WriteLine(""); // Si fue ID. if (Int32.TryParse(option, out int id)) { searchedPlaylist = playlistService.Get(id); } else // Si fue nombre { name = option; searchedPlaylist = playlistService.Find(p => p.Name.ToLower() == name.ToLower()); } if (searchedPlaylist != null) { writer.WriteLine( "[Playlist encontrada]\n" ); writer.WriteLine( $"- ID: {searchedPlaylist.Id}\n" + $"- Logo: {searchedPlaylist.Logo}\n" + $"- Nombre: {searchedPlaylist.Name}\n" + $"- Piezas ({searchedPlaylist.PieceList.Count} en total): \n" ); var pieces = searchedPlaylist.PieceList; // Printing pieces foreach (var piece in pieces) { writer.WriteLine( text: $"- ID: {piece.Id}, Nombre: {piece.Name}, Artista: {piece.Artist}", indent: 1 ); } } else { writer.WriteLine(">> Playlist no encontrada"); } } else { writer.WriteLine(">> No tienes playlists en tu lista <<"); } }
/// <summary> /// Returns the number of run vusers from VuserStateGraph graph /// </summary> /// <returns>Number of run vusers per catagory</returns> public static Dictionary <string, int> GetVusersCountByStatus(LrAnalysis lrAnalysis) { var vuserDictionary = new Dictionary <string, int>(4) { { "Passed", 0 }, { "Stopped", 0 }, { "Failed", 0 }, { "Error", 0 } }; lrAnalysis.Session.VUsers.LoadValuesIfNeeded(); Graph vUserGraph = lrAnalysis.Session.OpenGraph("VuserStateGraph"); if (vUserGraph == null) { return(vuserDictionary); } List <String> vUserStates = new List <String>() { { "Passed" }, { "Stopped" }, { "Failed" }, { "Error" } }; try { Console.Write("Counting vUser Results for this scenario from "); FilterItem filterDimensionVUser; FilterItem item; Series vuserRanSeries; vUserGraph.Filter.Reset(); Console.Write(vUserGraph.Name); if (vUserGraph.Filter.TryGetValue("Vuser Status", out filterDimensionVUser) && vUserGraph.Filter.TryGetValue("Vuser End Status", out item)) { filterDimensionVUser.ClearValues(); item.ClearValues(); Console.Write(" by "); foreach (string vUserEndStatus in item.AvailableValues.DiscreteValues) { item.ClearValues(); Console.Write(vUserEndStatus + " "); item.AddDiscreteValue(vUserEndStatus); vUserGraph.ApplyFilterAndGroupBy(); if (vUserGraph.Series.TryGetValue("Quit", out vuserRanSeries)) { if (!vuserRanSeries.GraphStatistics.IsFunctionAvailable(StatisticsFunctionKind.Maximum)) { continue; } double vUserTypeMax = vuserRanSeries.GraphStatistics.Maximum; if (!HasValue(vUserTypeMax)) { continue; } vuserDictionary[vUserEndStatus] = (int)Math.Round(vUserTypeMax); } } Console.WriteLine(""); } ConsoleWriter.WriteLine("Getting maximum ran vUsers this scenarion"); var vUserStateGraph = lrAnalysis.Session.OpenGraph("VuserStateGraph"); if (vUserStateGraph == null) { return(vuserDictionary); } vUserStateGraph.Granularity = 4; if (vUserStateGraph.Filter.TryGetValue("Vuser Status", out filterDimensionVUser) && vUserStateGraph.Series.TryGetValue("Run", out vuserRanSeries)) { filterDimensionVUser.ClearValues(); vUserGraph.ApplyFilterAndGroupBy(); double vUserMax = vuserRanSeries.GraphStatistics.Maximum; if (!HasValue(vUserMax)) { vUserMax = -1; } vuserDictionary.Add("MaxVuserRun", (int)Math.Round(vUserMax)); ConsoleWriter.WriteLine(String.Format("{0} maximum vUser ran per {1} seconds", vUserMax, vUserStateGraph.Granularity)); } } catch (StackOverflowException exception) { ConsoleWriter.WriteLine(String.Format("Debug: Error on getting VUsers from Analysis" + exception)); } return(vuserDictionary); }
private void LogErrorCount(LrScenario scenario) { int errorsCount = scenario.GetErrorsCount(""); ConsoleWriter.WriteLine("Error count: " + errorsCount); }
public RadioRecorder(ConsoleWriter writer) { _writer = writer; _writer.WriteLine("Starting work with Radio Recorder", ConsoleColor.Cyan); }
private void checkForErrors() { //init variables string message = null; XmlDocument errorsXML = new XmlDocument(); errorsXML.Load(Path.Combine(_resultsFolder, "errors.xml")); _errors = new Dictionary <string, ControllerError>(); //new unseen error(s) foreach (XmlNode errorNode in errorsXML.DocumentElement.ChildNodes) { message = errorNode.InnerText; //ControllerError cerror; //if error exist, just update the count: bool added = false; //check if the error is ignorable foreach (string ignoreError in _ignoreErrorStrings) { if (message.ToLowerInvariant().Contains(ignoreError.ToLowerInvariant())) { ConsoleWriter.WriteLine(string.Format(Resources.LrErrorIgnored, message, ignoreError)); if (_errors.ContainsKey(message)) { _errors[message].occurences++; } else { _errors.Add(message, new ControllerError { state = ERRORState.Ignore, occurences = 1 }); } added = true; _errorsCount++; } } //error was not ignored, and was not added yet. add it now. if (!added) { // non ignorable error message, ConsoleWriter.WriteErrLine(message);//+ ", time " + time + ", host: " + host + ", VuserID: " + vuserId + ", script: " + script + ", line: " + line); if (_errors.ContainsKey(message)) { _errors[message].occurences++; } else { _errors.Add(message, new ControllerError { state = ERRORState.Error, occurences = 1 }); } _errorsCount++; //if the scenario ended event was not registered, we need to provide the opportunity to check the vuser status. //if (!_scenarioEndedEvent) //{ break; //} } } ConsoleWriter.WriteErrLine("total number of errors: " + _errorsCount); }
private bool waitForScenario(ref string errorReason) { ConsoleWriter.WriteLine("Scenario run has started"); ThreadPool.QueueUserWorkItem(DoTask, autoEvent); //wait for the scenario to end gracefully: int time = _pollingInterval * 1000; if (_summaryDataLogger.IsAnyDataLogged()) { LogDataDuringScenarioExecution(); } while (_stopWatch.Elapsed <= _perScenarioTimeOutMinutes) { if (_runCancelled()) { errorReason = Resources.GeneralTimedOut; return(false); } if (autoEvent.WaitOne(time)) { break; } } if (_stopWatch.Elapsed > _perScenarioTimeOutMinutes) { _stopWatch.Stop(); errorReason = string.Format(Resources.LrScenarioTimeOut, _stopWatch.Elapsed.ToString("dd\\:hh\\:mm\\:ss")); ConsoleWriter.WriteErrLine(errorReason); } if (_scenarioEndedEvent) { try { //ConsoleWriter.WriteLine("unregistering event"); _engine.Events.ScenarioEvents.OnScenarioEnded -= ScenarioEvents_OnScenarioEnded; _scenarioEndedEvent = false; } catch { } } //if scenario not ended until now, force stop it. if (!_scenarioEnded) { int ret = _engine.Scenario.StopNow(); if (ret != 0) { errorReason = string.Format(Resources.LrStopScenarioEnded); return(false); } int tries = 2; while (_engine.Scenario.IsActive() && tries > 0) { //ConsoleWriter.WriteLine("\t\tScenario is still running. Waiting for the scenario to stop..."); Stopper wlrunStopper = new Stopper(_pollingInterval * 1000); wlrunStopper.Start(); tries--; } if (_engine.Scenario.IsActive()) { errorReason = Resources.LrControllerFailedToStop; return(false); } } return(true); }
private void generateAnalysisReport(TestRunResults runDesc) { string lrrLocation = Path.Combine(runDesc.ReportLocation, LRR_FOLDER, LRR_FOLDER + ".lrr"); string lraLocation = Path.Combine(runDesc.ReportLocation, LRA_FOLDER, LRA_FOLDER + ".lra"); string htmlLocation = Path.Combine(runDesc.ReportLocation, HTML_FOLDER, HTML_FOLDER + ".html"); ProcessStartInfo analysisRunner = new ProcessStartInfo(); analysisRunner.FileName = ANALYSIS_LAUNCHER; analysisRunner.Arguments = "\"" + lrrLocation + "\" \"" + lraLocation + "\" \"" + htmlLocation + "\" \"" + _analysisTemplate + "\""; analysisRunner.UseShellExecute = false; analysisRunner.RedirectStandardOutput = true; ConsoleWriter.WriteLine("executing Analysis launcher with arguments : " + analysisRunner.Arguments); ConsoleWriter.WriteLine("time for analysis: " + _perScenarioTimeOutMinutes.ToString(@"dd\:\:hh\:mm\:ss")); analysisRunner.RedirectStandardOutput = true; analysisRunner.RedirectStandardError = true; Process runner = Process.Start(analysisRunner); if (runner != null) { runner.OutputDataReceived += runner_OutputDataReceived; runner.ErrorDataReceived += runner_ErrorDataReceived; runner.BeginOutputReadLine(); runner.BeginErrorReadLine(); Stopwatch analysisStopWatch = Stopwatch.StartNew(); while (!runner.WaitForExit(_pollingInterval * 1000) && analysisStopWatch.Elapsed < _perScenarioTimeOutMinutes) { ; } analysisStopWatch.Stop(); runner.CancelOutputRead(); runner.CancelErrorRead(); ConsoleWriter.WriteLine("time passed: " + analysisStopWatch.Elapsed.ToString(@"dd\:\:hh\:mm\:ss")); if (analysisStopWatch.Elapsed > _perScenarioTimeOutMinutes) { runDesc.ErrorDesc = Resources.LrAnalysisTimeOut; ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); runDesc.TestState = TestState.Error; if (!runner.HasExited) { runner.Kill(); } } //ConsoleWriter.WriteLine("checking error code"); if (runner.ExitCode != (int)Launcher.ExitCodeEnum.Passed) { runDesc.ErrorDesc = Resources.LrAnalysisRunTimeError; ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); runDesc.TestState = TestState.Error; } //using (StreamReader reader = runner.StandardOutput) //{ // string result = reader.ReadToEnd(); // ConsoleWriter.WriteLine(Resources.LrAnlysisResults); // ConsoleWriter.WriteLine(""); // ConsoleWriter.WriteLine(result); //} } else { runDesc.ErrorDesc = Resources.LrAnlysisInitFail; ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); runDesc.TestState = TestState.Error; } }
private bool runScenario(string scenario, ref string errorReason, RunCancelledDelegate runCancelled) { cleanENV(); ConsoleWriter.WriteLine(string.Format(Resources.LrInitScenario, scenario)); //start controller _engine = new LrEngine(); if (_engine == null) { errorReason = string.Format(Resources.LrFailToOpenController, scenario); return(false); } //try to register the end scenario event: _scenarioEndedEvent = false; try { _engine.Events.ScenarioEvents.OnScenarioEnded += ScenarioEvents_OnScenarioEnded; _scenarioEndedEvent = true; } catch (Exception e) { ConsoleWriter.WriteException(Resources.LrFailToRegisterEndScenarioEvent, e); _scenarioEndedEvent = false; } if (_displayController == true) { _engine.ShowMainWindow(1); } else { _engine.ShowMainWindow(0); } //pointer to the scenario object: LrScenario currentScenario = _engine.Scenario; //try to open the scenario and validate the scenario and connect to load generators if (openScenario(scenario, ref errorReason) && validateScenario(currentScenario, ref errorReason)) { //apply rts to scripts foreach (ScriptRTSModel scriptRTS in _scriptRTSSet) { try { LrScripts currentScripts = currentScenario.Scripts; LrScript currentScript = currentScripts.Item[scriptRTS.GetScriptName()]; string runtimeSettings = "", actionLogic = ""; currentScript.GetScriptRunTimeSettings(ref runtimeSettings, ref actionLogic); RTSHelper rtsHelper = new RTSHelper(runtimeSettings, RTSHelper.COMMAND_ARGUMENTS, scriptRTS.GetKeyValuePairs()); string updatedRuntimeSettings = rtsHelper.GetUpdatedIniFileText(); currentScript.SetScriptRunTimeSettings(updatedRuntimeSettings, actionLogic); } catch (Exception e) { errorReason = string.Format(Resources.LrRTSError, scriptRTS.GetScriptName(), e.Message); return(false); } } //set the result dir: ConsoleWriter.WriteLine("setting scenario result folder to " + Path.Combine(_resultsFolder, LRR_FOLDER)); currentScenario.ResultDir = Path.Combine(_resultsFolder, LRR_FOLDER); ConsoleWriter.WriteLine("scenario result folder: " + currentScenario.ResultDir); //check if canceled or timedOut: if (_runCancelled()) { errorReason = Resources.GeneralTimedOut; return(false); } _scenarioEnded = false; ConsoleWriter.WriteLine(Resources.LrStartScenario); int ret = currentScenario.Start(); if (!currentScenario.ResultDir.Equals(Path.Combine(_resultsFolder, LRR_FOLDER))) { ConsoleWriter.WriteLine("controller failed to write to " + Path.Combine(_resultsFolder, LRR_FOLDER) + " setting result folder to " + currentScenario.ResultDir); _controller_result_dir = new DirectoryInfo(currentScenario.ResultDir).Name; ConsoleWriter.WriteLine("controller reult dir: " + _controller_result_dir); } if (ret != 0) { errorReason = string.Format(Resources.LrStartScenarioFail, scenario, ret); return(false); } //per scenario timeout stopwatch _stopWatch = Stopwatch.StartNew(); //wait for scenario to end: if (!waitForScenario(ref errorReason)) { //something went wrong during scenario execution, error reason set in errorReason string return(false); } else {//scenario has ended Console.WriteLine(string.Format(Resources.LrScenarioEnded, scenario, _stopWatch.Elapsed.Hours, _stopWatch.Elapsed.Minutes, _stopWatch.Elapsed.Seconds)); //collate results collateResults(); } } else { return(false); } return(true); }