private static IEnumerable <Stopper> GetStoppersDefinitions(ExcelPackage pck) { var ws = pck.Workbook.Worksheets["Cluster-Comp S&S Mapping"]; using var tbl = GetDataTable(ws); foreach (DataRow row in tbl.Rows) { if (int.TryParse((string)row[2], out var stopperId) && stopperId > 100) { var stopper = new Stopper() { ID = int.Parse((string)row[2]), Name = (string)row[3], Cluster = new Cluster() { ID = (string)row[0], Name = (string)row[1] } }; yield return(stopper); } } }
public IDisposable Start(string outputFormat) { Stopper stopper = new Stopper(this, outputFormat); _startTime = DateTime.Now; return(stopper); }
private static void KillController() { var wlrunProcesses = Process.GetProcessesByName("Wlrun"); if (wlrunProcesses.Length > 0) { foreach (Process p in wlrunProcesses) { if (!p.HasExited) { p.Kill(); // When kill wlrun process directly, there might be a werfault.exe process generated, kill it if it appears. DateTime nowTime = DateTime.Now; while (DateTime.Now.Subtract(nowTime).TotalSeconds < 10) { var werFaultProcesses = Process.GetProcessesByName("WerFault"); if (werFaultProcesses.Length > 0) { //Console.WriteLine("Kill process of WerFault"); foreach (Process pf in werFaultProcesses) { pf.Kill(); } break; } Stopper werFaultProcessesStopper = new Stopper(2000); werFaultProcessesStopper.Start(); } Stopper wlrunStopper = new Stopper(2000); wlrunStopper.Start(); } } ConsoleWriter.WriteLine("wlrun killed"); } }
public BTCoroutine incSecondRun(Stopper stopper) { while (true) { print("Enter incSecond"); if (stopper.shouldStop) { print("incSecond Stopped!"); stopper.shouldStop = false; yield return(BTNodeResult.Stopped); yield break; } if (second < max) { second++; yield return(BTNodeResult.Running); } else if (second == max) { yield return(BTNodeResult.Success); yield break; } else { // We should never reach this part } } }
public BTCoroutine gotoRestArea(Stopper stopper) { runningBT = "goto-rest-area"; BTCoroutine routine = gotoImplementation(stopper, zoneManager.findInteractableZone(this, Interactable.Type.Rest).position); return(routine); }
public IDisposable Start(LogMode logMode, string startFormat, string endFormat, params object[] args) { if (!string.IsNullOrWhiteSpace(startFormat)) { JLog.Default.Write(logMode, startFormat, args); } Stopper stopper = new Stopper(this, Format, logMode, endFormat, args); return stopper; }
public BTCoroutine gotoNearestRally(Stopper stopper) { runningBT = "goto-nearest-rally"; Vector3 destination = zoneManager.findRallyZone(this).position; BTCoroutine routine = gotoImplementation(stopper, destination); return(routine); }
public BTCoroutine gotFlockCenter(Stopper stopper) { runningBT = "goto-flock-center"; Vector3 destination = perception.flockCenter; BTCoroutine routine = gotoImplementation(stopper, destination); return(routine); }
public BTCoroutine gotoRestItem(Stopper stopper) { runningBT = "goto-rest-item"; Vector3 destination = ((Interactable)blackboard["InteractableTarget"]).getInteractionPos(this).position; BTCoroutine routine = gotoImplementation(stopper, destination); return(routine); }
public IDisposable Start(LogMode logMode, string startFormat, string endFormat, params object[] args) { if (!string.IsNullOrWhiteSpace(startFormat)) { JLog.Default.Write(logMode, startFormat, args); } Stopper stopper = new Stopper(this, Format, logMode, endFormat, args); return(stopper); }
public static void Main(string[] args) { // Instantiate actors Updater updater = new Updater(); Stopper stopper = new Stopper(updater); // Wait for the actors to expire updater.Wait(); stopper.Wait(); Console.WriteLine("Graceful exit"); }
// Use this for initialization public void Start() { Stopper s = new Stopper(); Console.WriteLine("How many hidden nodes?"); hidden = int.Parse(Console.ReadLine()); Console.WriteLine("Epoch counter?"); int epochCtr = int.Parse(Console.ReadLine()); Console.WriteLine("Error threshold?"); s.errorThresh = float.Parse(Console.ReadLine()); Thread oThread = new Thread(new ThreadStart(s.run)); oThread.Start(); String outPath = "C:/Users/SwoodGrommet/Desktop/game-ai/Assets/Scripts/Datas/"; outputFile = "weights.txt"; sets = new ArrayList(); rec = new Recorder(); nn = new NeuralNetwork (input, output, hidden); numWeights = (input * hidden) + (hidden * output) + (hidden + output); weights = getRandomWeights (numWeights); nn = new NeuralNetwork (input, output, hidden); nn.setWeights (weights); Console.WriteLine("chutzpah"); rec.read (this.sets); read = true; double changeDel = 0; while (/*!trained &&*/ read) { double errors = 0; //do { foreach (TrainingSet set in this.sets) { setInputs(set.getInputs()); setTargets(set.getTargets()); errors += train(); } //Debug.Log("Current error : " + errors); //} while (error > 0.0001); error = errors / sets.Count; if (s.output) { Console.WriteLine("Outputting weights to file"); this.weights = nn.getWeights(); nn.outputWeights(weights); s.output = false; } if (s.errorThresh > error || s.stop) { Console.WriteLine("All trainings are done!!!"); break; } //Console.WriteLine(ctr + ": " + errors); if (ctr % epochCtr == 0) { Console.WriteLine("epoch: " + ctr / epochCtr + "; error: " + error + "; Delta: " + (changeDel - error)); changeDel = error; } ctr++; } }
public BTCoroutine rest(Stopper stopper) { runningBT = "rest"; Interactable target = (Interactable)blackboard["InteractableTarget"]; blackboard.Remove("InteractableTarget"); BTCoroutine routine = consumeImplementation(stopper, target); return(routine); }
static void Main(string[] args) { Dispatcher dispatcher = new Dispatcher(); Stopper stopper = new Stopper(); Safir.Dob.Connection connection = new Safir.Dob.Connection(); connection.Open("foo", "foo", 0, stopper, dispatcher); System.Console.WriteLine("Connected!"); for (int i = 10; i > 0; --i) { System.Console.WriteLine("Sleeping: " + i); System.Threading.Thread.Sleep(1000); } }
private BTCoroutine gotoImplementation(Stopper stopper, Vector3 target) { navAgent.isStopped = false; navAgent.destination = target; Rigidbody rb = GetComponent <Rigidbody>(); while (true) { if (navAgent.hasPath) { animatorDriver.PlayWalk(); if (rb.constraints == RigidbodyConstraints.FreezeAll) { rb.constraints = RigidbodyConstraints.None; } } else { animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); rb.constraints = RigidbodyConstraints.FreezeAll; } if (stopper.shouldStop) { if (blackboard.ContainsKey("InteractableTarget")) { Interactable toRemove = (Interactable)blackboard["InteractableTarget"]; Physics.IgnoreCollision(toRemove.GetComponent <BoxCollider>(), GetComponent <BoxCollider>(), false); toRemove.unReserve(this); blackboard.Remove("InteractableTarget"); } navAgent.isStopped = true; stopper.shouldStop = false; animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Stopped); yield break; } if (destinationReached()) { animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Success); yield break; } yield return(BTNodeResult.Running); } }
private void collateResults() { int ret = _engine.Scenario.CollateResults(); if (ret != 0) { ConsoleWriter.WriteErrLine(string.Format(Resources.LrScenarioCollateFail, ret)); } while (!_engine.Scenario.IsResultsCollated() && _stopWatch.Elapsed < _perScenarioTimeOutMinutes) { Stopper collateStopper = new Stopper(_pollingInterval * 1000); collateStopper.Start(); } }
public BTCoroutine idleWander(Stopper stopper) { runningBT = "idle-wander"; Interactable interactable = zoneManager.requestIdleInteractable(this); idleBehavior.setContext(interactable); BTNode subRoot = idleBehavior.getRoot(); subRoot.overrwriteStopper(stopper); BTCoroutine routine = subRoot.Procedure(); return(routine); }
public void Handle(Page page) { if (Stopper != null) { if (!Stopper.NeedStop(page, this)) { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } } else { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } }
public virtual bool Handle(ref Page page, ISpider spider) { if (Stopper != null) { if (!Stopper.NeedStop(page, this)) { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } } else { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } return(true); }
private void closeController() { //try to gracefully shut down the controller if (_engine != null) { try { var process = Process.GetProcessesByName("Wlrun"); if (process.Length > 0) { int rc = _engine.CloseController(); if (rc != 0) { ConsoleWriter.WriteErrLine( "\t\tFailed to close Controller with CloseController API function, rc: " + rc); } } //give the controller 15 secs to shutdown. otherwise, print an error. Stopper controllerStopper = new Stopper(15000); controllerStopper.Start(); if (_engine != null) { process = Process.GetProcessesByName("Wlrun"); if (process.Length > 0) { ConsoleWriter.WriteErrLine("\t\tThe Controller is still running..."); Stopper wlrunStopper = new Stopper(10000); wlrunStopper.Start(); return; } } } catch (Exception e) { ConsoleWriter.WriteErrLine("\t\t Cannot close Controller gracefully, exception details:"); ConsoleWriter.WriteErrLine(e.Message); ConsoleWriter.WriteErrLine(e.StackTrace); ConsoleWriter.WriteErrLine("killing Controller process"); cleanENV(); } } _engine = null; }
public CalculateVatReturnSummary(int nCustomerMarketplaceID) { m_nCustomerMarketplaceID = nCustomerMarketplaceID; m_oSpLoadBusinesses = new LoadBusinessesForVatReturnSummary(m_nCustomerMarketplaceID, DB, Log); m_oSpLoadSummaryData = new LoadDataForVatReturnSummary(m_nCustomerMarketplaceID, DB, Log); m_oSpLoadRtiMonths = new LoadRtiMonthForVatReturnSummary(m_nCustomerMarketplaceID, DB, Log); m_oBusinessRegNums = new SortedDictionary <int, long>(); m_oRegNumBusinesses = new SortedDictionary <long, TimedBusinessID>(); m_oBusinessData = new SortedDictionary <long, BusinessData>(); m_oRtiMonths = new SortedDictionary <DateTime, decimal>(); Stopper = new Stopper(); this.historyRecordID = 0; } // constructor
private void cleanENV() { ConsoleWriter.WriteLine(Resources.LrCleanENV); try { // check if any mdrv.exe process existed, kill them. var mdrvProcesses = Process.GetProcessesByName("mdrv"); foreach (Process p in mdrvProcesses) { p.Kill(); Stopper stopper = new Stopper(500); stopper.Start(); } // check if any wlrun.exe process existed, kill them. KillController(); } catch (Exception e) { } }
public override void Handle(Page page) { var i = SetInterval?.Interval(page); if (i != null) { Interval = i.Value; } if (Stopper != null) { if (!Stopper.NeedStop(page, this)) { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } } else { page.AddTargetRequests(GenerateRequests(page)); page.MissExtractTargetUrls = true; } }
public BTCoroutine dynamicGoto(Stopper stopper) { if (interactable == null) { yield return(BTNodeResult.Failure); yield break; } user.navAgent.isStopped = false; user.animatorDriver.PlayWalk(); user.navAgent.destination = interactable.getInteractionPos(user).position; while (true) { if (stopper.shouldStop) { user.navAgent.isStopped = true; stopper.shouldStop = false; user.animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Stopped); yield break; } if (dynamicReached()) { user.animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Success); yield break; } yield return(BTNodeResult.Running); } }
private static void KillController() { var wlrunProcesses = Process.GetProcessesByName("Wlrun"); if (wlrunProcesses.Length > 0) { foreach (Process p in wlrunProcesses) { p.Kill(); // When kill wlrun process directly, there might be a werfault.exe process generated, kill it if it appears. DateTime nowTime = DateTime.Now; while (DateTime.Now.Subtract(nowTime).TotalSeconds < 10) { var werFaultProcesses = Process.GetProcessesByName("WerFault"); if (werFaultProcesses.Length > 0) { //Console.WriteLine("Kill process of WerFault"); foreach (Process pf in werFaultProcesses) { pf.Kill(); } break; } Stopper werFaultProcessesStopper = new Stopper(2000); werFaultProcessesStopper.Start(); } Stopper wlrunStopper = new Stopper(2000); wlrunStopper.Start(); } ConsoleWriter.WriteLine("wlrun killed"); } }
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); }
public void overrwriteStopper(Stopper newStopper) { this.stopper = newStopper; }
} // Name public override void Execute() { Guid oCalculationID = Guid.NewGuid(); Stopper.Execute(ElapsedDataMemberType.RetrieveDataFromDatabase, () => { m_oSpLoadBusinesses.ForEachRowSafe((sr, bRowsetStart) => { m_oBusinessRegNums[sr["BusinessID"]] = sr["RegistrationNo"]; return(ActionResult.Continue); }); m_oSpLoadSummaryData.ForEachResult <LoadDataForVatReturnSummary.ResultRow>(oRow => { if (oRow.BoxNum < 1) { return(ActionResult.Continue); } if (!m_oBusinessRegNums.ContainsKey(oRow.BusinessID)) { Log.Warn("Registration # not found for business with id {0}.", oRow.BusinessID); return(ActionResult.Continue); } // if long nRegNo = m_oBusinessRegNums[oRow.BusinessID]; if (m_oRegNumBusinesses.ContainsKey(nRegNo)) { m_oRegNumBusinesses[nRegNo].Update(oRow.BusinessID, oRow.DateFrom.Date); } else { m_oRegNumBusinesses[nRegNo] = new TimedBusinessID { BusinessID = oRow.BusinessID, Since = oRow.DateFrom.Date, } }; if (m_oBusinessData.ContainsKey(nRegNo)) { m_oBusinessData[nRegNo].Add(oRow); } else { m_oBusinessData[nRegNo] = new BusinessData(oRow); } return(ActionResult.Continue); }); m_oCurrentRtiMonthAction = SaveCustomerID; m_oSpLoadRtiMonths.ForEachResult <LoadRtiMonthForVatReturnSummary.ResultRow>(oRow => { m_oCurrentRtiMonthAction(oRow); return(ActionResult.Continue); }); // for each }); // Stopper.Execute Log.Debug("Customer ID: {0}, marketplace ID: {1}", m_nCustomerID, m_nCustomerMarketplaceID); Log.Debug("Summary data - begin:"); int nSavedCount = 0; foreach (KeyValuePair <long, BusinessData> pair in m_oBusinessData) { BusinessData oBusinessData = pair.Value; Stopper.Execute(ElapsedDataMemberType.AggregateData, () => oBusinessData.Calculate(m_nOneMonthSalary, m_oRtiMonths)); Stopper.Execute(ElapsedDataMemberType.StoreAggregatedData, () => { // Business registration number stays with the company for its entire life // while name and address can change. In our DB BusinessID is bound to // company name, address, and registration number therefore in the following // assignment we look for the most updated business id associated with // company registration number; oBusinessData.BusinessID = m_oRegNumBusinesses[ m_oBusinessRegNums[oBusinessData.BusinessID] ].BusinessID; Log.Debug(oBusinessData); var oSp = new SaveVatReturnSummary(DB, Log) { CustomerID = m_nCustomerID, CustomerMarketplaceID = m_nCustomerMarketplaceID, CalculationID = oCalculationID, Totals = new[] { oBusinessData }, Quarters = oBusinessData.QuartersToSave(), }; oSp.ExecuteNonQuery(); nSavedCount++; }); } // for each if (nSavedCount == 0) { DB.ExecuteNonQuery( "DeleteOtherVatReturnSummary", CommandSpecies.StoredProcedure, new QueryParameter("CustomerID", m_nCustomerID), new QueryParameter("CustomerMarketplaceID", m_nCustomerMarketplaceID) ); } // if Log.Debug("Summary data - end."); UpdateBusinessRelevanceAndTotals(); } // Execute
private BTCoroutine consumeImplementation(Stopper stopper, Interactable target) { target.attach(this); Vector3 targetDir = target.getInteractionPos(this).transform.forward; targetDir = Vector3.Normalize(targetDir); float step = navAgent.angularSpeed * Time.deltaTime; step = step / 180.0f * Mathf.PI; // The animal does not have to do anything beyond this, the container "feeds" the animal // on update (like an observer pattern) while (true) { if (stopper.shouldStop) { stopper.shouldStop = false; target.detach(this); Physics.IgnoreCollision(target.GetComponent <BoxCollider>(), GetComponent <BoxCollider>(), false); animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Stopped); yield break; } // Rotate until we are "close enough" float dot = Vector3.Dot(transform.forward, targetDir); if (dot <= 0.99f) { Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0f); transform.rotation = Quaternion.LookRotation(newDir); yield return(BTNodeResult.Running); } else { transform.rotation = Quaternion.LookRotation(targetDir); break; } } switch (target.type) { case Interactable.Type.Food: animatorDriver.PlayFullBodyState(States.AnimalFullBody.Eat); break; case Interactable.Type.Rest: animatorDriver.PlayFullBodyState(States.AnimalFullBody.Rest); break; } GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeAll; while (true) { if (stopper.shouldStop) { stopper.shouldStop = false; target.detach(this); Physics.IgnoreCollision(target.GetComponent <BoxCollider>(), GetComponent <BoxCollider>(), false); animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); GetComponent <Rigidbody>().constraints = RigidbodyConstraints.None; yield return(BTNodeResult.Stopped); yield break; } if (target.isEmpty()) { target.detach(this); animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Failure); yield break; } yield return(BTNodeResult.Running); } }
public BTCoroutine dynamicAction(Stopper stopper) { Physics.IgnoreCollision(interactable.GetComponent <BoxCollider>(), GetComponent <BoxCollider>()); interactable.attach(user); Vector3 targetDir = interactable.getInteractionPos(user).transform.forward; targetDir = Vector3.Normalize(targetDir); float step = user.navAgent.angularSpeed * Time.deltaTime; step = step / 180.0f * Mathf.PI; while (true) { if (stopper.shouldStop) { stopper.shouldStop = false; interactable.detach(user); Physics.IgnoreCollision(interactable.GetComponent <BoxCollider>(), GetComponent <BoxCollider>(), false); user.animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); yield return(BTNodeResult.Stopped); yield break; } // Rotate until we are "close enough" float dot = Vector3.Dot(transform.forward, targetDir); if (dot <= 0.99f) { Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0f); transform.rotation = Quaternion.LookRotation(newDir); yield return(BTNodeResult.Running); } else { transform.rotation = Quaternion.LookRotation(targetDir); break; } } switch (interactable.type) { case Interactable.Type.Chill: case Interactable.Type.Talk: user.animatorDriver.PlayFullBodyState(States.AnimalFullBody.Rest); break; } GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeAll; while (true) { if (stopper.shouldStop) { stopper.shouldStop = false; interactable.detach(user); Physics.IgnoreCollision(interactable.GetComponent <BoxCollider>(), GetComponent <BoxCollider>(), false); user.animatorDriver.PlayFullBodyState(States.AnimalFullBody.Idle); GetComponent <Rigidbody>().constraints = RigidbodyConstraints.None; yield return(BTNodeResult.Stopped); yield break; } yield return(BTNodeResult.Running); } }
private void collateResults() { int ret = _engine.Scenario.CollateResults(); if (ret != 0) { ConsoleWriter.WriteErrLine(string.Format(Resources.LrScenarioCollateFail, ret)); } while (!_engine.Scenario.IsResultsCollated() && _stopWatch.Elapsed < _perScenarioTimeOutMinutes) { Stopper collateStopper = new Stopper(_pollingInterval * 1000); collateStopper.Start(); } }
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; while (_stopWatch.Elapsed <= _perScenarioTimeOutMinutes) { if (_runCancelled()) { errorReason = Resources.GeneralTimedOut; return false; } if (autoEvent.WaitOne(time)) { break; } } if (_stopWatch.Elapsed > _perScenarioTimeOutMinutes) { _stopWatch.Stop(); ConsoleWriter.WriteErrLine(string.Format(Resources.LrScenarioTimeOut, _stopWatch.Elapsed.Seconds)); errorReason = string.Format(Resources.LrScenarioTimeOut, _stopWatch.Elapsed.Seconds); } 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) { ConsoleWriter.WriteErrLine(Resources.LrScenarioTimeOut); 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; }
/// <summary> /// Starts the timer and returns and "handle" that must be disposed to stop the timer. /// </summary> /// <param name="outputFormat">the output format string, that is used to render the result message</param> /// <returns>the handle to dispose for stopping the timer</returns> public IDisposable Start(string outputFormat) { Stopper stopper = new Stopper(this, outputFormat); _startTime = DateTime.Now; return stopper; }
private void cleanENV() { ConsoleWriter.WriteLine(Resources.LrCleanENV); try { // check if any mdrv.exe process existed, kill them. var mdrvProcesses = Process.GetProcessesByName("mdrv"); foreach (Process p in mdrvProcesses) { p.Kill(); Stopper stopper = new Stopper(500); stopper.Start(); } // check if any wlrun.exe process existed, kill them. KillController(); } catch (Exception e) { } }
static int Main(string[] args) { HpToolsLauncher.ConsoleQuickEdit.Disable(); Console.OutputEncoding = System.Text.Encoding.GetEncoding("utf-8"); log("starting analysis launcher"); int iPassed = (int)Launcher.ExitCodeEnum.Passed;//variable to keep track of whether all of the SLAs passed try { //The app uses 3 default arguments, a 4th optional one can be used to specify the path to an analysis template if (args.Length != 3 && args.Length != 4) { ShowHelp(); return((int)Launcher.ExitCodeEnum.Aborted); } string lrrlocation = args[0]; string lralocation = args[1]; string htmlLocation = args[2]; string analysisTemplateLocation = (args.Length == 4 ? args[3] : ""); log("creating analysis COM object"); LrAnalysis analysis = new LrAnalysis(); Session session = analysis.Session; log("creating analysis session"); //Apply a template and create LRA folder if (session.CreateWithTemplateFile(lralocation, lrrlocation, analysisTemplateLocation)) { log("analysis session created"); log("creating HTML reports"); HtmlReportMaker reportMaker = session.CreateHtmlReportMaker(); reportMaker.AddGraph("Connections"); reportMaker.AddGraph("ConnectionsPerSecond"); reportMaker.CreateDefaultHtmlReport( Path.Combine(Path.GetDirectoryName(htmlLocation), "IE", Path.GetFileName(htmlLocation)), ApiBrowserType.IE); reportMaker.CreateDefaultHtmlReport( Path.Combine(Path.GetDirectoryName(htmlLocation), "Netscape", Path.GetFileName(htmlLocation)), ApiBrowserType.Netscape); log("HTML reports created"); XmlDocument xmlDoc = new XmlDocument(); log("loading errors, if any"); session.ErrorMessages.LoadValuesIfNeeded(); if (session.ErrorMessages.Count != 0) { log("error count: " + session.ErrorMessages.Count); if (session.ErrorMessages.Count > 1000) { log("more then 1000 error during scenario run, analyzing only the first 1000."); } log(Resources.ErrorsReportTitle); XmlElement errorRoot = xmlDoc.CreateElement("Errors"); xmlDoc.AppendChild(errorRoot); int limit = 1000; ErrorMessage[] errors = session.ErrorMessages.ToArray(); //foreach (ErrorMessage err in session.ErrorMessages) for (int i = 0; i < limit && i < errors.Length; i++) { ErrorMessage err = errors[i]; XmlElement elem = xmlDoc.CreateElement("Error"); elem.SetAttribute("ID", err.ID.ToString()); elem.AppendChild(xmlDoc.CreateTextNode(err.Name)); log("ID: " + err.ID + " Name: " + err.Name); errorRoot.AppendChild(elem); } xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "Errors.xml")); xmlDoc.RemoveAll(); log(""); } XmlDocument runReprotDoc = new XmlDocument(); log("Gathering Run statistics"); XmlElement runsRoot = runReprotDoc.CreateElement("Runs"); runReprotDoc.AppendChild(runsRoot); XmlElement general = runReprotDoc.CreateElement("General"); runsRoot.AppendChild(general); XmlElement durationElement = runReprotDoc.CreateElement("Time"); durationElement.SetAttribute("End", "-1"); durationElement.SetAttribute("Start", "-1"); durationElement.SetAttribute("Duration", "-1"); Stopper stopper = new Stopper(10000); stopper.Start(); //foreach (Run currentRun in analysis.Session.Runs) //{ // stopper.Start(); // log("Gathering Duration statistics"); // stopper.Start(); //DateTime startTime = Helper.FromUnixTime(currentRun.StartTime); //DateTime endTime = Helper.FromUnixTime(currentRun.EndTime); //durationElement.SetAttribute("End", endTime.ToString()); //durationElement.SetAttribute("Start", startTime.ToString()); //durationElement.SetAttribute("Duration", Helper.GetScenarioDuration(currentRun)); //} general.AppendChild(durationElement); XmlElement vUsers = runReprotDoc.CreateElement("VUsers"); //log("Adding VUser statistics"); Dictionary <string, int> vuserCountDictionary = new Dictionary <string, int>(4) { { "Passed", 0 }, { "Stopped", 0 }, { "Failed", 0 }, { "Error", 0 } }; //vuserCountDictionary = Helper.GetVusersCountByStatus(analysis); foreach (KeyValuePair <string, int> kvp in vuserCountDictionary) { //log(msg: String.Format("{0} vUsers: {1}", kvp.Key, kvp.Value)); vUsers.SetAttribute(kvp.Key, kvp.Value.ToString()); } vUsers.SetAttribute("Count", session.VUsers.Count.ToString()); general.AppendChild(vUsers); XmlElement transactions = runReprotDoc.CreateElement("Transactions"); Dictionary <string, double> transactionSumStatusDictionary = new Dictionary <string, double>() { { "Count", 0 }, { "Pass", 0 }, { "Fail", 0 }, { "Stop", 0 } }; Dictionary <string, Dictionary <string, double> > transactionDictionary = Helper.CalcFailedTransPercent(analysis); foreach (KeyValuePair <string, Dictionary <string, double> > kvp in transactionDictionary) { XmlElement transaction = runReprotDoc.CreateElement("Transaction"); foreach (var transStatus in kvp.Value) { transaction.SetAttribute(transStatus.Key, transStatus.Value.ToString()); transactionSumStatusDictionary[transStatus.Key] += transStatus.Value; transactionSumStatusDictionary["Count"] += transStatus.Value; } transaction.SetAttribute("Name", kvp.Key); transactions.AppendChild(transaction); } foreach (var transStatus in transactionSumStatusDictionary) { transactions.SetAttribute(transStatus.Key, transStatus.Value.ToString()); //log(msg: String.Format("{0} transaction: {1}", transStatus.Key, transStatus.Value)); } general.AppendChild(transactions); string connectionsMaximum = "0"; //connectionsMaximum = Helper.GetConnectionsCount(analysis).ToString(); XmlElement connections = runReprotDoc.CreateElement("Connections"); connections.SetAttribute("MaxCount", connectionsMaximum); general.AppendChild(connections); log(""); log("closing session"); session.Close(); log(Resources.SLAReportTitle); log("calculating SLA"); SlaResult slaResult = Session.CalculateSla(lralocation, true); log("SLA calculation done"); XmlElement root = xmlDoc.CreateElement("SLA"); xmlDoc.AppendChild(root); int iCounter = 0; // set counter log("WholeRunRules : " + slaResult.WholeRunRules.Count); CultureInfo formatProvider = new CultureInfo("en-US"); foreach (SlaWholeRunRuleResult a in slaResult.WholeRunRules) { log(Resources.DoubleLineSeperator); XmlElement elem; if (a.Measurement.Equals(SlaMeasurement.PercentileTRT)) { SlaPercentileRuleResult b = slaResult.TransactionRules.PercentileRules[iCounter]; elem = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name log("Transaction Name : " + b.TransactionName); elem.SetAttribute("TransactionName", b.TransactionName.ToString()); log("Percentile : " + b.Percentage); elem.SetAttribute("Percentile", b.Percentage.ToString(formatProvider)); elem.SetAttribute("FullName", b.RuleUiName); log("Full Name : " + b.RuleUiName); log("Measurement : " + b.Measurement); elem.SetAttribute("Measurement", b.Measurement.ToString()); log("Goal Value : " + b.GoalValue); elem.SetAttribute("GoalValue", b.GoalValue.ToString(formatProvider)); log("Actual value : " + b.ActualValue); elem.SetAttribute("ActualValue", b.ActualValue.ToString(formatProvider)); log("status : " + b.Status); elem.AppendChild(xmlDoc.CreateTextNode(b.Status.ToString())); if (b.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } iCounter++; } else { elem = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name elem.SetAttribute("FullName", a.RuleUiName); log("Full Name : " + a.RuleUiName); log("Measurement : " + a.Measurement); elem.SetAttribute("Measurement", a.Measurement.ToString()); log("Goal Value : " + a.GoalValue); elem.SetAttribute("GoalValue", a.GoalValue.ToString(formatProvider)); log("Actual value : " + a.ActualValue); elem.SetAttribute("ActualValue", a.ActualValue.ToString(formatProvider)); log("status : " + a.Status); elem.AppendChild(xmlDoc.CreateTextNode(a.Status.ToString())); if (a.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } } root.AppendChild(elem); log(Resources.DoubleLineSeperator); } iCounter = 0; // reset counter log("TimeRangeRules : " + slaResult.TimeRangeRules.Count); foreach (SlaTimeRangeRuleResult a in slaResult.TimeRangeRules) { log(Resources.DoubleLineSeperator); XmlElement rule; if (a.Measurement.Equals(SlaMeasurement.AverageTRT)) { SlaTransactionTimeRangeRuleResult b = slaResult.TransactionRules.TimeRangeRules[iCounter]; rule = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name log("Transaction Name: " + b.TransactionName); rule.SetAttribute("TransactionName", b.TransactionName); log("Full Name : " + b.RuleUiName); rule.SetAttribute("FullName", b.RuleUiName); log("Measurement : " + b.Measurement); rule.SetAttribute("Measurement", b.Measurement.ToString()); log("SLA Load Threshold Value : " + b.CriteriaMeasurement); rule.SetAttribute("SLALoadThresholdValue", b.CriteriaMeasurement.ToString()); log("LoadThresholds : " + b.LoadThresholds.Count); foreach (SlaLoadThreshold slat in b.LoadThresholds) { XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold"); loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString(formatProvider)); loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString(formatProvider)); loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString(formatProvider)); rule.AppendChild(loadThr); } XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges"); log("TimeRanges : " + b.TimeRanges.Count); int passed = 0; int failed = 0; int noData = 0; foreach (SlaTimeRangeInfo slatri in b.TimeRanges) { XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo"); subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString()); subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString()); subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString(formatProvider)); subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString(formatProvider)); subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString(formatProvider)); subsubelem.InnerText = slatri.Status.ToString(); switch (slatri.Status) { case SlaRuleStatus.Failed: failed++; break; case SlaRuleStatus.Passed: passed++; break; case SlaRuleStatus.NoData: noData++; break; default: break; } timeRanges.AppendChild(subsubelem); } rule.AppendChild(timeRanges); SlaRuleStatus currentRuleStatus = b.Status; if (currentRuleStatus.Equals(SlaRuleStatus.NoData) && (passed > noData)) { currentRuleStatus = SlaRuleStatus.Passed; } log("status : " + currentRuleStatus); rule.AppendChild(xmlDoc.CreateTextNode(currentRuleStatus.ToString())); if (currentRuleStatus.Equals(SlaRuleStatus.Failed)) // 0 = failed { iPassed = (int)Launcher.ExitCodeEnum.Failed; } iCounter++; } else { rule = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name log("Full Name : " + a.RuleUiName); rule.SetAttribute("FullName", a.RuleUiName); log("Measurement : " + a.Measurement); rule.SetAttribute("Measurement", a.Measurement.ToString()); log("SLA Load Threshold Value : " + a.CriteriaMeasurement); rule.SetAttribute("SLALoadThresholdValue", a.CriteriaMeasurement.ToString()); log("LoadThresholds : " + a.LoadThresholds.Count); foreach (SlaLoadThreshold slat in a.LoadThresholds) { XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold"); loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString(formatProvider)); loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString(formatProvider)); loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString(formatProvider)); rule.AppendChild(loadThr); } XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges"); log("TimeRanges : " + a.TimeRanges.Count); int passed = 0; int failed = 0; int noData = 0; foreach (SlaTimeRangeInfo slatri in a.TimeRanges) { XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo"); subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString()); subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString()); subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString(formatProvider)); subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString(formatProvider)); subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString(formatProvider)); subsubelem.InnerText = slatri.Status.ToString(); switch (slatri.Status) { case SlaRuleStatus.Failed: failed++; break; case SlaRuleStatus.Passed: passed++; break; case SlaRuleStatus.NoData: noData++; break; default: break; } timeRanges.AppendChild(subsubelem); } rule.AppendChild(timeRanges); SlaRuleStatus currentRuleStatus = a.Status; if (currentRuleStatus.Equals(SlaRuleStatus.NoData) && (passed > noData)) { currentRuleStatus = SlaRuleStatus.Passed; } log("status : " + currentRuleStatus); rule.AppendChild(xmlDoc.CreateTextNode(currentRuleStatus.ToString())); if (currentRuleStatus.Equals(SlaRuleStatus.Failed)) { iPassed = (int)Launcher.ExitCodeEnum.Failed; } } root.AppendChild(rule); log(Resources.DoubleLineSeperator); } XmlNode slaNode = runReprotDoc.ImportNode(root, true); runsRoot.AppendChild(slaNode); log("saving RunReport.xml to " + Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "RunReport.xml")); runReprotDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "RunReport.xml")); runReprotDoc.RemoveAll(); //write XML to location: log("saving SLA.xml to " + Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml")); xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml")); } else { log(Resources.CannotCreateSession); return((int)Launcher.ExitCodeEnum.Aborted); } log("closing analysis session"); session.Close(); } catch (TypeInitializationException ex) { if (ex.InnerException is UnauthorizedAccessException) { log( "UnAuthorizedAccessException: Please check the account privilege of current user, LoadRunner tests should be run by administrators."); } else { log(ex.Message); log(ex.StackTrace); } return((int)Launcher.ExitCodeEnum.Aborted); } catch (Exception e) { log(e.Message); log(e.StackTrace); return((int)Launcher.ExitCodeEnum.Aborted); } // return SLA status code, if any SLA fails return a fail here. // writer.Flush(); // writer.Close(); return(iPassed); }
private void closeController_Kill() { //try to gracefully shut down the controller if (_engine != null) { try { var process = Process.GetProcessesByName("Wlrun"); if (process.Length > 0) { int rc = _engine.CloseController(); if (rc != 0) { ConsoleWriter.WriteErrLine( "\t\tFailed to close Controller with CloseController API function, rc: " + rc); } } if (_engine != null) { process = Process.GetProcessesByName("Wlrun"); if (process.Length > 0) { ConsoleWriter.WriteErrLine("\t\tThe Controller is still running..."); Stopper wlrunStopper = new Stopper(10000); wlrunStopper.Start(); KillController(); return; } } } catch (Exception e) { ConsoleWriter.WriteErrLine("\t\t Cannot close Controller gracefully, exception details:"); ConsoleWriter.WriteErrLine(e.Message); ConsoleWriter.WriteErrLine(e.StackTrace); ConsoleWriter.WriteErrLine("killing Controller process"); cleanENV(); } } _engine = null; }