#pragma warning disable 1998 public static async void Initialize() #pragma warning restore 1998 { LocalizeDictionary.Instance.Culture = CultureInfo.GetCultureInfo("en-US"); _startUpTime = DateTime.UtcNow; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Config.Load(); Log.Info($"HDT: {Helper.GetCurrentVersion()}, Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}"); var splashScreenWindow = new SplashScreenWindow(); #if (SQUIRREL) if (Config.Instance.CheckForUpdates) { var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow); while (!updateCheck.IsCompleted) { await Task.Delay(500); if (splashScreenWindow.SkipUpdate) { break; } } } #endif splashScreenWindow.ShowConditional(); Log.Initialize(); ConfigManager.Run(); LocUtil.UpdateCultureInfo(); var newUser = ConfigManager.PreviousVersion == null; LogConfigUpdater.Run().Forget(); LogConfigWatcher.Start(); UITheme.InitializeTheme().Forget(); ThemeManager.Run(); ResourceMonitor.Run(); Game = new GameV2(); Game.SecretsManager.OnSecretsChanged += cards => Overlay.ShowSecrets(cards); MainWindow = new MainWindow(); MainWindow.LoadConfigSettings(); MainWindow.Show(); splashScreenWindow.Close(); if (Config.Instance.DisplayHsReplayNoteLive && ConfigManager.PreviousVersion != null && ConfigManager.PreviousVersion < new Version(1, 1, 0)) { MainWindow.FlyoutHsReplayNote.IsOpen = true; } if (ConfigManager.UpdatedVersion != null) { #if (!SQUIRREL) Updater.Cleanup(); #endif MainWindow.FlyoutUpdateNotes.IsOpen = true; MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion); #if (SQUIRREL && !DEV) if (Config.Instance.CheckForDevUpdates && !Config.Instance.AllowDevUpdates.HasValue) { MainWindow.ShowDevUpdatesMessage(); } #endif } DataIssueResolver.Run(); #if (!SQUIRREL) Helper.CopyReplayFiles(); #endif BackupManager.Run(); if (Config.Instance.PlayerWindowOnStart) { Windows.PlayerWindow.Show(); } if (Config.Instance.OpponentWindowOnStart) { Windows.OpponentWindow.Show(); } if (Config.Instance.TimerWindowOnStartup) { Windows.TimerWindow.Show(); } PluginManager.Instance.LoadPluginsFromDefaultPath(); MainWindow.Options.OptionsTrackerPlugins.Load(); PluginManager.Instance.StartUpdateAsync(); UpdateOverlayAsync(); if (Config.Instance.ShowCapturableOverlay) { Windows.CapturableOverlay = new CapturableOverlayWindow(); Windows.CapturableOverlay.Show(); } if (LogConfigUpdater.LogConfigUpdateFailed) { MainWindow.ShowLogConfigUpdateFailedMessage().Forget(); } else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning) { MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.").Forget(); Overlay.ShowRestartRequiredWarning(); } LogWatcherManger.Start(Game).Forget(); RemoteConfig.Instance.Load(); HotKeyManager.Load(); if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning) { HearthstoneRunner.StartHearthstone().Forget(); } HSReplayNetHelper.UpdateAccount().Forget(); Initialized = true; Influx.OnAppStart( Helper.GetCurrentVersion(), newUser, HSReplayNetOAuth.IsFullyAuthenticated, HSReplayNetOAuth.AccountData?.IsPremium?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false, (int)(DateTime.UtcNow - _startUpTime).TotalSeconds, PluginManager.Instance.Plugins.Count ); }
public static async void Initialize() { LocalizeDictionary.Instance.Culture = CultureInfo.GetCultureInfo("en-US"); _startUpTime = DateTime.UtcNow; Log.Info($"HDT: {Helper.GetCurrentVersion()}, Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Config.Load(); var splashScreenWindow = new SplashScreenWindow(); #if (SQUIRREL) if (Config.Instance.CheckForUpdates) { var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow); while (!updateCheck.IsCompleted) { await Task.Delay(500); if (splashScreenWindow.SkipUpdate) { break; } } } #endif splashScreenWindow.ShowConditional(); Log.Initialize(); ConfigManager.Run(); LocUtil.UpdateCultureInfo(); var newUser = ConfigManager.PreviousVersion == null; LogConfigUpdater.Run().Forget(); LogConfigWatcher.Start(); Helper.UpdateAppTheme(); ThemeManager.Run(); ResourceMonitor.Run(); Game = new GameV2(); LoginType loginType; var loggedIn = HearthStatsAPI.LoadCredentials(); if (!loggedIn && Config.Instance.ShowLoginDialog) { var loginWindow = new LoginWindow(); splashScreenWindow.Close(); loginWindow.ShowDialog(); if (loginWindow.LoginResult == LoginType.None) { Application.Current.Shutdown(); return; } loginType = loginWindow.LoginResult; splashScreenWindow = new SplashScreenWindow(); splashScreenWindow.ShowConditional(); } else { loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest; } MainWindow = new MainWindow(); MainWindow.LoadConfigSettings(); MainWindow.Show(); splashScreenWindow.Close(); if (Config.Instance.DisplayHsReplayNoteLive && ConfigManager.PreviousVersion != null && ConfigManager.PreviousVersion < new Version(1, 1, 0)) { MainWindow.FlyoutHsReplayNote.IsOpen = true; } if (ConfigManager.UpdatedVersion != null) { #if (!SQUIRREL) Updater.Cleanup(); #endif MainWindow.FlyoutUpdateNotes.IsOpen = true; MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion); } NetDeck.CheckForChromeExtention(); DataIssueResolver.Run(); #if (!SQUIRREL) Helper.CopyReplayFiles(); #endif BackupManager.Run(); if (Config.Instance.PlayerWindowOnStart) { Windows.PlayerWindow.Show(); } if (Config.Instance.OpponentWindowOnStart) { Windows.OpponentWindow.Show(); } if (Config.Instance.TimerWindowOnStartup) { Windows.TimerWindow.Show(); } if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn) { HearthStatsManager.SyncAsync(background: true); } PluginManager.Instance.LoadPlugins(); MainWindow.Options.OptionsTrackerPlugins.Load(); PluginManager.Instance.StartUpdateAsync(); UpdateOverlayAsync(); if (Config.Instance.ShowCapturableOverlay) { Windows.CapturableOverlay = new CapturableOverlayWindow(); Windows.CapturableOverlay.Show(); } if (LogConfigUpdater.LogConfigUpdateFailed) { MainWindow.ShowLogConfigUpdateFailedMessage().Forget(); } else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning) { MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted."); Overlay.ShowRestartRequiredWarning(); } LogReaderManager.Start(Game).Forget(); NewsUpdater.UpdateAsync(); HotKeyManager.Load(); if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning) { Helper.StartHearthstoneAsync().Forget(); } ApiWrapper.UpdateAccountStatus().Forget(); Initialized = true; Influx.OnAppStart(Helper.GetCurrentVersion(), loginType, newUser, (int)(DateTime.UtcNow - _startUpTime).TotalSeconds); }
//private bool rendering; public virtual void Render() { /* * if (rendering) * { * return; // can be dangerous, rendering from two threads? * } * * rendering = true; * * try * { */ DateTime t = DateTime.Now; if (image != null && Map != null && (Map.Size.Width != image.Width || Map.Size.Height != image.Height)) // check if we need to re-create bitmap { ClearImage(); } if (Map == null) { if (image != null) { ClearImage(); } return; } if (image == null) { image = new Bitmap(Map.Size.Width, Map.Size.Height, PixelFormat.Format32bppPArgb); ResourceMonitor.OnResourceAllocated(this, image); } if (!Visible || MaxVisible < Map.Zoom || MinVisible > Map.Zoom) { return; } Graphics graphics = Graphics.FromImage(image); graphics.Transform = Map.MapTransform.Clone(); graphics.Clear(Color.Transparent); graphics.PageUnit = GraphicsUnit.Pixel; // call virtual implementation which renders layer OnRender(graphics, Map); if (LabelLayer != null && LabelLayer.Visible) { ((LabelLayer)LabelLayer).OnRender(graphics, map); } // fire event if (LayerRendered != null) { LayerRendered(this, graphics); } graphics.Dispose(); lastRenderDuration = (DateTime.Now - t).Milliseconds; /* * } * finally * { * rendering = false; * } */ RenderRequired = false; }
/// <summary> /// Renders the map to an image /// </summary> /// <returns></returns> public virtual Image Render() { // DateTime startTime = DateTime.Now; // Used when logging Rendering time of Map if (Size.IsEmpty) { return(null); // nothing to render } if (MapRendering != null) { MapRendering(null); } if (image != null && (Size.Width != image.Width || Size.Height != image.Height)) // re-create only when it is required { image.Dispose(); ResourceMonitor.OnResourceDeallocated(this, image); image = null; } if (image == null) { image = new Bitmap(Size.Width, Size.Height, PixelFormat.Format32bppPArgb); ResourceMonitor.OnResourceAllocated(this, image); } if (rendering) { return(null); } rendering = true; // TODO: draw using multiple threads /* Action<int> renderLayer = delegate(int i) * { * if (Layers[i].RenderRequired) * { * Layers[i].Render(); * } * }; * Parallel.For(0, Layers.Count, renderLayer); */ var visibleLayers = GetAllMapLayers(layers, true, true).OrderByDescending(l => l.RenderOrder).ToArray(); // draw decoration layers on top var gridVectorLayer = GetGridLayer(); if (gridVectorLayer != null) { visibleLayers = visibleLayers.Concat(new[] { gridVectorLayer }).ToArray(); } // merge all layer bitmaps var g = Graphics.FromImage(image); g.Clear(BackColor); foreach (var layer in visibleLayers) { if (!(layer.MaxVisible >= Zoom) || !(layer.MinVisible < Zoom)) { continue; } if (layer.RenderRequired || layer.Image == null) { layer.Render(); } if (layer.Image == null) { continue; } if (Math.Abs(layer.Opacity - 1.0) > 0.0000001) { var srcWidth = layer.Image.Width; var srcHeight = layer.Image.Height; g.DrawImage(layer.Image, new Rectangle(0, 0, srcWidth, srcHeight), 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel, CalculateOpacityImageAttributes(layer)); } else { g.DrawImage(layer.Image, 0, 0); } if (MapLayerRendered != null) { MapLayerRendered(g, layer); } if (layer.LastRenderDuration < 100) // do not keep Bitmap if it is very fast to render { layer.ClearImage(); } } g.Transform = MapTransform; g.PageUnit = GraphicsUnit.Pixel; if (MapRendered != null) { MapRendered(g); } g.Dispose(); foreach (var layer in Layers) { ClearLayerImages(layer); } // don't delete, enable when optimizing performance //double dt = (DateTime.Now - startTime).TotalMilliseconds; //log.DebugFormat("Map rendered in {0:F0} ms, size {1} x {2} px", dt, Size.Width, Size.Height); RenderRequired = false; rendering = false; return(Image); }
private async Task RandomisedTest(RandomConfig config) { // ARRANGE var testLogger = new TestOutputLogger(); var groupName = Guid.NewGuid().ToString(); await this.zkHelper.InitializeAsync("/rebalanser", TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(30)); await this.zkHelper.PrepareResourceGroupAsync(groupName, "res", config.ResourceCount); var resourceMonitor = new ResourceMonitor(); List <int> resSuffixes = new List <int>(); for (int i = 0; i < config.ResourceCount; i++) { resourceMonitor.CreateResource($"res{i}"); resSuffixes.Add(i); } var clientOptions = new ClientOptions() { AutoRecoveryOnError = true, RestartDelay = TimeSpan.FromSeconds(10), OnAssignmentDelay = config.OnAssignmentDelay }; var clients = new List <TestClient>(); for (int i = 0; i < config.ClientCount; i++) { clients.Add(new TestClient(resourceMonitor, groupName, clientOptions, config.OnStartEventHandlerTime, config.OnStopEventHandlerTime, config.RandomiseEventHandlerTimes)); } for (int i = 0; i < config.ClientCount; i++) { if (config.StartUpClientInterval.TotalMilliseconds > 0) { await Task.Delay(config.StartUpClientInterval); } await clients[i].StartAsync(ZkHelper.ZooKeeperHosts, "/rebalanser", this.currentConfig.SessionTimeout, this.currentConfig.ConnectTimeout, this.currentConfig.minRebalancingInterval, testLogger); } await Task.Delay(TimeSpan.FromSeconds(30)); // ACT var sw = new Stopwatch(); sw.Start(); var rand = new Random(Guid.NewGuid().GetHashCode()); int testCounter = 0; while (sw.Elapsed < config.TestDuration) { testLogger.Info("TEST RUNNER", "Test " + testCounter); // action == 0 -> add/remove a client // action == 1 -> add/remove a resource var action = rand.Next(2); if (action == 0) { var clientIndex = rand.Next(config.ClientCount); await clients[clientIndex].PerformActionAsync(ZkHelper.ZooKeeperHosts, "/rebalanser", this.currentConfig.SessionTimeout, this.currentConfig.ConnectTimeout, this.currentConfig.minRebalancingInterval, testLogger); } else { // resAction == 0 && resources exist -> remove a resource // else add a resource var resAction = rand.Next(2); if (resAction == 0 || !resSuffixes.Any()) { var resSuffix = resSuffixes.Any() ? resSuffixes.Max() + 1 : 0; resSuffixes.Add(resSuffix); resourceMonitor.AddResource($"res{resSuffix}"); testLogger.Info("TEST RUNNER", "Adding a resource"); await this.zkHelper.AddResourceAsync(groupName, $"res{resSuffix}"); testLogger.Info("TEST RUNNER", "Added a resource"); } else { var index = rand.Next(resSuffixes.Count); var resSuffix = resSuffixes[index]; resSuffixes.RemoveAt(index); resourceMonitor.RemoveResource($"res{resSuffix}"); testLogger.Info("TEST RUNNER", "Removing a resource"); await this.zkHelper.DeleteResourceAsync(groupName, $"res{resSuffix}"); testLogger.Info("TEST RUNNER", "Removed a resource"); } } // wait for the configured period of time before making asserts // this gives the necessary time for rebalancing TimeSpan currentTestInterval; if (config.RandomiseInterval) { currentTestInterval = TimeSpan.FromMilliseconds(rand.Next((int)config.MaxInterval.TotalMilliseconds)); } else { currentTestInterval = config.MaxInterval; } await Task.Delay(currentTestInterval); resourceMonitor.PrintEvents($"/home/jack/tmp/rebalanser-zk/test-{groupName}"); // check for double assignments. All test scenarios must check this. No matter // what happens, we can never allow double assignments - ever if (resourceMonitor.DoubleAssignmentsExist()) { foreach (var violation in resourceMonitor.GetDoubleAssignments()) { testLogger.Error("TEST RUNNER", violation.ToString()); } } Assert.False(resourceMonitor.DoubleAssignmentsExist()); // depending on the type of test, we'll ensure that all resources have been assigned // some tests that have extremely short durations between events do not leave enough time // for rebalancing and so do not perform this check. The conditional check will // only perform this check when a long enough time period has been allowed for rebalancing to complete if (config.CheckType == CheckType.FullCheck) { if (clients.Any(x => x.Started)) { testLogger.Info("TEST RUNNER", "Perform all resources assigned check"); Assert.True(resourceMonitor.AllResourcesAssigned()); } } else if (config.CheckType == CheckType.ConditionalCheck) { if (testCounter % config.ConditionalCheckInterval == 0 && clients.Any(x => x.Started)) { testLogger.Info("TEST RUNNER", "Grace period before all resources assigned check"); await Task.Delay(config.ConditionalCheckWaitPeriod); testLogger.Info("TEST RUNNER", "Perform all resources assigned check"); Assert.True(resourceMonitor.AllResourcesAssigned()); } } testCounter++; } // clean up for (int i = 0; i < config.ClientCount; i++) { await clients[i].StopAsync(); } }
public SystemPerformanceViewModel() { resourceMonitor = new ResourceMonitor(); StartSystemStatsThread(); }