public UIBindingRow(ViewModel model, Command command) { using (var tracker = TimingLogger.Track("UIBindingRow.ctor()")) { _model = model; _command = command; ActionName = command.Name; var binding = _model.GetKeyBinding(ActionName); tracker.Log("... after binding"); // checkbox on the left _checkboxStorable = new JSONStorableBool(ActionName, binding == null ? false : binding.Enabled, OnCheckboxHandler); _checkboxUi = _model.Plugin.CreateToggle(_checkboxStorable); _checkboxUi.labelText.text = command.DisplayName; _checkboxUi.labelText.resizeTextMaxSize = _checkboxUi.labelText.fontSize; _checkboxUi.labelText.resizeTextForBestFit = true; _checkboxUi.backgroundColor = Color.clear; tracker.Log("... after checkbox create"); var shortcutText = binding == null ? "" : binding.KeyChord.ToString(); _shortcutButtonUi = _model.Plugin.CreateButton(shortcutText, rightSide: true); _shortcutButtonUi.height = _checkboxUi.height; _shortcutButtonUi.button.onClick.AddListener(OnShortcutHandler); tracker.Log("... after button create"); } }
public List <KeyValuePair <string, KeyBinding> > GetShownBindings() { using (TimingLogger.Track("GetShowBindings()")) { var shown = new List <KeyValuePair <string, KeyBinding> >(); foreach (var item in _bindings) { var actionName = item.Key; Command command = _commandsByName.ContainsKey(actionName) ? _commandsByName[actionName] : null; if (command == null) { continue; } if (!ActionCategory.Equals(command.Group)) { continue; } if (!ActionSubCategory.Equals(command.SubGroup)) { continue; } shown.Add(item); } return(shown); } }
public void SeePlayerHand(int playerShowingHand, Card hole1, Card hole2, Hand bestHand) { if (_botTimeOutMilliSeconds > 0) { if (!IsBotBusy()) { _task = Task.Run(() => { RunSeePlayerHand(playerShowingHand, hole1, hole2, bestHand); }); // wait X amount of time for task to complete if (!_task.Wait(_botTimeOutMilliSeconds)) { // Note that the task is still running in the background _bIsBotBusy = true; Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunSeePlayerHand(playerShowingHand, hole1, hole2, bestHand); } TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}, {5}, {6}, {7}", _handNum, Stage.StageShowdown, PlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond, playerShowingHand, hole1, hole2)); }
public NUnitResults Explore(TestFilter filter) { var timing = new TimingLogger(settings, logger); var results = new NUnitResults(Runner.Explore(filter)); timing.LogTime("Execution engine discovery time "); return(results); }
public NUnitResults Run(ITestEventListener listener, TestFilter filter) { var timing = new TimingLogger(settings, logger); var results = new NUnitResults(Runner.Run(listener, filter)); timing.LogTime("Execution engine run time "); return(results); }
private void InitUI() { using (TimingLogger.Track("InitUI()")) { InitUIHeader(); InitUIBindings(); } }
public void Initialize() { using (var timing = TimingLogger.Track("Initialize()")) { _actionController = new CommandFactory(Plugin); InitBindings(); InitializeUI(); } }
public Writer(TimingLogger logger, LogLevel logLevel) { _logLevel = logLevel; _processWrite = typeof(TimingLogger).GetMethod( "ProcessWrite", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, new Type[] { typeof(LogLevel), typeof(string) }) ! .CreateDelegate <Action <LogLevel, string> >(logger); }
public NUnitResults Run(ITestEventListener listener, TestFilter filter) { var timing = new TimingLogger(settings, logger); var results = new NUnitResults(Runner.Run(listener, filter)); timing.LogTime($"Execution engine run time with filter length {filter.Text.Length}"); if (filter.Text.Length < 300) { logger.Debug($"Filter: {filter.Text}"); } return(results); }
/// <summary> /// Called by the VisualStudio IDE when selected tests are to be run. Never called from TFS Build, except (at least 2022, probably also 2019) when vstest.console uses /test: then this is being used. /// </summary> /// <param name="tests">The tests to be run.</param> /// <param name="runContext">The RunContext.</param> /// <param name="frameworkHandle">The FrameworkHandle.</param> public void RunTests(IEnumerable <TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { Initialize(runContext, frameworkHandle); CheckIfDebug(); InitializeForExecution(runContext, frameworkHandle); RunType = RunType.Ide; TestLog.Debug("RunTests by IEnumerable<TestCase>. RunType = Ide"); var timing = new TimingLogger(Settings, TestLog); Debug.Assert(NUnitEngineAdapter != null, "NUnitEngineAdapter is null"); Debug.Assert(NUnitEngineAdapter.EngineEnabled, "NUnitEngineAdapter TestEngine is null"); var assemblyGroups = tests.GroupBy(tc => tc.Source); if (IsInProcDataCollectorsSpecifiedWithMultipleAssemblies(assemblyGroups)) { TestLog.Error( "Failed to run tests for multiple assemblies when InProcDataCollectors specified in run configuration."); Unload(); return; } foreach (var assemblyGroup in assemblyGroups) { var assemblytiming = new TimingLogger(Settings, TestLog); try { string assemblyName = assemblyGroup.Key; string assemblyPath = Path.IsPathRooted(assemblyName) ? assemblyName : Path.Combine(Directory.GetCurrentDirectory(), assemblyName); var filterBuilder = CreateTestFilterBuilder(); var filter = filterBuilder.FilterByList(assemblyGroup); RunAssembly(assemblyPath, assemblyGroup, filter); } catch (Exception ex) { if (ex is TargetInvocationException) { ex = ex.InnerException; } TestLog.Warning("Exception thrown executing tests", ex); } assemblytiming.LogTime($"Executing {assemblyGroup.Key} time "); } timing.LogTime("Total execution time"); TestLog.Info($"NUnit Adapter {AdapterVersion}: Test execution complete"); Unload(); }
public NUnitResults Explore(TestFilter filter) { var timing = new TimingLogger(settings, logger); var results = new NUnitResults(Runner.Explore(filter)); timing.LogTime($"Execution engine discovery time with filter length {filter.Text.Length}"); if (filter.Text.Length < 300) { logger.Debug($"Filter: {filter.Text}"); } return(results); }
private void InitUIBindings() { var shownBindings = GetShownBindings(); using (TimingLogger.Track($"InitUIBindings() [count: {shownBindings.Count}]")) { // show ui elements based on filters foreach (var item in shownBindings) { var actionName = item.Key; var command = _commandsByName[actionName]; _uiBindings.Add(new UIBindingRow(this, command)); } } }
public void InitPlayer(int pPlayerNum, GameConfig gameConfig, Dictionary <string, string> playerConfigSettings) { PlayerNum = pPlayerNum; StackSize = gameConfig.StartingStack; if (playerConfigSettings.ContainsKey("startingStack")) { StackSize = Convert.ToInt32(playerConfigSettings["startingStack"]); } _botTimeOutMilliSeconds = gameConfig.BotTimeOutMilliSeconds; if (_botTimeOutMilliSeconds > 0) { if (!IsBotBusy()) { _task = Task.Run(() => { RunInitPlayer(pPlayerNum, gameConfig, playerConfigSettings); }); // wait X amount of time for task to complete if (!_task.Wait(_botTimeOutMilliSeconds)) { // Note that the task is still running in the background _bIsBotBusy = true; Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunInitPlayer(pPlayerNum, gameConfig, playerConfigSettings); } TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}", _handNum, Stage.StagePreflop, pPlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond)); if (IsObserver) { IsAlive = false; IsActive = false; StackSize = 0; } }
protected override void OnResume() { TimingLogger timing = null; if (firstOnResume) { timing = new TimingLogger("startup-timing: OnResume reached"); } base.OnResume(); if (firstOnResume) { timing.Stop("startup-timing: OnResume end reached"); firstOnResume = false; } }
protected override void OnStart() { TimingLogger timing = null; if (firstOnStart) { timing = new TimingLogger("startup-timing: OnStart reached"); } base.OnStart(); if (firstOnStart) { timing.Stop("startup-timing: OnStart end reached"); firstOnStart = false; } }
public void GetAction(Stage stage, int betSize, int callAmount, int minRaise, int maxRaise, int raisesRemaining, int potSize, out ActionType playersAction, out int playersBetAmount) { // Default to fold if exception or timeout playersAction = ActionType.Fold; playersBetAmount = 0; if (_botTimeOutMilliSeconds > 0) { if (!IsBotBusy()) { _task = Task.Run(() => { RunGetAction(stage, betSize, callAmount, minRaise, maxRaise, raisesRemaining, potSize); }); // wait X amount of time for task to complete // if method has not returned in time then use default action if (_task.Wait(_botTimeOutMilliSeconds)) { playersAction = _playersAction; playersBetAmount = _playersBetAmount; } else { // Note that the task is still running in the background Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunGetAction(stage, betSize, callAmount, minRaise, maxRaise, raisesRemaining, potSize); playersAction = _playersAction; playersBetAmount = _playersBetAmount; } ValidateAction(stage, callAmount, minRaise, maxRaise, raisesRemaining, potSize, ref playersAction, ref playersBetAmount); TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}, {5}, {6}", _handNum, stage, PlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond, playersAction, playersBetAmount)); }
public void SeeBoardCard(EBoardCardType cardType, Card boardCard) { if (_botTimeOutMilliSeconds > 0) { if (!IsBotBusy()) { _task = Task.Run(() => { RunSeeBoardCard(cardType, boardCard); }); // wait X amount of time for task to complete if (!_task.Wait(_botTimeOutMilliSeconds)) { // Note that the task is still running in the background _bIsBotBusy = true; Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunSeeBoardCard(cardType, boardCard); } Stage stage = Stage.StageFlop; if (cardType == EBoardCardType.BoardRiver) { stage = Stage.StageRiver; } else if (cardType == EBoardCardType.BoardTurn) { stage = Stage.StageTurn; } TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}, {5}, {6}", _handNum, stage, PlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond, cardType, boardCard)); }
public void InitHand(int handNum, int numPlayers, List <PlayerInfo> players, int dealerId, int smallBlindSize, int bigBlindSize) { _handNum++; IsActive = IsAlive; StackSizeAtStartOfHand = StackSize; if (_botTimeOutMilliSeconds > 0) { // if bot is busy at the start of the hand then don't send any messages for the hand (so it doesn't get messages for half a hand) _bIsBotBusy = (_task != null && !_task.IsCompleted); if (!IsBotBusy()) { _task = Task.Run(() => { RunInitHand(handNum, numPlayers, players, dealerId, smallBlindSize, bigBlindSize); }); // wait X amount of time for task to complete if (!_task.Wait(_botTimeOutMilliSeconds)) { // Note that the task is still running in the background _bIsBotBusy = true; Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunInitHand(handNum, numPlayers, players, dealerId, smallBlindSize, bigBlindSize); } TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}", _handNum, Stage.StagePreflop, PlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond)); }
public void EndOfGame(int numPlayers, List <PlayerInfo> players) { if (_botTimeOutMilliSeconds > 0) { if (!IsBotBusy()) { _task = Task.Run(() => { RunEndOfGame(numPlayers, players); }); // wait X amount of time for task to complete if (!_task.Wait(_botTimeOutMilliSeconds)) { // Note that the task is still running in the background _bIsBotBusy = true; Logger.Log("TIMEOUT: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // bot is busy still running the previous task Logger.Log("BOT BUSY: {0} Player {1}", MethodBase.GetCurrentMethod().Name, PlayerNum); } } else { // timeout code disabled - just called method directly RunEndOfGame(numPlayers, players); } TimingLogger.Log(string.Format("{0}, {1}, {2}, {3}, {4:0.0000}", _handNum, Stage.StageShowdown, PlayerNum, MethodBase.GetCurrentMethod().Name, (double)_lastMethodElapsedTime.Ticks / TimeSpan.TicksPerMillisecond)); // !!! should I be doing this here? if (_newDomain != null) { AppDomain.Unload(_newDomain); } }
protected override void OnCreate(Bundle bundle) { TimingLogger timing = null; if (firstOnCreate) { timing = new TimingLogger("startup-timing: OnCreate reached"); } TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); if (firstOnCreate) { timing.Stop("startup-timing: OnCreate end reached"); firstOnCreate = false; } }
public TimingLoggerConsole(TimingLogger logger) { _outWriter = new(logger, LogLevel.None); _errorWriter = new(logger, LogLevel.Error); }
public IList <TestCase> Convert(NUnitResults discoveryResults, string assemblyPath) { if (discoveryResults == null) { return(new List <TestCase>()); } AssemblyPath = assemblyPath; var timing = new TimingLogger(Settings, TestLog); if (Settings.DiscoveryMethod != DiscoveryMethod.Legacy) { TestRun = ConvertXml(discoveryResults); } var nunitTestCases = discoveryResults.TestCases(); // As a side effect of calling TestConverter.ConvertTestCase, // the converter's cache of all test cases is populated as well. // All future calls to convert a test case may now use the cache. if (Settings.DiscoveryMethod == DiscoveryMethod.Legacy) { converterForXml = new TestConverterForXml(TestLog, AssemblyPath, Settings); foreach (XmlNode testNode in nunitTestCases) { loadedTestCases.Add(converterForXml.ConvertTestCase(new NUnitEventTestCase(testNode))); } TestLog.Info( $" NUnit3TestExecutor discovered {loadedTestCases.Count} of {nunitTestCases.Count} NUnit test cases using Legacy discovery mode"); } else { converter = new TestConverter(TestLog, AssemblyPath, Settings, this); var isExplicit = TestRun.IsExplicit; var testCases = RunnableTestCases(isExplicit); foreach (var testNode in testCases) { loadedTestCases.Add(converter.ConvertTestCase(testNode)); } var msg = isExplicit ? "Explicit run" : "Non-Explicit run"; TestLog.Info( $" NUnit3TestExecutor discovered {loadedTestCases.Count} of {nunitTestCases.Count} NUnit test cases using Current Discovery mode, {msg}"); } timing.LogTime("Converting test cases "); return(loadedTestCases); IEnumerable <NUnitDiscoveryTestCase> RunnableTestCases(bool isExplicit) { IEnumerable <NUnitDiscoveryTestCase> result; if (isExplicit || !Settings.DesignMode) { result = TestRun.TestAssembly.AllTestCases; } else { result = TestRun.TestAssembly.RunnableTestCases; } return(result); } }
static void Main(string [] args) { bool bGraphicsDisplay = false; try { string sConfigFile; if (args.Length > 0) { sConfigFile = args[0]; } else { sConfigFile = "HoldemConfig.xml"; } var sOutputBase = Path.GetFileNameWithoutExtension(sConfigFile); int numGames = 1; if (args.Length > 1) { if (!Int32.TryParse(args[1], out numGames)) { numGames = 1; } } int gameNum = 0; while (gameNum < numGames) { var prog = new Program(); prog.PlayGame(sConfigFile, sOutputBase + "." + gameNum); bGraphicsDisplay = prog.GraphicsDisplay(); Logger.Close(); TimingLogger.Close(); gameNum++; } } catch (Exception e) { var sExceptionMessage = "EXCEPTION : " + e + "\nPlease send gamelog.txt to [email protected]"; Console.WriteLine(sExceptionMessage); } finally { Logger.Close(); TimingLogger.Close(); if (bGraphicsDisplay) { Console.SetCursorPosition(0, 0); } Console.WriteLine("-- press any key to exit --"); Console.ReadKey(); } }
private void LoadConfig(string sConfigFile, string sOutputBase) { var doc = XDocument.Load(sConfigFile); // This must happen before we write the first log message Logger.Initialize("logs\\" + sOutputBase + "_gamelog.txt"); TimingLogger.Initialize("logs\\" + sOutputBase + "_calllog.csv"); Logger.Log("--- *** CONFIG *** ---"); Logger.Log(doc.ToString()); var holdemConfig = doc.Element("HoldemConfig"); if (holdemConfig == null) { throw new Exception("Unable to find HoldemConfig element in HoldemConfig.xml"); } var gameRules = holdemConfig.Element("GameRules"); if (gameRules == null) { throw new Exception("Unable to find GameRules element in HoldemConfig.xml"); } // Get game rules var gameConfigSettings = new Dictionary <string, string> { { "smallBlind", _smallBlindSize.ToString() }, { "bigBlind", _bigBlindSize.ToString() }, { "startingStack", _startingStack.ToString() }, { "maxNumRaisesPerBettingRound", _maxNumRaisesPerBettingRound.ToString() }, { "maxHands", _maxHands.ToString() }, { "doubleBlindFrequency", _doubleBlindFrequency.ToString() }, { "botTimeOutMilliSeconds", _botTimeOutMilliSeconds.ToString() }, { "randomDealer", _bRandomDealer.ToString() }, { "randomSeating", _bRandomSeating.ToString() }, { "pauseAfterEachHand", _bPauseAfterEachHand.ToString() }, { "sleepAfterActionMilliSeconds", _sleepAfterActionMilliSeconds.ToString() }, { "graphicsDisplay", _bGraphicsDisplay.ToString() } }; // add defaults to dictionary // add or update values in dictionary from values in xml foreach (var attr in gameRules.Attributes()) { if (gameConfigSettings.ContainsKey(attr.Name.ToString())) { gameConfigSettings[attr.Name.ToString()] = attr.Value; } else { gameConfigSettings.Add(attr.Name.ToString(), attr.Value); } } // read values from dictionary _smallBlindSize = Convert.ToInt32(gameConfigSettings["smallBlind"]); _bigBlindSize = Convert.ToInt32(gameConfigSettings["bigBlind"]); _startingStack = Convert.ToInt32(gameConfigSettings["startingStack"]); _maxNumRaisesPerBettingRound = Convert.ToInt32(gameConfigSettings["maxNumRaisesPerBettingRound"]); _maxHands = Convert.ToInt32(gameConfigSettings["maxHands"]); _doubleBlindFrequency = Convert.ToInt32(gameConfigSettings["doubleBlindFrequency"]); _botTimeOutMilliSeconds = Convert.ToInt32(gameConfigSettings["botTimeOutMilliSeconds"]); _bRandomDealer = Convert.ToBoolean(gameConfigSettings["randomDealer"]); _bRandomSeating = Convert.ToBoolean(gameConfigSettings["randomSeating"]); _bPauseAfterEachHand = Convert.ToBoolean(gameConfigSettings["pauseAfterEachHand"]); _sleepAfterActionMilliSeconds = Convert.ToInt32(gameConfigSettings["sleepAfterActionMilliSeconds"]); _bGraphicsDisplay = Convert.ToBoolean(gameConfigSettings["graphicsDisplay"]); // setup displays if (_bGraphicsDisplay) { //_displays.Add(new GraphicsDisplay()); _eventHandlers.Add(new ConsoleDisplayHandler()); } if (_sleepAfterActionMilliSeconds > 0) { _eventHandlers.Add(new SleepHandler(_sleepAfterActionMilliSeconds)); } var textDisplay = new TextDisplay(); textDisplay.SetWriteToConsole(!_bGraphicsDisplay); _displays.Add(textDisplay); var gameConfig = new GameConfig { ConfigFileName = sConfigFile, OutputBase = sOutputBase, SmallBlindSize = _smallBlindSize, BigBlindSize = _bigBlindSize, StartingStack = _startingStack, MaxNumRaisesPerBettingRound = _maxNumRaisesPerBettingRound, MaxHands = _maxHands, DoubleBlindFrequency = _doubleBlindFrequency, BotTimeOutMilliSeconds = _botTimeOutMilliSeconds, RandomDealer = _bRandomDealer, RandomSeating = _bRandomSeating }; // Create players var xplayers = doc.Descendants("Player").ToList(); int i; var numBots = xplayers.Count; if (numBots == 0) { throw new Exception("No Player elements found in HoldemConfig.xml"); } _allBots = new List <ServerHoldemPlayer>(); var playerConfigSettingsList = new List <Dictionary <string, string> >(); // Create bots - work out how many player and how many observers var botNum = 0; foreach (var player in xplayers) { var playerConfigSettings = player.Attributes().ToDictionary(attr => attr.Name.ToString(), attr => attr.Value); // read player attributes, add to player config string sValue; bool isTrusted = false; if (playerConfigSettings.TryGetValue("trusted", out sValue)) { Boolean.TryParse(sValue, out isTrusted); } playerConfigSettingsList.Add(playerConfigSettings); var bot = new ServerHoldemPlayer(botNum, playerConfigSettings["dll"], isTrusted); _allBots.Add(bot); botNum++; if (!bot.IsObserver) { _numPlayers++; } } if (_numPlayers < 2 || _numPlayers > 23) { throw new Exception($"The number of live (non observer) players found is {_numPlayers}. It must be between 2 and 23"); } // Create array to hold players (actual players not observers) _players = new ServerHoldemPlayer[_numPlayers]; var rnd = new Random(); List <int> unusedSlots = new List <int>(); for (i = 0; i < _numPlayers; i++) { unusedSlots.Add(i); } // assign id to each bot and call InitPlayer int nextObserverId = _numPlayers; int nextPlayerId = 0; botNum = 0; foreach (var bot in _allBots) { int botId; // work out player id if (bot.IsObserver) { botId = nextObserverId; nextObserverId++; } else { if (_bRandomSeating) { int pos = rnd.Next(unusedSlots.Count); botId = unusedSlots[pos]; unusedSlots.RemoveAt(pos); } else { botId = nextPlayerId; nextPlayerId++; } } // Need to ensure that playerId matches a players index in _players because some code is relying on this bot.InitPlayer(botId, gameConfig, playerConfigSettingsList[botNum]); // Just call this to preload Name and write entry to timing log // ReSharper disable once UnusedVariable var sName = bot.Name; // todo: properties shouldn't do anything, so should handle whatever this is doing differently botNum++; if (!bot.IsObserver) { _players[botId] = bot; } } foreach (var display in _displays) { display.Initialise(gameConfig, _numPlayers, _sleepAfterActionMilliSeconds); } }
public void DiscoverTests(IEnumerable <string> sources, IDiscoveryContext discoveryContext, IMessageLogger messageLogger, ITestCaseDiscoverySink discoverySink) { Initialize(discoveryContext, messageLogger); CheckIfDebug(); TestLog.Info($"NUnit Adapter {AdapterVersion}: Test discovery starting"); // Ensure any channels registered by other adapters are unregistered CleanUpRegisteredChannels(); if (Settings.InProcDataCollectorsAvailable && sources.Count() > 1) { TestLog.Error("Unexpected to discover tests in multiple assemblies when InProcDataCollectors specified in run configuration."); Unload(); return; } foreach (string sourceAssembly in sources) { string sourceAssemblyPath = Path.IsPathRooted(sourceAssembly) ? sourceAssembly : Path.Combine(Directory.GetCurrentDirectory(), sourceAssembly); TestLog.Debug("Processing " + sourceAssembly); if (Settings.DumpXmlTestDiscovery) { dumpXml = new DumpXml(sourceAssemblyPath); } try { var package = CreateTestPackage(sourceAssemblyPath, null); NUnitEngineAdapter.CreateRunner(package); var results = NUnitEngineAdapter.Explore(); dumpXml?.AddString(results.AsString()); if (results.IsRunnable) { int cases; using (var testConverter = new TestConverterForXml(TestLog, sourceAssemblyPath, Settings)) { var timing = new TimingLogger(Settings, TestLog); cases = ProcessTestCases(results, discoverySink, testConverter); timing.LogTime("Discovery/Processing/Converting:"); } TestLog.Debug($"Discovered {cases} test cases"); // Only save if seed is not specified in runsettings // This allows workaround in case there is no valid // location in which the seed may be saved. if (cases > 0 && !Settings.RandomSeedSpecified) { Settings.SaveRandomSeed(Path.GetDirectoryName(sourceAssemblyPath)); } } else { if (results.HasNoNUnitTests) { if (Settings.Verbosity > 0) { TestLog.Info("Assembly contains no NUnit 3.0 tests: " + sourceAssembly); } } else { TestLog.Info("NUnit failed to load " + sourceAssembly); } } } catch (NUnitEngineException e) { if (e.InnerException is BadImageFormatException) { // we skip the native c++ binaries that we don't support. TestLog.Warning("Assembly not supported: " + sourceAssembly); } else { TestLog.Warning("Exception thrown discovering tests in " + sourceAssembly, e); } } catch (BadImageFormatException) { // we skip the native c++ binaries that we don't support. TestLog.Warning("Assembly not supported: " + sourceAssembly); } catch (FileNotFoundException ex) { // Either the NUnit framework was not referenced by the test assembly // or some other error occurred. Not a problem if not an NUnit assembly. TestLog.Warning("Dependent Assembly " + ex.FileName + " of " + sourceAssembly + " not found. Can be ignored if not an NUnit project."); } catch (FileLoadException ex) { // Attempts to load an invalid assembly, or an assembly with missing dependencies TestLog.Warning("Assembly " + ex.FileName + " loaded through " + sourceAssembly + " failed. Assembly is ignored. Correct deployment of dependencies if this is an error."); } catch (TypeLoadException ex) { if (ex.TypeName == "NUnit.Framework.Api.FrameworkController") { TestLog.Warning(" Skipping NUnit 2.x test assembly"); } else { TestLog.Warning("Exception thrown discovering tests in " + sourceAssembly, ex); } } catch (Exception ex) { TestLog.Warning("Exception thrown discovering tests in " + sourceAssembly, ex); } finally { dumpXml?.DumpForDiscovery(); NUnitEngineAdapter?.CloseRunner(); } } TestLog.Info($"NUnit Adapter {AdapterVersion}: Test discovery complete"); Unload(); }
private void InitUIHeader() { using (TimingLogger.Track("InitUIHeader()")) { // add the action filter using (TimingLogger.Track("... setup category dropdown")) { var groupNames = GetGroupNames().OrderBy((x) => x).ToList(); if (_actionFilterStorable == null) { _actionFilterStorable = new JSONStorableStringChooser("category", groupNames, ActionCategory, ""); _actionFilterUi = Plugin.CreateScrollablePopup(_actionFilterStorable); _actionFilterUi.labelWidth = 0f; _actionFilterUi.popup.onValueChangeHandlers += (newValue) => { var currentSubCategory = ActionSubCategory; ActionCategory = newValue; var subCategories = GetSubGroupNames(newValue).ToList(); if (subCategories.Count == 0) { ActionSubCategory = ""; } else if (!subCategories.Any((c) => c.Equals(currentSubCategory))) { ActionSubCategory = subCategories[0]; } InitializeUI(); // TODO: figure out how to actually get this UI element to // show up on top of the UI elements just below it instead // of behind _actionFilterUi.popup.Toggle(); _actionFilterUi.popup.Toggle(); }; } else { _actionFilterStorable.choices = groupNames; } } using (TimingLogger.Track("... setup subcategory dropdown")) { // add the subcategory filter var subCategories = GetSubGroupNames(ActionCategory).OrderBy((x) => x).ToList(); if (_actionSubCatFilterStorable == null) { _actionSubCatFilterStorable = new JSONStorableStringChooser("subcategory", subCategories, ActionSubCategory, ""); _actionSubCatFilterUi = Plugin.CreateScrollablePopup(_actionSubCatFilterStorable, rightSide: true); _actionSubCatFilterUi.height = _actionFilterUi.height; _actionSubCatFilterUi.labelWidth = 0f; _actionSubCatFilterUi.popup.onValueChangeHandlers += (newValue) => { ActionSubCategory = newValue; InitializeUI(); // TODO: figure out how to actually get this UI element to // show up on top of the UI elements just below it instead // of behind _actionSubCatFilterUi.popup.Toggle(); _actionSubCatFilterUi.popup.Toggle(); }; } else { _actionSubCatFilterStorable.choices = subCategories; _actionSubCatFilterUi.popup.currentValueNoCallback = ActionSubCategory; } } } }
private static readonly LogWriter sLog_TagBC = sLog7.WithTags("TagB", "TagC"); // same as sLog7, but tags messages with 'TagB' and 'TagC' private static void Main(string[] args) { // Initialize the logging subsystem bool initConfig = false; Log.Initialize <VolatileLogConfiguration>( // volatile configuration (programmatic configuration only, no persistence) // Log.Initialize<FileBackedLogConfiguration>( // file-based configuration (default location, beside the executable with file extension '.gplogconf') config => { // VolatileLogConfiguration only: // Always initialize the configuration programmatically initConfig = false; // for VolatileLogConfiguration // FileBackedLogConfiguration only: // Initialize the configuration only, if the configuration file does not exist, yet // config.Path = "./my-conf.gplogconf"; // override the default location of the file // initConfig = !File.Exists(config.FullPath); if (initConfig) { // Add configuration for log writers that attach 'TagA' // - set base log level to 'None' effectively silencing the log writer // - include log level 'Notice' // - no excluded log levels // - tags must contain 'TagA' // => enabled log levels: 'Notice' config.AddLogWritersByWildcard( "*", x => x .WithTag("TagA") .WithBaseLevel(LogLevel.None) .WithLevel(LogLevel.Notice)); // Add configuration for log writers that attach 'TagB' and/or 'TagC' // - set base log level to 'None' effectively silencing the log writer // - include log level 'Warning' // - no excluded log levels // - tags must contain 'TagB' and/or 'TagC' // => enabled log levels: 'Warning' config.AddLogWritersByWildcard( "*", x => x .WithTagRegex("^Tag[BC]$") .WithBaseLevel(LogLevel.None) .WithLevel(LogLevel.Warning)); // Add configuration for log writer 'GriffinPlus.Lib.Logging.Demo.MyClass1' only // - set base log level to 'Notice' => enables log level 'Emergency', 'Alert', 'Critical', 'Error', 'Warning' and 'Notice' // - include log level 'Trace' // - exclude log level 'Warning' // - tags are not evaluated // => enabled log levels: 'Emergency', 'Alert', 'Critical', 'Error', 'Notice', 'Trace' config.AddLogWriter <MyClass1>( x => x .WithBaseLevel(LogLevel.Notice) .WithLevel(LogLevel.Trace) .WithoutLevel("Warning")); // Add configuration for log writer 'GriffinPlus.Lib.Logging.Demo.MyClass2' only // - set base log level to 'None' effectively silencing the log writer // - no included/excluded log levels // - tags are not evaluated // => no enabled log levels config.AddLogWriter( typeof(MyClass2), x => x.WithBaseLevel(LogLevel.None)); // Add configuration for log writer 'GriffinPlus.Lib.Logging.Demo.MyClass3' only // - set base log level to 'All' enabling all log levels (including aspects) // - exclude all log levels from 'Informational' up to 'Trace' ('Informational', 'Debug', 'Trace') // - tags are not evaluated // => enabled log levels: All log levels, but 'Informational', 'Debug', 'Trace' config.AddLogWriter( typeof(MyClass3), x => x .WithBaseLevel(LogLevel.All) .WithoutLevelRange(LogLevel.Informational, LogLevel.Debug)); // Add configuration for log writers matching regex pattern // - pattern matches 'GriffinPlus.Lib.Logging.Demo.MyClassA' and 'GriffinPlus.Lib.Logging.Demo.MyClassB' // - base level defaults to 'Error' => enables log level 'Emergency', 'Alert', 'Critical', 'Error' // - include all log levels from 'Informational' up to 'Trace' ('Informational', 'Debug', 'Trace') // - no excluded log levels // - tags are not evaluated // => enabled log levels: 'Emergency', 'Alert', 'Critical', 'Error', 'Informational', 'Debug' config.AddLogWritersByRegex( "^GriffinPlus.Lib.Logging.Demo.MyClass[A-Z]$", x => x.WithLevelRange(LogLevel.Informational, LogLevel.Debug)); // Add configuration for log writers matching wildcard pattern // - applies to 'GriffinPlus.Lib.Logging.Demo.MyClass4' only // (other writers are handled by preceding steps) // - base level defaults to 'Error' => enables log level 'Emergency', 'Alert', 'Critical', 'Error' // - include log level 'Trace' // - no excluded log levels // - tags are not evaluated // => enabled log levels: 'Emergency', 'Alert', 'Critical', 'Error', 'Trace' config.AddLogWritersByWildcard( "GriffinPlus.Lib.Logging.Demo.MyClass*", x => x.WithLevel(LogLevel.Trace)); // Add configuration for log writer 'My Fancy Writer' // (matches everything that was not handled explicitly before) // - set base log level to 'None' effectively silencing the log writer // - include aspect log level 'Demo Aspect' // - no excluded log levels // - tags are not evaluated // => enabled log levels: 'Demo Aspect' config.AddLogWriter( "My Fancy Writer", x => x .WithBaseLevel(LogLevel.None) .WithLevel("Demo Aspect")); // Add configuration for log writer 'Timing' to enable logging time measurements written by the internal // 'Timing' log writer (see below for time measurements) config.AddLogWriterTiming(); // Add default configuration for log writers that have not been handled up to this point // - base level defaults to level 'Notice' // - no included/excluded log levels // => enabled log levels: 'Emergency', 'Alert', 'Critical', 'Error', 'Warning', 'Notice' config.AddLogWriterDefault(); } }, builder => { // Create log message formatter that prints log messages in a tabular fashion var tableFormatter = new TableMessageFormatter(); tableFormatter.AddTimestampColumn("yyyy-MM-dd HH:mm:ss.fff"); // use custom timestamp format tableFormatter.AddProcessIdColumn(); tableFormatter.AddProcessNameColumn(); tableFormatter.AddApplicationNameColumn(); tableFormatter.AddLogWriterColumn(); tableFormatter.AddLogLevelColumn(); tableFormatter.AddTagsColumn(); tableFormatter.AddTextColumn(); // Create log message formatter that prints log messages as JSON var jsonFormatter = new JsonMessageFormatter(); jsonFormatter.Style = JsonMessageFormatterStyle.Beautified; jsonFormatter.AddTimestampField("yyyy-MM-dd HH:mm:ss.fff"); // use custom timestamp format jsonFormatter.AddProcessIdField(); jsonFormatter.AddProcessNameField(); jsonFormatter.AddApplicationNameField(); jsonFormatter.AddLogWriterField(); jsonFormatter.AddLogLevelField(); jsonFormatter.AddTagsField(); jsonFormatter.AddTextField(); // Create pipeline stage for printing to the console builder.Add <ConsoleWriterPipelineStage>( "Console", stage => { stage.MessageQueueSize = 500; // buffer up to 500 messages (default) stage.DiscardMessagesIfQueueFull = false; // block if the queue is full (default) stage.ShutdownTimeout = TimeSpan.FromMilliseconds(5000); // wait up to 5000ms for the stage to shut down (default) stage.Formatter = tableFormatter; // use specific formatter stage.DefaultStream = ConsoleOutputStream.Stdout; // print to stdout by default (default) stage.MapLogLevelToStream(LogLevel.Emergency, ConsoleOutputStream.Stderr); // print errors to stderr stage.MapLogLevelToStream(LogLevel.Alert, ConsoleOutputStream.Stderr); // stage.MapLogLevelToStream(LogLevel.Critical, ConsoleOutputStream.Stderr); // stage.MapLogLevelToStream(LogLevel.Error, ConsoleOutputStream.Stderr); // }); // Create pipeline stage for writing to a file builder.Add <FileWriterPipelineStage>( "File", stage => { stage.Path = "Unnamed.log"; // Path of the file to write to (default) stage.Append = false; // do not append written messages to existing log file (default) stage.MessageQueueSize = 500; // buffer up to 500 messages (default) stage.DiscardMessagesIfQueueFull = false; // block if the queue is full (default) stage.ShutdownTimeout = TimeSpan.FromMilliseconds(5000); // wait up to 5000ms for the stage to shut down (default) stage.Formatter = jsonFormatter; // use specific formatter }); // Create pipeline stage that forwards to Elasticsearch using the Elasticsearch Common Schema (ECS) version 1.10. // The stage supports the following password-based authentication schemes: // - Basic authentication (with custom credentials only) // - Digest authentication (with custom credentials only) // - NTLM Authentication (with custom credentials and login user credentials) // - Kerberos Authentication (with custom credentials and login user credentials) // - Negotiate Authentication (with custom credentials and login user credentials) builder.Add <ElasticsearchPipelineStage>( "Elasticsearch", stage => { stage.ApiBaseUrls = new[] { new Uri("http://127.0.0.1:9200/") }; // use local elasticsearch server stage.AuthenticationSchemes = AuthenticationScheme.PasswordBased; // support all password based authentication schemes stage.Username = ""; // username to use when authenticating (empty to use login user) stage.Password = ""; // password to use when authenticating (empty to use login user) stage.Domain = ""; // domain to use when authenticating (for schemes 'Digest', 'NTLM', 'Kerberos' and 'Negotiate') stage.BulkRequestMaxConcurrencyLevel = 5; // maximum number of requests on the line stage.BulkRequestMaxSize = 5 * 1024 * 1024; // maximum size of a bulk request stage.BulkRequestMaxMessageCount = 0; // maximum number of messages in a bulk request (0 = unlimited) stage.IndexName = "logs"; // elasticsearch index to write log messages into stage.OrganizationId = ""; // value of the 'organization.id' field stage.OrganizationName = ""; // value of the 'organization.name' field stage.SendQueueSize = 50000; // maximum number of messages the stage buffers before discarding messages }); }); // Save configuration, if it was initialized programmatically (after initialization the configuration is bound to // the pipeline stages, so stages can persist their settings in the configuration) if (initConfig) { Log.Configuration.Save(true); } // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // Use the logging subsystem // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // Get an aspect log level. var aspect = LogLevel.GetAspect("Demo Aspect"); // Write messages to all known log levels (predefined log levels + aspects). foreach (var level in LogLevel.KnownLevels) { sLog1.Write(level, "This is sLog1 writing using level '{0}'.", level.Name); sLog2.Write(level, "This is sLog2 writing using level '{0}'.", level.Name); sLog3.Write(level, "This is sLog3 writing using level '{0}'.", level.Name); sLog4.Write(level, "This is sLog4 writing using level '{0}'.", level.Name); sLog5.Write(level, "This is sLog5 writing using level '{0}'.", level.Name); sLog6.Write(level, "This is sLog6 writing using level '{0}'.", level.Name); sLog7.Write(level, "This is sLog7 writing using level '{0}'.", level.Name); sLog_TagA.Write(level, "This is sLog_TagA writing using level '{0}'.", level.Name); sLog_TagB.Write(level, "This is sLog_TagB writing using level '{0}'.", level.Name); sLog_TagBC.Write(level, "This is sLog_TagBC writing using level '{0}'.", level.Name); } // Use a timing logger to determine how long an operation takes. It uses log level 'Timing' and log writer // 'Timing' by default, so you need to ensure that the configuration lets these messages pass). sLog1.Write(LogLevel.Notice, "Presenting a timing logger with default settings..."); using (TimingLogger.Measure()) { Thread.Sleep(500); } // Use a timing logger, customize the log writer/level it uses and associate an operation name with the // measurement that is printed to the log as well. sLog1.Write(LogLevel.Notice, "A timing logger with custom log level/writer and operation name..."); using (TimingLogger.Measure(sLog1, LogLevel.Notice, "Waiting for 500ms")) { Thread.Sleep(500); } // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // Wait for the user to press a key to shut the logging subsystem down // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- Thread.Sleep(1000); Console.WriteLine(); Console.WriteLine("Press any key to shut the logging subsystem down..."); Console.ReadKey(); // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // Shut the logging subsystem down // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // Shut the logging subsystem down Log.Shutdown(); }