Exemple #1
0
        public Center(ExpansionFeature expansion_feature)
        {
            _ExpansionFeature = expansion_feature;

            _Hall = new Hall();
            _Updater = new Updater();
        }
Exemple #2
0
		public static void Main(string[] args)
		{
			var view = new ConsoleViewer();
			var input = new ConsoleInput(view);

			var core = _LoadGame("Game.dll");

			var client = new Client<IUser>(view, input);

			client.ModeSelectorEvent += new ModeCreator(core , client.Command ).Select;
			
            

            var updater = new Updater();
			updater.Add(client);
			updater.Add(core);

			while(client.Enable)
			{
				input.Update();
				updater.Working();
			}

			updater.Shutdown();
		}
Exemple #3
0
 static void Main(string[] args)
 {
     Console.WriteLine("SUP Updater");
     Console.WriteLine("Copyright (c) 2014 Samarjeet Singh");
     if (args.Length < 3)
     {
         ShowHelp();
         return;
     }
     uphost = new ConsoleAppUpdate();
     uphost.UpdateFile = args[1];
     uphost.Files = AppFile.GetAppFiles(args[0]);
     uphost.CurrentVersion = Convert.ToDouble(args[2]);
     print("SUP Updater Console");
     print("Copyright (C) 2014 Samarjeet Singh");
     print(string.Empty);
     print("Checking for Updates.....");
     var checker = new Updater(uphost);
     if (checker.IsUpdateAvailable())
     {
         var result = MessageBox.Show("Updates are available ? Would you like to download it ?");
         if (result == DialogResult.OK)
         {
             Update update = checker.GetUpdate();
             update.UpdateDownload += update_UpdateDownload;
             update.DownloadUpdate();
         }
     }
     else
     {
         MessageBox.Show("No Updates Are Available!");
     }
 }
Exemple #4
0
        private static void Main(string[] args)
        {
            var sw = new SpinWait();
            Program._Enable = true;
            var updater = new Updater();
            var launcher = new Launcher();

            var server = new Server();
            var serverAppliction = new Regulus.Remoting.Soul.Native.Server(server, 12345);

            var client = new Proxy();
            Program.client_UserEvent(client.SpawnUser("user"));

            launcher.Push(serverAppliction);
            updater.Add(client);

            launcher.Launch();
            while(Program._Enable)
            {
                updater.Working();
                sw.SpinOnce();
            }

            updater.Shutdown();
            launcher.Shutdown();

            Console.ReadKey();
        }
        public User(IAgent agent)
        {
            this._Agent = agent;

            this._Updater = new Updater();
            this._User = new Remoting.User(this._Agent);
        }
 public static void Main()
 {
     Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);//Application.StartupPath;
     var updater = new Updater("http://www.repziw4.net/content/dediiw4/", "", false);
     updater.StatusChanged += updater_StatusChanged;
     updater.Start(new string[] { "RepZ-IW4" });
 }
        // TODO: Restrict movement across try/catch/finally borders

        public static ICode V(ICode ast) {
            var v = new VisitorSsaCopyPropagation();
            var ast2 = v.Visit(ast);
            var alreadyReplaced = new Dictionary<Expr, Expr>();
            foreach (var a in v.assignments.Values) {
                if (a.mustKeep) {
                    continue;
                }
                if (a.assignment == null) {
                    continue;
                }
                if (a.count == 1) {
                    if (!VisitorFindSpecials.Any(a.assignment, Expr.Special.PossibleSideEffects)) {
                        ast2 = VisitorReplace.V(ast2, a.assignment, null);
                    }
                } else if (a.count == 2 /*|| 
                    (IsSimple(alreadyReplaced.ValueOrDefault(a.assignment.Expr, a.assignment.Expr)) && !a.assignment.Expr.Type.IsNonPrimitiveValueType())*/) {
                    var updater = new Updater(a.assignment.Target);
                    ast2 = updater.Visit(ast2);
                    foreach (var replaced in updater.Replaced) {
                        alreadyReplaced[replaced.Item1] = replaced.Item2;
                    }
                }
            }
            return ast2;
        }
        public Proxy(IUserFactoty<IUser> custom)
        {
            this._UserFactory = custom;
            this._Client = new Client<IUser>(this, new Command());
            this._Updater = new Updater();

            this.Client_ModeSelectorEvent(this._Client.Selector);
        }
        public Proxy()
        {
            this._UserFactory = new RemotingFactory();
            this._Client = new Client<IUser>(this, new Command());
            this._Updater = new Updater();

            this.Client_ModeSelectorEvent(this._Client.Selector);
        }
Exemple #10
0
 protected WindowConsole()
 {
     _AutoPowerRegulator = new AutoPowerRegulator(new PowerRegulator());
     Viewer = new ConsoleViewer();
     _Input = new ConsoleInput(Viewer);
     _Console = new Console(_Input, Viewer);
     _Updater = new Updater();
 }
Exemple #11
0
        public Proxy(IUserFactoty<IUser> custom)
        {
            _UserFactory = custom;
            _Client = new Client<IUser>(this, this);
            _Updater = new Updater();

            Client_ModeSelectorEvent(_Client.Selector);
        }
Exemple #12
0
        public Proxy()
        {
            _UserFactory = new RemotingFactory();
            _Client = new Client<IUser>(this, this);
            _Updater = new Updater();

            Client_ModeSelectorEvent(_Client.Selector);
        }
Exemple #13
0
        public DummyStandalone()
        {
            var frature = new DummyFrature();

            _Storage = new ExpansionFeature(frature, frature, frature);
            _Updater = new Updater();
            _Center = new Center(_Storage);
        }
Exemple #14
0
 public ClientHandler(string ip_address, int port)
 {
     // TODO: Complete member initialization
     _IpAddress = ip_address;
     _Port = port;
     _Bots = new Updater();
     _DummyStandalone = new DummyStandalone();
 }
Exemple #15
0
        public MainWindow(DataManager dataManager, ConfigManager configManager)
        {
            InitializeComponent();
            myUpdater = new Updater(Update_maskedTextBoxCounter_Text);

            this.dataManager = dataManager;
            this.configManager = configManager;
        }
Exemple #16
0
 public User(IAgent agent)
 {
     _Agent = agent;
     _ConnectProvider = new TProvider<IConnect>();
     _OnlineProvider = new TProvider<IOnline>();
     _Machine = new StageMachine();
     _Updater = new Updater();
 }
Exemple #17
0
        public User(IAgent agent)
        {
            _Agent = agent;
            _Updater = new Updater();
            _User = new Regulus.Remoting.User(_Agent);

            _Version = typeof(IVerify).Assembly.GetName()
                                    .Version.ToString();
        }
 public Server()
 {
     this._LogRecorder = new LogFileRecorder("Storage");
     this._DefaultAdministratorName = "itisnotagame";
     this._Ip = "mongodb://127.0.0.1:27017";
     this._Name = "ItIsNotAGame1";
     this._Updater = new Updater();
     this._Database = new NoSQL.Database(this._Ip);
     this._Center = new Game.Storage.Center(this);
 }
        public OpenDNSInterface(Logging Log)
        {
            m_Log = Log;

            m_Updater = new Updater(m_CurrentVersion);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            InitializeComponent();
        }
Exemple #20
0
        public void ReleaseCheck()
        {
            var expected = new Fixture().Create<IReadOnlyList<Release>>();
            var g = new Mock<IGitHubClient>();
            g.Setup(x => x.Repository.Release.GetAll(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.FromResult(expected));
            var u = new Updater(g.Object);
            var result = u.GetLatestRelease();

            Assert.That(result, Is.Not.Null);
        }
Exemple #21
0
 static UpdateHelper()
 {
     try
     {
         u = new Updater(UpdateServer, username, password);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Update Server Url Error. Please check add the valid UpdateServer URL.");
     }
 }
Exemple #22
0
        public Server()
        {
            //_LogRecorder = new LogFileRecorder("Storage");
            _DefaultAdministratorName = "vgameadmini";

            //const string mongodbUrls = "mongodb://127.0.0.1:27017";
            _Name = "VGame";
            _Updater = new Updater();
            _Database = new Database();
            _Center = new Center(this);
        }
 public static void Execute(string serverName, string databaseName, string path = ".", bool useTransactions = false, bool requireRollback = false, string username = null, string password = null)
 {
     var scriptTarget = (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
                            ? new SqlDatabase(serverName, databaseName, username, password)
                            : new SqlDatabase(serverName, databaseName);
     foreach (var releaseDirectoryPath in Directory.GetDirectories(path, "Release *"))
     {
         var scriptSource = new FolderContainingNumberedSqlScripts(releaseDirectoryPath, "*.sql");
         var updater = new Updater<ITextScriptTarget>(scriptSource, scriptTarget, requireRollback, useTransactions);
         updater.ApplyScripts();
     }
 }
Exemple #24
0
        public Complex()
        {
            _LogRecorder = new LogFileRecorder("Play");

            _StorageVerifyData = new Regulus.CustomType.Verify();
            _FormulaVerifyData = new Regulus.CustomType.Verify();
            _Machine = new StageMachine();
            _Updater = new Updater();

            _BuildParams();
            _BuildUser();
        }
Exemple #25
0
 private void RollbackLatest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Output.WriteLine("Uninstalling...");
     var updater = new Updater(new UpdateParams(this.patcherInfo.configuration, this.GetAdminConnectionString(context)), new InteractiveResponseStream(context));
     this.patcherInfo.DisallowMainHandler();
     int resultCode = updater.RollbackLastPatch();
     if(resultCode == 0) {
         context.Response.Output.WriteLine("Uninstalled");
     } else {
         context.Response.Output.WriteLine("Failed to uninstall: error code {0}", resultCode);
     }
 }
Exemple #26
0
 private void Install(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     context.Response.Output.WriteLine("Installing...");
     var updater = new Updater(new UpdateParams(this.patcherInfo.configuration, this.GetAdminConnectionString(context)), new InteractiveResponseStream(context));
     int resultCode = updater.ApplyAll();
     if(resultCode == 0) {
         this.patcherInfo.PatchesInstalled();
         context.Response.Output.WriteLine("Installed");
     } else {
         context.Response.Output.WriteLine("Failed to install: error code {0}", resultCode);
     }
 }
        public void TestCenter()
        {
            var binder = Substitute.For<Remoting.ISoulBinder>();
            var finder = Substitute.For<IAccountFinder>();
            var record = Substitute.For<IGameRecorder>();

            var center = new Center(finder, record);

            Updater updater = new Updater();
            center.Join(binder);
            updater.Add(center);
            updater.Working();
            updater.Shutdown();
        }
        public ThreadCoreHandler(ICore core)
        {
            if(core == null)
            {
                throw new ArgumentNullException(nameof(core));
            }

            _Core = core;

            _RequesterHandlers = new Updater();
            _Spin = new PowerRegulator();
            _AutoPowerRegulator = new AutoPowerRegulator(_Spin);
            _Binders = new Queue<ISoulBinder>();
        }
Exemple #29
0
        public Center(
			IAccountFinder account_finder, 
			IFishStageQueryer fish_stage_queryer, 
			IGameRecorder rq, 
			ITradeNotes trade_account)
        {
            _GameRecorder = rq;
            _AccountFinder = account_finder;
            _FishStageQueryer = fish_stage_queryer;
            _Tradefinder = trade_account;

            _Updater = new Updater();
            _Hall = new Hall();
        }
Exemple #30
0
        private static void Main(string[] args)
        {
            var sw = new SpinWait();

            var botCount = 1;
            if(args.Length > 0)
            {
                botCount = int.Parse(args[0]);
            }

            if(args.Length > 1)
            {
                Program.IPAddress = args[1];
            }

            var clientHandler = new ClientHandler(Program.IPAddress, Program.Port, botCount);
            var view = new ConsoleViewer();
            Singleton<Log>.Instance.Initial(view);
            var input = new ConsoleInput(view);
            var client = new Client(view, input);
            var packetRegulator = new PacketRegulator();
            client.Command.Register(
                "si",
                () =>
                {
                    Console.WriteLine(
                        "Send Interval : {0}\nRequest Package Queue : {1}",
                        HitHandler.Interval,
                        packetRegulator.Sampling);
                });
            client.ModeSelectorEvent += clientHandler.Begin;

            var updater = new Updater();
            updater.Add(client);
            updater.Add(clientHandler);
            updater.Add(packetRegulator);

            while(client.Enable)
            {
                input.Update();
                updater.Working();
                sw.SpinOnce();
            }

            client.Command.Unregister("si");
            updater.Shutdown();
            clientHandler.End();
            Singleton<Log>.Instance.Final();
        }
#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();
            Reflection.Exception += e => Log.Warn("HearthMirror Exception: " + e);
            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)
            {
                ShowRestartRequiredMessageAsync().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
                );
        }
Exemple #32
0
        void configAutoUpdate()
        {
            _updater = Updater.CreateUpdaterInstance(Properties.Settings.Default.AutoUpdateUri, "update_c.xml");

            //开启时做一次检查
            _updater.Context.EnableEmbedDialog = false;
            _updater.Context.AutoKillProcesses = false;

            _updater.Error += (sender, e) =>
            {
                logError("自动更新时发生错误:" + _updater.Context.Exception.Message, _updater.Context.Exception);
            };

            _updater.UpdatesFound += (sender, e) =>
            {
                _autoUpdateTimer.Stop();

                //保存上次运行的服务配置
                SaveLastRunningConfig();

                //刷新一次服务状态
                refreshServicesStatus();

                //给于半分钟时间等待所有服务退出
                int i;
                for (i = 0; i < 10; i++)
                {
                    foreach (var controllableUI in _serviceUIs)
                    {
                        controllableUI.Value.Stop();
                    }

                    System.Threading.Thread.Sleep(3000);

                    //刷新一次服务状态
                    refreshServicesStatus();

                    if (_serviceUIs.All(cui => cui.Value.IsStopped))
                    {
                        break;
                    }
                }

                if (i == 10)//等待超时
                {
                    logError("自动更新错误:等待服务关闭超时,将启用强制更新模式");
                    //尽量保存配置信息
                    SaveConfig();

                    //配置外部更新程序为强制结束进程模式
                    _updater.Context.AutoExitCurrentProcess       = true;
                    _updater.Context.AutoKillProcesses            = true;
                    _updater.Context.AutoEndProcessesWithinAppDir = true;
                    //启动外部更新程序
                    _updater.StartExternalUpdater();
                }
                else//所有服务正常关闭
                {
                    //启动更新进程
                    _updater.StartExternalUpdater();

                    //退出控制台
                    CanClose = true;
                    Synchronizer.Invoke(() => { Window.Close(); });
                }
            };

            if (!_updater.BeginCheckUpdateInProcess())
            {
                logError("开始检测更新时发生错误:" + _updater.Context.Exception.Message, _updater.Context.Exception);
            }

            _autoUpdateTimer          = new Timer(Properties.Settings.Default.AutoUpdateInterval * 1000);
            _autoUpdateTimer.Elapsed += (sender, e) =>
            {
                //自动升级检查
                if (!_updater.BeginCheckUpdateInProcess())
                {
                    logError("开始检测更新时发生错误:" + _updater.Context.Exception.Message, _updater.Context.Exception);
                }
            };

            _autoUpdateTimer.Start();
        }
Exemple #33
0
        void StartupThread()
        {
#if !DEBUG
            try {
#endif
            Server.InitLibrary(Environment.GetCommandLineArgs());
            if (shutdownPending)
            {
                return;
            }

            Server.InitServer();
            if (shutdownPending)
            {
                return;
            }

            BeginInvoke((Action)OnInitSuccess);

            UpdaterResult update = Updater.CheckForUpdates();
            if (shutdownPending)
            {
                return;
            }

            if (update.UpdateAvailable)
            {
                new UpdateWindow(update, false).ShowDialog();
            }

            if (!ConfigKey.ProcessPriority.IsBlank())
            {
                try {
                    Process.GetCurrentProcess().PriorityClass = ConfigKey.ProcessPriority.GetEnum <ProcessPriorityClass>();
                } catch (Exception) {
                    Logger.Log(LogType.Warning,
                               "MainForm.StartServer: Could not set process priority, using defaults.");
                }
            }

            if (shutdownPending)
            {
                return;
            }
            if (Server.StartServer())
            {
                startupComplete = true;
                BeginInvoke((Action)OnStartupSuccess);
            }
            else
            {
                BeginInvoke((Action)OnStartupFailure);
            }
#if !DEBUG
        }

        catch (Exception ex) {
            Logger.LogAndReportCrash("Unhandled exception in ServerGUI.StartUp", "ServerGUI", ex, true);
            Shutdown(ShutdownReason.Crashed, Server.HasArg(ArgKey.ExitOnCrash));
        }
#endif
        }
Exemple #34
0
 public AppSettingBox()
 {
     this.Font = new Font(SystemFonts.MenuFont.FontFamily, 10F);
     mliConfigDir.AddCtrs(new Control[] { cmbConfigDir, btnConfigDir });
     mliBackup.AddCtrs(new Control[] { chkBackup, btnBackupDir });
     mliUpdate.AddCtrs(new Control[] { lblGitee, lblGithub, lblUpdate });
     mliProtect.AddCtr(chkProtect);
     mliEngine.AddCtr(cmbEngine);
     mliWinXSortable.AddCtr(chkWinXSortable);
     mliShowFilePath.AddCtr(chkShowFilePath);
     mliOpenMoreRegedit.AddCtr(chkOpenMoreRegedit);
     mliHideDisabledItems.AddCtr(chkHideDisabledItems);
     cmbConfigDir.AutosizeDropDownWidth();
     cmbEngine.AutosizeDropDownWidth();
     MyToolTip.SetToolTip(cmbConfigDir, AppString.Tip.ConfigPath);
     MyToolTip.SetToolTip(btnConfigDir, AppString.Other.OpenConfigDir);
     MyToolTip.SetToolTip(btnBackupDir, AppString.Other.OpenBackupDir);
     MyToolTip.SetToolTip(mliUpdate, AppString.Tip.CheckUpdate + Environment.NewLine
                          + AppString.Tip.LastCheckUpdateTime + AppConfig.LastCheckUpdateTime.ToLongDateString());
     cmbConfigDir.Items.AddRange(new[] { AppString.Other.AppDataDir, AppString.Other.AppDir });
     cmbEngine.Items.AddRange(new[] { "Baidu", "Bing", "Google", "DogeDoge", "Sogou", "360", AppString.Other.CustomEngine });
     btnConfigDir.MouseDown += (sender, e) => ExternalProgram.JumpExplorer(AppConfig.ConfigDir);
     btnBackupDir.MouseDown += (sender, e) => ExternalProgram.JumpExplorer(AppConfig.BackupDir);
     lblGithub.Click        += (sender, e) => ExternalProgram.OpenUrl(GithubUrl);
     lblGitee.Click         += (sender, e) => ExternalProgram.OpenUrl(GiteeUrl);
     lblUpdate.Click        += (sender, e) =>
     {
         if (!Updater.CheckUpdate())
         {
             MessageBoxEx.Show(AppString.MessageBox.NoUpdateDetected);
         }
     };
     cmbConfigDir.SelectionChangeCommitted += (sender, e) =>
     {
         string newPath = (cmbConfigDir.SelectedIndex == 0) ? AppConfig.AppDataConfigDir : AppConfig.AppConfigDir;
         if (newPath == AppConfig.ConfigDir)
         {
             return;
         }
         if (MessageBoxEx.Show(AppString.MessageBox.RestartApp, MessageBoxButtons.OKCancel) != DialogResult.OK)
         {
             cmbConfigDir.SelectedIndex = AppConfig.SaveToAppDir ? 1 : 0;
         }
         else
         {
             DirectoryEx.CopyTo(AppConfig.ConfigDir, newPath);
             Directory.Delete(AppConfig.ConfigDir, true);
             SingleInstance.Restart(true);
         }
     };
     cmbEngine.SelectionChangeCommitted += (sender, e) =>
     {
         if (cmbEngine.SelectedIndex < cmbEngine.Items.Count - 1)
         {
             AppConfig.EngineUrl = AppConfig.EngineUrls[cmbEngine.SelectedIndex];
         }
         else
         {
             using (InputDialog dlg = new InputDialog {
                 Title = AppString.Other.SetCustomEngine
             })
             {
                 dlg.Text = AppConfig.EngineUrl;
                 if (dlg.ShowDialog() == DialogResult.OK)
                 {
                     AppConfig.EngineUrl = dlg.Text;
                 }
                 string url = AppConfig.EngineUrl;
                 for (int i = 0; i < AppConfig.EngineUrls.Length; i++)
                 {
                     if (url.Equals(AppConfig.EngineUrls[i]))
                     {
                         cmbEngine.SelectedIndex = i; break;
                     }
                 }
             }
         }
     };
     chkBackup.MouseDown            += (sender, e) => AppConfig.AutoBackup = chkBackup.Checked = !chkBackup.Checked;
     chkProtect.MouseDown           += (sender, e) => AppConfig.ProtectOpenItem = chkProtect.Checked = !chkProtect.Checked;
     chkWinXSortable.MouseDown      += (sender, e) => AppConfig.WinXSortable = chkWinXSortable.Checked = !chkWinXSortable.Checked;
     chkOpenMoreRegedit.MouseDown   += (sender, e) => AppConfig.OpenMoreRegedit = chkOpenMoreRegedit.Checked = !chkOpenMoreRegedit.Checked;
     chkHideDisabledItems.MouseDown += (sender, e) => AppConfig.HideDisabledItems = chkHideDisabledItems.Checked = !chkHideDisabledItems.Checked;
     chkShowFilePath.MouseDown      += (sender, e) =>
     {
         chkShowFilePath.Checked = !chkShowFilePath.Checked;
         if (MessageBoxEx.Show(AppString.MessageBox.RestartApp, MessageBoxButtons.OKCancel) == DialogResult.OK)
         {
             AppConfig.ShowFilePath = chkShowFilePath.Checked;
             SingleInstance.Restart(true);
         }
         else
         {
             chkShowFilePath.Checked = !chkShowFilePath.Checked;
         }
     };
 }
Exemple #35
0
        static void Main(string[] args)
        {
            DEBUG = false;

            Console.Title = "Akarr's steambot";

            Console.ForegroundColor = ConsoleColor.White;

            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

            AppDomain currentDomain = default(AppDomain);

            currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;

            Console.Title = "Akarr's steambot";

            config = new Config();
            if (!config.LoadConfig())
            {
                Console.WriteLine("Config file (config.cfg) can't be found or is corrupted ! Bot can't start.");
                Console.ReadKey();
                return;
            }

            PrintWelcomeMessage();

            Updater updater = new Updater(config.DisableAutoUpdate, BUILD_VERSION);

            Task.WaitAll(updater.Update());

            if (config.DisplayLocation)
            {
                SendLocation();
            }

            steambotManager = new Manager(config);
            threadManager   = new Thread(new ThreadStart(steambotManager.Start));
            threadManager.CurrentUICulture = new CultureInfo("en-US");
            threadManager.Start();

            AttemptLoginBot(config.SteamUsername, config.SteamPassword, config.SteamAPIKey);

            while (steambotManager.OnlineBots.Count < 1)
            {
                Thread.Sleep(TimeSpan.FromSeconds(3));
            }

            steambotManager.SelectFirstBot();

            /*if (!IsLinux())
             * {
             *  string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
             *  if (File.Exists("website.zip"))
             *  {
             *      Console.WriteLine("Website not extracted ! Doing that now...");
             *      //ZipFile.ExtractToDirectory("website.zip", path);
             *
             *      File.Delete("website.zip");
             *      Console.WriteLine("Done !");
             *  }
             *
             *  if (Directory.Exists(path + "/website"))
             *  {
             *      //Webinteface are shit anyway... Worst idea ever!
             *      //httpsrv = new HTTPServer("/website", 85);
             *      //Console.WriteLine("HTTP Server started on port : " + httpsrv.Port + ">>> http://localhost:" + httpsrv.Port + "/index.html");
             *  }
             *  else
             *  {
             *      Console.ForegroundColor = ConsoleColor.Red;
             *      Console.WriteLine("Website folder not present, can't start web interface. Re-download ASteambot from original github.");
             *      Console.ForegroundColor = ConsoleColor.White;
             *  }
             * }
             * else
             * {
             *  Console.ForegroundColor = ConsoleColor.Red;
             *  Console.WriteLine("HTTP Server disabled for UNIX users. Wait for a fix :) !");
             *  Console.ForegroundColor = ConsoleColor.White;
             * }*/

            Console.WriteLine("I gave up for now on the webinterface. Worst idea ever.");

            string command = "";

            while (command != "quit")
            {
                Console.Write("> ");
                command = Console.ReadLine();
                steambotManager.Command(command);
            }

            if (httpsrv != null)
            {
                httpsrv.Stop();
            }
        }
Exemple #36
0
 public VehicleInsurementSeeder(Updater updater) : base(updater)
 {
 }
Exemple #37
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            TreeView tree  = (TreeView)schemaTreeView1.Controls.Find("treeView1", true)[0];
            TreeNode dbArm = tree.Nodes[0];
            var      sb    = new StringBuilder();

            foreach (TreeNode node in dbArm.Nodes)
            {
                if (node.Nodes.Count != 0)
                {
                    foreach (TreeNode subnode in node.Nodes)
                    {
                        if (subnode.Checked)
                        {
                            //ISchemaBase selected = (ISchemaBase)tree.SelectedNode.Tag;
                            ISchemaBase selected = (ISchemaBase)subnode.Tag;

                            IDatabase database = (IDatabase)schemaTreeView1.LeftDatabase;

                            if (database.Find(selected.FullName) != null)
                            {
                                switch (selected.ObjectType)
                                {
                                case ObjectType.Table:
                                {
                                    switch (selected.Status)
                                    {
                                    case ObjectStatus.Create: sb.Append(Updater.createNew(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.AlterWhitespace: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    default: sb.AppendLine($"Nothing could be found to do for table '{selected.Name}'"); break;
                                    }
                                }
                                break;

                                case ObjectType.StoredProcedure:
                                {
                                    switch (selected.Status)
                                    {
                                    case ObjectStatus.Create: sb.Append(Updater.createNew(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.AlterWhitespace: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    default: sb.AppendLine($"Nothing could be found to do for stored procedure '{selected.Name}'"); break;
                                    }
                                }
                                break;

                                case ObjectType.Function:
                                {
                                    switch (selected.Status)
                                    {
                                    case ObjectStatus.Create: sb.Append(Updater.createNew(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.AlterWhitespace: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter | ObjectStatus.AlterBody: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    default: sb.AppendLine($"Nothing could be found to do for function '{selected.Name}'"); break;
                                    }
                                }
                                break;

                                case ObjectType.View:
                                {
                                    switch (selected.Status)
                                    {
                                    case ObjectStatus.Create: sb.Append(Updater.createNew(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.AlterWhitespace: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    case ObjectStatus.Alter | ObjectStatus.AlterBody: sb.Append(Updater.alter(selected, RightDatabaseSelector.ConnectionString)); break;

                                    default: sb.AppendLine($"Nothing could be found to do for view '{selected.Name}'"); break;
                                    }
                                }
                                break;

                                default:
                                {
                                    switch (selected.Status)
                                    {
                                    case ObjectStatus.Create: sb.Append(Updater.addNew(selected, RightDatabaseSelector.ConnectionString)); break;

                                    default: sb.AppendLine($"Nothing could be found to do for '{selected.Name}'"); break;
                                    }
                                }
                                break;
                                }
                            }
                        }
                    }
                }
            }

            if (sb.Length == 0)
            {
                MessageBox.Show(this, "All successful.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(this, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (Options.Comparison.ReloadComparisonOnUpdate)
            {
                StartComparison();
            }

            btnUpdate.Enabled = false;
        }
Exemple #38
0
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            Browser.Visibility             = Visibility.Hidden;
            TosBrowser.Visibility          = Visibility.Hidden;
            DataContext                    = this;
            GeneralSettingsItem.IsSelected = true;

            #region ContextMenu.DevMenu

            DevMenu.Visibility      = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
            Config.PropertyChanged += (o, args) =>
            {
                if (args.PropertyName == "ShowDevOptions")
                {
                    DevMenu.Visibility = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
                }
            };

            #endregion

            #region ToS

            if (!Config.Instance.TosAccepted)
            {
                RightWindowCommands.Visibility = Visibility.Collapsed;
            }
            else
            {
                MainTabControl.SelectedIndex = 1;
            }

            #endregion

            if (!File.Exists(Directories.CoreFilePath))
            {
                MessageBox.Show(string.Format("Couldn't find {0}", Path.GetFileName(Directories.CoreFilePath)));
                Environment.Exit(0);
            }

            Updater.MainWindow = this;
            CheckForUpdates(true, true, false);

            Updater.GetRepositories(
                delegate(List <string> list)
            {
                if (list.Count > 0)
                {
                    Config.Instance.KnownRepositories.Clear();
                    foreach (var repo in list)
                    {
                        Config.Instance.KnownRepositories.Add(repo);
                    }
                }
            });

            //Try to login with the saved credentials.
            if (!Auth.Login(Config.Instance.Username, Config.Instance.Password).Item1)
            {
                ShowLoginDialog();
            }
            else
            {
                OnLogin(Config.Instance.Username);
            }

            Config.Instance.FirstRun = false;


            foreach (var gameSetting in Config.Instance.Settings.GameSettings)
            {
                gameSetting.PropertyChanged += GameSettingOnPropertyChanged;
            }
            NewsTabItem.Visibility       = Visibility.Hidden;
            AssembliesTabItem.Visibility = Visibility.Hidden;
            SettingsTabItem.Visibility   = Visibility.Hidden;
        }
Exemple #39
0
        /// <summary>
        ///     Will compare the last status with the current one and return event updates.
        /// </summary>
        /// <returns></returns>
        public EventBase[] Update()
        {
            // event-queue
            var events  = new List <EventBase>();
            var isFirst = last == null;
            var current = Updater.GetLatestServerInfo();

            if (current != null)
            {
                // if first info, or last success was different from this (either went online or went offline) => invoke
                if (NotifyServer && (isFirst || last.HadSuccess != current.HadSuccess))
                {
                    Debug.WriteLine("Server '" + Updater.Address + ":" + Updater.Port + "' status change: " + current.HadSuccess);
                    var errMsg = current.LastError != null ? "Connection Failed: " + current.LastError.GetType().Name : "";
                    events.Add(new OnlineStatusEvent(messages, current.HadSuccess, current.HadSuccess ? current.ServerMotd : errMsg));
                }

                // if first info, or last player count was different (player went online or offline) => invoke
                if (NotifyCount)
                {
                    var diff = isFirst
                        ? current.CurrentPlayerCount
                        : current.CurrentPlayerCount - last.CurrentPlayerCount;
                    if (diff != 0)
                    {
                        Debug.WriteLine("Server '" + Updater.Address + ":" + Updater.Port + "' count change: " + diff);
                        events.Add(new PlayerChangeEvent(messages, diff));
                    }
                }

                // check current list for new players
                var onlineIds = new List <string>();
                if (current.OnlinePlayers != null)
                {
                    foreach (var p in current.OnlinePlayers)
                    {
                        // save online user id temporarily
                        if (!onlineIds.Contains(p.Id))
                        {
                            onlineIds.Add(p.Id);
                        }
                        // register name
                        userNames[p.Id] = p.Name;
                        // if notify and user has state and last state was offline and user is watched, notify change
                        if (NotifyNames && (!userStates.ContainsKey(p.Id) || !userStates[p.Id]))
                        {
                            events.Add(new PlayerStateEvent(messages, p, true));
                        }
                        // register state or set to true
                        userStates[p.Id] = true;
                    }
                }

                // this needs to be done to avoid ElementChangedException
                var keys = userStates.Keys.ToArray();
                // check all states for players who went offline
                foreach (var k in keys)
                {
                    if (!userStates[k] || onlineIds.Contains(k))
                    {
                        continue;
                    }
                    // if user state still true, but he is not in online list => went offline
                    userStates[k] = false;
                    // create payload
                    var p = new PlayerPayLoad {
                        Id = k, RawName = userNames[k]
                    };
                    // notify => invoke
                    if (NotifyNames)
                    {
                        events.Add(new PlayerStateEvent(messages, p, false));
                    }
                }
            }
            // set new last
            last = current;
            ApplyServerInfo(current);
            return(events.ToArray());
        }
Exemple #40
0
    /// <summary>
    /// Returns Instance asynchronously
    /// </summary>
    /// <returns></returns>
    public static async Task <(Updater, bool)> CreateAsync()
    {
        var updater = new Updater();

        return(updater, await updater.CheckVersion());
    }
Exemple #41
0
        private void CheckForUpdates(bool loader, bool core, bool showDialogOnFinish)
        {
            if (CheckingForUpdates)
            {
                return;
            }
            StatusString       = Utility.GetMultiLanguageText("Checking");
            _updateMessage     = "";
            CheckingForUpdates = true;
            UpdaterWorker      = new BackgroundWorker();

            UpdaterWorker.DoWork += delegate
            {
                if (loader)
                {
                    _loaderVersionCheckResult = Updater.CheckLoaderVersion();
                }

                if (core)
                {
                    if (Config.Instance.LeagueOfLegendsExePath != null)
                    {
                        var exe = Utility.GetLatestLeagueOfLegendsExePath(Config.Instance.LeagueOfLegendsExePath);
                        if (exe != null)
                        {
                            var updateResult = Updater.UpdateCore(exe, !showDialogOnFinish);
                            _updateMessage = updateResult.Item3;
                            switch (updateResult.Item2)
                            {
                            case true:
                                StatusString = Utility.GetMultiLanguageText("Updated");
                                break;

                            case false:
                                StatusString = Utility.GetMultiLanguageText("OUTDATED");
                                break;

                            default:
                                StatusString = Utility.GetMultiLanguageText("Unknown");
                                break;
                            }

                            return;
                        }
                    }
                    StatusString   = Utility.GetMultiLanguageText("Unknown");
                    _updateMessage = Utility.GetMultiLanguageText("LeagueNotFound");
                }
            };

            UpdaterWorker.RunWorkerCompleted += delegate
            {
                try
                {
                    if (File.Exists(Updater.SetupFile))
                    {
                        Thread.Sleep(1000);
                        File.Delete(Updater.SetupFile);
                    }
                }
                catch
                {
                    MessageBox.Show(Utility.GetMultiLanguageText("FailedToDelete"));
                    Environment.Exit(0);
                }

                if (_loaderVersionCheckResult != null && _loaderVersionCheckResult.Item1)
                {
                    //Update the loader only when we are not injected to be able to replace the core files.
                    if (!Injection.IsInjected)
                    {
                        Updater.Updating = true;
                        Updater.UpdateLoader(_loaderVersionCheckResult);
                    }
                }

                Updater.CheckedForUpdates = true;
                CheckingForUpdates        = false;
                if (showDialogOnFinish)
                {
                    ShowTextMessage(Utility.GetMultiLanguageText("UpdateStatus"), _updateMessage);
                }
            };

            UpdaterWorker.RunWorkerAsync();
        }
        private static async void UpdateOverlayAsync()
        {
            if (Config.Instance.CheckForUpdates)
            {
                Updater.CheckForUpdates(true);
            }
            var hsForegroundChanged = false;
            var useNoDeckMenuItem   = TrayIcon.NotifyIcon.ContextMenu.MenuItems.IndexOfKey("startHearthstone");

            UpdateOverlay = Helper.HearthstoneDirExists;
            while (UpdateOverlay)
            {
                if (User32.GetHearthstoneWindow() != IntPtr.Zero)
                {
                    if (Game.CurrentRegion == Region.UNKNOWN)
                    {
                        //game started
                        Game.CurrentRegion = Helper.GetCurrentRegion();
                    }
                    Overlay.UpdatePosition();

                    if (Config.Instance.CheckForUpdates)
                    {
                        Updater.CheckForUpdates();
                    }

                    if (!Game.IsRunning)
                    {
                        Overlay.Update(true);
                    }

                    MainWindow.BtnStartHearthstone.Visibility = Visibility.Collapsed;
                    TrayIcon.NotifyIcon.ContextMenu.MenuItems[useNoDeckMenuItem].Visible = false;

                    Game.IsRunning = true;
                    if (User32.IsHearthstoneInForeground())
                    {
                        if (hsForegroundChanged)
                        {
                            Overlay.Update(true);
                            if (Config.Instance.WindowsTopmostIfHsForeground && Config.Instance.WindowsTopmost)
                            {
                                //if player topmost is set to true before opponent:
                                //clicking on the playerwindow and back to hs causes the playerwindow to be behind hs.
                                //other way around it works for both windows... what?
                                Windows.OpponentWindow.Topmost = true;
                                Windows.PlayerWindow.Topmost   = true;
                                Windows.TimerWindow.Topmost    = true;
                            }
                            hsForegroundChanged = false;
                        }
                    }
                    else if (!hsForegroundChanged)
                    {
                        if (Config.Instance.WindowsTopmostIfHsForeground && Config.Instance.WindowsTopmost)
                        {
                            Windows.PlayerWindow.Topmost   = false;
                            Windows.OpponentWindow.Topmost = false;
                            Windows.TimerWindow.Topmost    = false;
                        }
                        hsForegroundChanged = true;
                    }
                }
                else
                {
                    Overlay.ShowOverlay(false);
                    if (Game.IsRunning)
                    {
                        //game was closed
                        Logger.WriteLine("Exited game", "UpdateOverlayLoop");
                        Game.CurrentRegion = Region.UNKNOWN;
                        Logger.WriteLine("Reset region", "UpdateOverlayLoop");
                        //HsLogReaderV2.Instance.ClearLog();
                        Game.Reset();
                        if (DeckList.Instance.ActiveDeck != null)
                        {
                            Game.SetPremadeDeck((Deck)DeckList.Instance.ActiveDeck.Clone());
                        }
                        await LogReaderManager.Restart();

                        MainWindow.BtnStartHearthstone.Visibility = Visibility.Visible;
                        TrayIcon.NotifyIcon.ContextMenu.MenuItems[useNoDeckMenuItem].Visible = true;

                        if (Config.Instance.CloseWithHearthstone)
                        {
                            MainWindow.Close();
                        }
                    }
                    Game.IsRunning = false;
                }

                if (Config.Instance.NetDeckClipboardCheck.HasValue && Config.Instance.NetDeckClipboardCheck.Value &&
                    Initialized &&
                    !User32.IsHearthstoneInForeground())
                {
                    NetDeck.CheckForClipboardImport();
                }

                await Task.Delay(Config.Instance.UpdateDelay);
            }
            CanShutdown = true;
        }
Exemple #43
0
        ///////////////////////////////////////////////////////////
        public UBSApp(DateTime fechaInicio) : base("root")
        {
            //Buscar actualizacion
            UBSCarga.Progress = Convert.ToInt32(100);
            UBSCarga.Status   = "Buscando actualizaciones";

            Updater.InstallUpdate();
            Updater.FindUpdate();


            // Init Global config manager
            GlobalConfigManager.Init();


            //Cargar el modo debug
            try
            {
                if (File.Exists("Debug.txt"))
                {
                    GlobalConfigManager.SetParameter("Debug", Convert.ToBoolean(File.ReadAllText("Debug.txt")));
                }
                else
                {
                    GlobalConfigManager.SetParameter("Debug", false);
                }
            }
            catch (Exception e)
            {
                Error("Error al abrir el archivo del modo depuración. Revisa el fichero Debug.txt, debe de contener únicamente el valor \"true\" o \"false\". " + e.Message, true);
                GlobalConfigManager.SetParameter("Debug", false);
            }

            //[Debug] Cargar el escritor de tiempos de ejecución.
            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                UBSExecutionTimeLogger.Instance.Init(fechaInicio, "", "ExecutionTime.log", true);
                WriteExecutionTime("Iniciacion del programa ", fechaInicio);
            }
            #endregion

            // Get UBS version
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string UBSversion = fvi.FileVersion;

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Version del UBS cargada");
            }
            #endregion

            // Init logger
            UBSLogger.Instance.Init("UBS " + UBSversion, "UBS.log", Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")));

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Logger inicializado");
            }
            #endregion

            // Load config
            AppConfig       app_config;
            AppConfigLoader loader = new AppConfigLoader(config_filename);
            if (!loader.Load(out app_config))
            {
                Error("Error en la carga del fichero de configuración. [" + config_filename + "]", true);
            }

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Configuracion del UBS cargada");
            }
            #endregion

            //Save dummy Config

            /*app_config = new AppConfig();
             * app_config.isMinimized = false;
             * app_config.AppName = "UBS Dummy";
             * app_config.AppSize = new System.Drawing.Size(600, 800);
             * System.Collections.Generic.Dictionary<string, ModuleInfo> aux = new System.Collections.Generic.Dictionary<string, ModuleInfo>();
             * ModuleInfoLocal mi = new ModuleInfoLocal();
             * mi.Id = "LocMod";
             * mi.Name = "LocalModule";
             * mi.Filename = "LocMod.dll";
             * mi.ModuleType = "modules.UBSPageModule";
             * aux.Add(mi.Id, mi);
             * mi.Id += 1;
             * aux.Add(mi.Id + 1, mi);
             * ModuleInfoRemote miRemoto = new ModuleInfoRemote();
             * miRemoto.Id = "RemMod";
             * miRemoto.Name = "RemoteModule";
             * miRemoto.Filename = "RemMod.dll";
             * miRemoto.ModuleType = "modules.UBSPageModule";
             * miRemoto.Ip = "192.168.10.10";
             * aux.Add(miRemoto.Id, miRemoto);
             * miRemoto.Id += 2;
             * aux.Add(miRemoto.Id + 2, miRemoto);
             * app_config.Modules = aux;
             * loader.Save(app_config);*/

            // Load modules
            module_manager = new UBSModuleManager(app_config);
            if (!module_manager.LoadModules())
            {
                Error("Algunos módulos no se han podido cargar correctamente", true);
            }

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Módulos cargados");
            }
            #endregion

            // Load communications
            // each handle message in a thread
            communication_manager = new CommunicationManager(app_config);
            communication_manager.EnableLocalModules(module_manager.GetLocalModules());

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Comunicaciones cargadas");
            }
            #endregion

            // Load Container Form
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            form_container      = new UBSFormContainer();
            form_container.Text = "UBS " + UBSversion + " :: " + app_config.AppName;

            //Set the Form Size
            if (app_config.AppSize.Height == 0 && app_config.AppSize.Height == 0)// Full screen
            {
                //Si el modo debug está activo que la pantalla no sea completa del todo
                if (!Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
                {
                    form_container.FormBorderStyle = FormBorderStyle.None;
                    form_container.WindowState     = FormWindowState.Maximized;
                }
                else
                {
                    form_container.Scale(new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
                }
            }
            else
            {
                form_container.Scale(new System.Drawing.Size(app_config.AppSize.Width, app_config.AppSize.Height));
            }

            if (app_config.isMinimized)
            {
                form_container.WindowState = FormWindowState.Minimized;
            }

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Formularios cargados");
            }
            #endregion

            // Append ConsoleWrite delegate
            UBSStatusFunctions.Instance.SetConsoleLoggerDelegate(form_container.WriteConsole);
            UBSStatusFunctions.Instance.SetModuleErrorDelegate(form_container.ModuleError);
            UBSStatusFunctions.Instance.SetModuleConnectionDelegate(form_container.ModuleConnection);

            // Append delegates
            module_functions = new UBSAppComponentFunctions();
            UBSModuleDelegates module_delegates = new UBSModuleDelegates
                                                  (
                communication_manager.SendMessage,
                module_manager.GetAvailableModuleNames,
                module_manager.GetLocalModules,
                module_functions.Log,
                module_functions.WriteConsole,
                module_functions.Notify,
                module_functions.Error,
                module_functions.WriteExecutionTime,
                GlobalConfigManager.SetParameter,
                GlobalConfigManager.GetParameter,
                form_container.GoToModule,
                form_container.ButtonColor
                                                  );

            module_manager.AppendDelegates(module_delegates);

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Delegados asociados");
            }
            #endregion

            // Initialization of global parameters
            GlobalConfigManager.SetParameter("Communication", "message");

            #region ExecutionTime
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("Parametros globales cargados");
            }
            if (Convert.ToBoolean(GlobalConfigManager.GetParameter("Debug")))
            {
                WriteExecutionTime("UBS Constructor OK");
            }
            #endregion
        }
Exemple #44
0
        public virtual void TestAccquireReleaseRace()
        {
            DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();

            ctrl.UpdateStalled(false);
            AtomicBoolean stop       = new AtomicBoolean(false);
            AtomicBoolean checkPoint = new AtomicBoolean(true);

            int          numStallers  = AtLeast(1);
            int          numReleasers = AtLeast(1);
            int          numWaiters   = AtLeast(1);
            Synchronizer sync         = new Synchronizer(numStallers + numReleasers, numStallers + numReleasers + numWaiters);

            ThreadClass[]     threads    = new ThreadClass[numReleasers + numStallers + numWaiters];
            IList <Exception> exceptions = new ConcurrentList <Exception>(new List <Exception>());

            for (int i = 0; i < numReleasers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, true, exceptions);
            }
            for (int i = numReleasers; i < numReleasers + numStallers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, false, exceptions);
            }
            for (int i = numReleasers + numStallers; i < numReleasers + numStallers + numWaiters; i++)
            {
                threads[i] = new Waiter(stop, checkPoint, ctrl, sync, exceptions);
            }

            Start(threads);
            int   iters = AtLeast(10000);
            float checkPointProbability = TEST_NIGHTLY ? 0.5f : 0.1f;

            for (int i = 0; i < iters; i++)
            {
                if (checkPoint.Get())
                {
                    Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)), "timed out waiting for update threads - deadlock?");
                    if (exceptions.Count > 0)
                    {
                        foreach (Exception throwable in exceptions)
                        {
                            Console.WriteLine(throwable.ToString());
                            Console.Write(throwable.StackTrace);
                        }
                        Assert.Fail("got exceptions in threads");
                    }

                    if (ctrl.HasBlocked() && ctrl.Healthy)
                    {
                        AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
                    }

                    checkPoint.Set(false);
                    sync.Waiter.countDown();
                    sync.LeftCheckpoint.@await();
                }
                Assert.IsFalse(checkPoint.Get());
                Assert.AreEqual(0, sync.Waiter.Remaining);
                if (checkPointProbability >= (float)Random().NextDouble())
                {
                    sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                    checkPoint.Set(true);
                }
            }
            if (!checkPoint.Get())
            {
                sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                checkPoint.Set(true);
            }

            Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)));
            AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
            checkPoint.Set(false);
            stop.Set(true);
            sync.Waiter.countDown();
            sync.LeftCheckpoint.@await();

            for (int i = 0; i < threads.Length; i++)
            {
                ctrl.UpdateStalled(false);
                threads[i].Join(2000);
                if (threads[i].IsAlive && threads[i] is Waiter)
                {
                    if (threads[i].State == ThreadState.WaitSleepJoin)
                    {
                        Assert.Fail("waiter is not released - anyThreadsStalled: " + ctrl.AnyStalledThreads());
                    }
                }
            }
        }
 private void UpdateButton_Click(object sender, RoutedEventArgs e)
 {
     Updater.ManualCheckVersion();
 }
Exemple #46
0
        public static void Main(string[] args)
        {
            ParseArguments(args);

            if (IsHelp)
            {
                Help();
            }
            else
            {
                Console.WriteLine("");
                Console.WriteLine("Setting up csAnt...");
                Console.WriteLine("");


                Console.WriteLine("PackageName:" + PackageName);
                Console.WriteLine("");
                Console.WriteLine("Version:" + (Version == new Version(0, 0, 0, 0) ? "[Latest]" : Version.ToString()));
                Console.WriteLine("");
                Console.WriteLine("Destination path:");
                Console.WriteLine("  " + DestinationPath);
                Console.WriteLine("");

                var nugetRetriever = new InstallerNugetPackageRetriever(
                    NugetSourcePath,
                    DestinationPath
                    );

                if (!String.IsNullOrEmpty(NugetPath))
                {
                    nugetRetriever.NugetPath = NugetPath;
                }

                var unpacker = new InstallUnpacker();

                if (Update)
                {
                    var updater = new Updater(
                        nugetRetriever,
                        unpacker
                        );

                    updater.PackageName = PackageName;
                    updater.Version     = Version;
                    updater.Status      = Status;

                    updater.Clear       = Clear;
                    updater.Import      = Import;
                    updater.ImportPath  = ImportPath;
                    updater.Clone       = Clone;
                    updater.CloneSource = CloneSource;

                    updater.Update();
                }
                else
                {
                    var installer = new Installer(
                        nugetRetriever,
                        unpacker
                        );

                    installer.PackageName = PackageName;
                    installer.Version     = Version;
                    installer.Status      = Status;

                    installer.Clear       = Clear;
                    installer.Import      = Import;
                    installer.ImportPath  = ImportPath;
                    installer.Clone       = Clone;
                    installer.CloneSource = CloneSource;

                    installer.Install();
                }

                if (ShowIntro)
                {
                    OutputIntro();
                }
            }
        }
    private void OnStateChange(KMGameInfo.State state)
    {
        CurrentState = state;

        if (!transform.gameObject.activeInHierarchy)
        {
            return;
        }

        Votes.OnStateChange();
        CheckSupport.Cleanup();

        if (state != KMGameInfo.State.PostGame && _leaderboardDisplay != null)
        {
            DestroyObject(_leaderboardDisplay);
            _leaderboardDisplay = null;
        }

        twitchGame?.gameObject.SetActive(state == KMGameInfo.State.Gameplay);

        OtherModes.RefreshModes(state);

        // Automatically check for updates after a round is finished or when entering the setup state but never more than once per hour.
        bool hourPassed = DateTime.Now.Subtract(Updater.LastCheck).TotalHours >= 1;

        if ((state == KMGameInfo.State.PostGame || state == KMGameInfo.State.Setup) && hourPassed && !Updater.UpdateAvailable)
        {
            _coroutinesToStart.Enqueue(Updater.CheckForUpdates().Yield(() =>
            {
                if (Updater.UpdateAvailable)
                {
                    IRCConnection.SendMessage("There is a new update to Twitch Plays!");
                }
            }));
        }

        switch (state)
        {
        case KMGameInfo.State.Gameplay:
            DefaultCamera();
            LeaderboardController.DisableLeaderboards();
            break;

        case KMGameInfo.State.Setup:
            DefaultCamera();
            _coroutinesToStart.Enqueue(VanillaRuleModifier.Refresh());
            _coroutinesToStart.Enqueue(MultipleBombs.Refresh());
            _coroutinesToStart.Enqueue(FactoryRoomAPI.Refresh());

            if (!initialLoad)
            {
                initialLoad = true;
                _coroutinesToStart.Enqueue(ComponentSolverFactory.LoadDefaultInformation(true));
                _coroutinesToStart.Enqueue(Repository.LoadData());
                if (TwitchPlaySettings.data.TestModuleCompatibility && !TwitchPlaySettings.data.TwitchPlaysDebugEnabled)
                {
                    _coroutinesToStart.Enqueue(CheckSupport.FindSupportedModules());
                }
            }

            // Clear out the retry reward if we return to the setup room since the retry button doesn't return to setup.
            // A post game run command would set the retry bonus and then return to the setup room to start the mission, so we don't want to clear that.
            if (TwitchPlaySettings.GetRewardBonus() == 0)
            {
                TwitchPlaySettings.ClearRetryReward();
            }
            break;

        case KMGameInfo.State.PostGame:
            DefaultCamera();
            if (_leaderboardDisplay == null)
            {
                _leaderboardDisplay = Instantiate(TwitchLeaderboardPrefab);
            }
            Leaderboard.Instance.SaveDataToFile();
            break;

        case KMGameInfo.State.Transitioning:
            ModuleData.LoadDataFromFile();
            TwitchPlaySettings.LoadDataFromFile();

            var pageManager = SceneManager.Instance?.SetupState?.Room.GetComponent <SetupRoom>().BombBinder.MissionTableOfContentsPageManager;
            if (pageManager != null)
            {
                var tableOfContentsList = pageManager.GetValue <List <Assets.Scripts.BombBinder.MissionTableOfContents> >("tableOfContentsList");
                if (tableOfContentsList[SetupState.LastBombBinderTOCIndex].ToCID == "toc_tp_search")
                {
                    SetupState.LastBombBinderTOCIndex = 0;
                    SetupState.LastBombBinderTOCPage  = 0;
                }
            }

            break;
        }

        StopEveryCoroutine();
    }
Exemple #48
0
        public static void StartBot()
        {
            Console.Write(@"DiscordBot: [");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write(@"Version " + ProgramVersion.Major + @"." + ProgramVersion.Minor + @"." + ProgramVersion.Build + @"." + ProgramVersion.Revision);
            Console.ResetColor();
            Console.WriteLine(@"]    ");

            Console.Write(@"Developed by Melissa Brennan (");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write(@"@MythicalCuddles");
            Console.ResetColor();
            Console.WriteLine(@")");

            Console.WriteLine(@"Web: www.mythicalcuddles.xyz");

            Console.WriteLine(@"Copyright 2017 - 2019 Melissa Brennan | Licensed under the MIT License.");
            Console.WriteLine(@"-----------------------------------------------------------------");

            MelissaNet.MelissaNet.Initialize();

            /*    Update Checker via MythicalCore    */
            try
            {
                var updateCheck = Updater.CheckForUpdate("DiscordBot", ProgramVersion);
                if (updateCheck.Item1)
                {
                    Console.WriteLine(@"-----------------------------------------------------------------");
                    LogMessage lm = new LogMessage(LogSeverity.Info, "MythicalCore",
                                                   "A new update has been found. Would you like to download?");
                    lm.PrintToConsole();
                    Console.WriteLine(@"-----------------------------------------------------------------");

                    DialogResult result = MessageBox.Show("A new update is available. Would you like to update?",
                                                          "DiscordBot Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                    if (result == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(updateCheck.Item2);
                        Environment.Exit(0);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(@"-----------------------------------------------------------------");
                LogMessage lm = new LogMessage(LogSeverity.Error, "MythicalCore",
                                               "Unable to check for new updates.");
                lm.PrintToConsole();
                Console.WriteLine(@"-----------------------------------------------------------------");
            }
            /*    Update End    */

            Configuration.EnsureExists();
            StringConfiguration.EnsureExists();
            QuoteHandler.EnsureExists();
            VoteLinkHandler.EnsureExists();

            try
            {
                DatabaseActivity.CheckForDatabase();
            }
            catch (Exception e)
            {
                LogMessage lm = new LogMessage(LogSeverity.Critical, "MySQL Database", "Unable to connect to database. Is it currently running?", e);
                lm.PrintToConsole();
                Environment.Exit(0);
            }


            Console.WriteLine(@"-----------------------------------------------------------------");

            new DiscordBot().RunBotAsync().GetAwaiter().GetResult();
        }
Exemple #49
0
        internal static void Boot()
        {
            Logger.Log(LogLevel.Info, "core", "Booting Everest");
            Logger.Log(LogLevel.Info, "core", $"VersionCelesteString: {VersionCelesteString}");

            if (Type.GetType("Mono.Runtime") != null)
            {
                // Mono hates HTTPS.
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
                    return(true);
                };
            }

            PathGame = Path.GetDirectoryName(typeof(Celeste).Assembly.Location);

            // .NET hates it when strong-named dependencies get updated.
            AppDomain.CurrentDomain.AssemblyResolve += (asmSender, asmArgs) => {
                AssemblyName asmName = new AssemblyName(asmArgs.Name);
                if (!asmName.Name.StartsWith("Mono.Cecil") && !asmName.Name.StartsWith("YamlDotNet"))
                {
                    return(null);
                }

                Assembly asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(other => other.GetName().Name == asmName.Name);
                if (asm != null)
                {
                    return(asm);
                }

                return(Assembly.LoadFrom(Path.Combine(PathGame, asmName.Name + ".dll")));
            };

            if (!File.Exists(Path.Combine(PathGame, "EverestXDGFlag")))
            {
                XDGPaths    = false;
                PathEverest = PathGame;
            }
            else
            {
                XDGPaths = true;
                var dataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                Directory.CreateDirectory(PathEverest = Path.Combine(dataDir, "Everest"));
                Directory.CreateDirectory(Path.Combine(dataDir, "Everest", "Mods")); // Make sure it exists before content gets initialized
            }
            PathSettings = Path.Combine(PathEverest, "ModSettings");
            Directory.CreateDirectory(PathSettings);

            // Before even initializing anything else, make sure to prepare any static flags.
            Flags.Initialize();

            if (!Flags.IsDisabled && !Flags.IsDisabled)
            {
                // 0.1 parses into 1 in regions using ,
                // This also somehow sets the exception message language to English.
                CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
                CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
            }

            if (!Flags.IsHeadless)
            {
                // Initialize the content helper.
                Content.Initialize();

                // Initialize all main managers before loading any mods.
                TouchInputManager.Instance = new TouchInputManager(Celeste.Instance);
                // Don't add it yet, though - add it in Initialize.
            }

            // Register our core module and load any other modules.
            new CoreModule().Register();

            // Note: Everest fulfills some mod dependencies by itself.
            new NullModule(new EverestModuleMetadata()
            {
                Name          = "Celeste",
                VersionString = $"{Celeste.Instance.Version.ToString()}-{(typeof(Game).Assembly.FullName.Contains("FNA") ? "fna" : "xna")}"
            }).Register();
            new NullModule(new EverestModuleMetadata()
            {
                Name          = "DialogCutscene",
                VersionString = "1.0.0"
            }).Register();

            Loader.LoadAuto();

            if (!Flags.IsHeadless && !Flags.IsDisabled)
            {
                // Load stray .bins afterwards.
                Content.Crawl(new MapBinsInModsModContent(Path.Combine(PathEverest, "Mods")));
            }

            // Also let all mods parse the arguments.
            Queue <string> args = new Queue <string>(Args);

            while (args.Count > 0)
            {
                string arg = args.Dequeue();
                foreach (EverestModule mod in _Modules)
                {
                    if (mod.ParseArg(arg, args))
                    {
                        break;
                    }
                }
            }

            // Start requesting the version list ASAP.
            Updater.RequestAll();
        }
 private void ButCheckUpdates_OnClick(object sender, RoutedEventArgs e)
 {
     Updater.Check(true);
     UpdateButtonCheckLogic();
 }
Exemple #51
0
 private void HyperlinkUpdateNow_OnClick(object sender, RoutedEventArgs e) => Updater.StartUpdate();
Exemple #52
0
 void updateButton_Click(object sender, EventArgs e) =>
 Updater.Run();
Exemple #53
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            TreeView tree   = (TreeView)schemaTreeView1.Controls.Find("treeView1", true)[0];
            TreeNode dbArm  = tree.Nodes[0];
            string   result = "";

            foreach (TreeNode node in dbArm.Nodes)
            {
                if (node.Nodes.Count != 0)
                {
                    foreach (TreeNode subnode in node.Nodes)
                    {
                        if (subnode.Checked)
                        {
                            //ISchemaBase selected = (ISchemaBase)tree.SelectedNode.Tag;
                            ISchemaBase selected = (ISchemaBase)subnode.Tag;

                            Database database = (Database)schemaTreeView1.DatabaseSource;

                            if (database.Find(selected.FullName) != null)
                            {
                                switch (selected.ObjectType)
                                {
                                case Enums.ObjectType.Table:
                                {
                                    switch (selected.Status)
                                    {
                                    case Enums.ObjectStatusType.CreateStatus: result += Updater.createNew(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterWhitespaceStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    default: result += "Nothing could be found to do for table " + selected.Name + ".\r\n"; break;
                                    }
                                }
                                break;

                                case Enums.ObjectType.StoreProcedure:
                                {
                                    switch (selected.Status)
                                    {
                                    case Enums.ObjectStatusType.CreateStatus: result += Updater.createNew(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterWhitespaceStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    default: result += "Nothing could be found to do for stored procedure " + selected.Name + ".\r\n"; break;
                                    }
                                }
                                break;

                                case Enums.ObjectType.Function:
                                {
                                    switch (selected.Status)
                                    {
                                    case Enums.ObjectStatusType.CreateStatus: result += Updater.createNew(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterWhitespaceStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus | Enums.ObjectStatusType.AlterBodyStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    default: result += "Nothing could be found to do for function " + selected.Name + ".\r\n"; break;
                                    }
                                }
                                break;

                                case Enums.ObjectType.View:
                                {
                                    switch (selected.Status)
                                    {
                                    case Enums.ObjectStatusType.CreateStatus: result += Updater.createNew(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterWhitespaceStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    case Enums.ObjectStatusType.AlterStatus | Enums.ObjectStatusType.AlterBodyStatus: result += Updater.alter(selected, mySqlConnectFront2.ConnectionString); break;

                                    default: result += "Nothing could be found to do for view " + selected.Name + ".\r\n"; break;
                                    }
                                }
                                break;

                                default:
                                {
                                    switch (selected.Status)
                                    {
                                    case Enums.ObjectStatusType.CreateStatus: result += Updater.addNew(selected, mySqlConnectFront2.ConnectionString); break;

                                    default: result += "Nothing could be found to do for " + selected.Name + ".\r\n"; break;
                                    }
                                }
                                break;
                                }
                            }
                        }
                    }
                }
            }

            if (result == string.Empty)
            {
                result = "All successful";
            }
            MessageBox.Show(result);

            if (SqlFilter.Comparison.ReloadComparisonOnUpdate)
            {
                if (optSQL2005.Checked)
                {
                    ProcesarSQL2005();
                }
            }

            btnUpdate.Enabled = false;
        }
Exemple #54
0
 private async void menuHelpUpdater_Click(object sender, RoutedEventArgs e)
 {
     await Updater.BeginUpdateProcess();
 }
Exemple #55
0
 private void metroButton2_Click(object sender, EventArgs e)
 {
     DialogResult = DialogResult.Cancel;
     Updater.CheckForUpdates();
     Close();
 }
Exemple #56
0
 public SchemaSeeder(Updater updater) : base(updater)
 {
 }
        private static async void UpdateOverlayAsync()
        {
#if (!SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                Updater.CheckForUpdates(true);
            }
#endif
            var hsForegroundChanged = false;
            while (UpdateOverlay)
            {
                if (Config.Instance.CheckForUpdates)
                {
                    Updater.CheckForUpdates();
                }
                if (User32.GetHearthstoneWindow() != IntPtr.Zero)
                {
                    if (Game.CurrentRegion == Region.UNKNOWN)
                    {
                        //game started
                        Helper.VerifyHearthstonePath();
                        Game.CurrentRegion = await Helper.GetCurrentRegion();

                        if (Game.CurrentRegion != Region.UNKNOWN)
                        {
                            BackupManager.Run();
                            Game.MetaData.HearthstoneBuild = null;
                        }
                    }
                    Overlay.UpdatePosition();

                    if (!Game.IsRunning)
                    {
                        Overlay.Update(true);
                        Windows.CapturableOverlay?.UpdateContentVisibility();
                    }

                    TrayIcon.MenuItemStartHearthstone.Visible = false;

                    Game.IsRunning = true;
                    GameIsRunningChanged?.Invoke(true);

                    Helper.GameWindowState = User32.GetHearthstoneWindowState();
                    Windows.CapturableOverlay?.Update();
                    if (User32.IsHearthstoneInForeground() && Helper.GameWindowState != WindowState.Minimized)
                    {
                        if (hsForegroundChanged)
                        {
                            Overlay.Update(true);
                            if (Config.Instance.WindowsTopmostIfHsForeground && Config.Instance.WindowsTopmost)
                            {
                                //if player topmost is set to true before opponent:
                                //clicking on the playerwindow and back to hs causes the playerwindow to be behind hs.
                                //other way around it works for both windows... what?
                                Windows.OpponentWindow.Topmost = true;
                                Windows.PlayerWindow.Topmost   = true;
                                Windows.TimerWindow.Topmost    = true;
                            }
                            hsForegroundChanged = false;
                        }
                    }
                    else if (!hsForegroundChanged)
                    {
                        if (Config.Instance.WindowsTopmostIfHsForeground && Config.Instance.WindowsTopmost)
                        {
                            Windows.PlayerWindow.Topmost   = false;
                            Windows.OpponentWindow.Topmost = false;
                            Windows.TimerWindow.Topmost    = false;
                        }
                        hsForegroundChanged = true;
                    }
                }
                else if (Game.IsRunning)
                {
                    Game.IsRunning = false;
                    GameIsRunningChanged?.Invoke(false);
                    Overlay.ShowOverlay(false);
                    Watchers.Stop();
                    if (Windows.CapturableOverlay != null)
                    {
                        Windows.CapturableOverlay.UpdateContentVisibility();
                        await Task.Delay(100);

                        Windows.CapturableOverlay.ForcedWindowState = WindowState.Minimized;
                        Windows.CapturableOverlay.WindowState       = WindowState.Minimized;
                    }
                    Log.Info("Exited game");
                    Game.CurrentRegion = Region.UNKNOWN;
                    Log.Info("Reset region");
                    await Reset();

                    Game.IsInMenu = true;
                    Game.InvalidateMatchInfoCache();
                    Overlay.HideRestartRequiredWarning();
                    Helper.ClearCachedHearthstoneBuild();
                    TurnTimer.Instance.Stop();

                    TrayIcon.MenuItemStartHearthstone.Visible = true;

                    if (Config.Instance.CloseWithHearthstone)
                    {
                        MainWindow.Close();
                    }
                }

                await Task.Delay(UpdateDelay);
            }
            CanShutdown = true;
        }
        /**
         * Gets the latest update patch number (i.e. the latest PATCHSCRIPTRUNNER patch) which this version of ScriptRunner
         * is expecting to have been run. This will be checked against the target database. This number should reflect the
         * latest update patch in the update package.
         * @return Patch number of the latest ScriptRunner install patch which this version is expecting.
         */
        public static int getLatestExpectedUpdatePatchNumber()
        {
            List <PatchScript> lList = Updater.getUpdatePatches();

            return(lList[lList.Count - 1].getPatchNumber());
        }
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            ConfigManager.Run();
            Logger.Initialzie();
            Helper.UpdateAppTheme();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
            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 (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            if (Helper.HearthstoneDirExists)
            {
                if (Helper.UpdateLogConfig && Game.IsRunning)
                {
                    MainWindow.ShowMessageAsync("Restart Hearthstone",
                                                "This is either your first time starting HDT or the log.config file has been updated. Please restart Hearthstone, for HDT to work properly.");
                }
                LogReaderManager.Start(Game);
            }
            else
            {
                MainWindow.ShowHsNotInstalledMessage();
            }

            Helper.CopyReplayFiles();
            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();
            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();
            Initialized = true;

            Analytics.Analytics.TrackPageView(
                string.Format("/app/v{0}/{1}{2}", Helper.GetCurrentVersion().ToVersionString(),
                              loginType.ToString().ToLower(), newUser ? "/new" : ""), "");
        }
Exemple #60
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!GlobalHandlers.SessionHandler.isLoggedIn())
            {
                Response.Redirect("~/admin/login/default.aspx", false);
                return;
            }
            if (IsPostBack)
            {
                if (Request.Form["editfield"] != null)
                {
                    string text = Request.Form["editfield"].ToString();

                    if (text.StartsWith("updateNow"))
                    {
                        string returning = text.Replace("updateNow(", "");
                        returning = returning.Replace(")", "");
                        updateNow(returning);
                    }
                    else if (text.StartsWith("deleteNow"))
                    {
                        string returning = text.Replace("deleteNow(", "");
                        returning = returning.Replace(")", "");
                        deleteNow(returning);
                    }
                    else if (text == "shutoff")
                    {
                        //requesting emergency shutoff
                        emergencyShutoff();
                    }
                }
            }
            SchoolName.Text            = GlobalHandlers.DatabaseHandler.globalInformation.School_Name;
            DistrictName.Text          = GlobalHandlers.DatabaseHandler.globalInformation.District_Name;
            schoolID.Text              = GlobalHandlers.DatabaseHandler.globalInformation.School_ID;
            DistrictID.Text            = GlobalHandlers.DatabaseHandler.globalInformation.District_ID;
            ColorLabel.Text            = GlobalHandlers.DatabaseHandler.globalInformation.Color;
            ColorLabel.ForeColor       = System.Drawing.ColorTranslator.FromHtml(GlobalHandlers.DatabaseHandler.globalInformation.Color);
            version.Text               = ConstantManager.Total_Version.ToString();
            SecondColorLabel.ForeColor = System.Drawing.ColorTranslator.FromHtml(GlobalHandlers.DatabaseHandler.globalInformation.SecondColor);
            SecondColorLabel.Text      = GlobalHandlers.DatabaseHandler.globalInformation.SecondColor;
            string markup = @"<tr><td>?type</td><td>?how</td><td>?when</td><td>?lastUpdate</td></tr>";

            Updater updater = GlobalHandlers.DatabaseHandler.getUpdater(config.handlers.instances.ViewerHandler.Feature.ANNOUNCEMENTS);

            if (updater == null)
            {
                panelUpdaters.Controls.Add(new LiteralControl("<tr><td>No announcement updater found</td></tr>"));
            }
            else
            {
                string toAdd = markup.Replace("?id", updater.ID);
                toAdd = toAdd.Replace("?type", getTypeById(updater.Feature_Id));
                toAdd = toAdd.Replace("?how", getTypeIdName(updater.Type_Id, config.handlers.instances.ViewerHandler.Feature.ANNOUNCEMENTS));
                toAdd = toAdd.Replace("?when", getFormattedWhen(updater.Type));
                toAdd = toAdd.Replace("?lastUpdate", Updates.NextTimeUpdate_Announcements.ToString("U").Replace("Z", ""));
                panelUpdaters.Controls.Add(new LiteralControl(toAdd));
            }

            Updater eventUpdater = GlobalHandlers.DatabaseHandler.getUpdater(config.handlers.instances.ViewerHandler.Feature.EVENTS);

            if (eventUpdater == null)
            {
                panelUpdaters.Controls.Add(new LiteralControl("<tr><td>No event updater found</td></tr>"));
            }
            else
            {
                string toAdde = markup.Replace("?id", eventUpdater.ID);
                toAdde = toAdde.Replace("?type", getTypeById(eventUpdater.Feature_Id));
                toAdde = toAdde.Replace("?when", getFormattedWhen(eventUpdater.Type));
                toAdde = toAdde.Replace("?how", getTypeIdName(updater.Type_Id, config.handlers.instances.ViewerHandler.Feature.EVENTS));
                toAdde = toAdde.Replace("?lastUpdate", Updates.NextTimeUpdate_Events.ToString("U").Replace("Z", ""));
                panelUpdaters.Controls.Add(new LiteralControl(toAdde));
            }
            form.Style.Clear();
        }