コード例 #1
0
ファイル: MainForm.cs プロジェクト: Inzaghi2012/teamlab.v7.5
        private void buttonRestore_Click(object sender, EventArgs e)
        {
            var backuper = new BackupManager(textBoxBackup.Text, textBoxCoreConfig.Text, textBoxWebConfig.Text);
            backuper.AddBackupProvider(new Restarter());
            backuper.ProgressChanged += backuper_ProgressChanged;

            try
            {
                progress = true;
                labelStatus.Text = string.Empty;
                buttonRestore.Enabled = buttonCancel.Enabled = false;

                backuper.Load();

                labelStatus.Text = "Complete";
            }
            catch (Exception error)
            {
                labelStatus.Text = "Error: " + error.Message.Replace("\r\n", " ");
            }
            finally
            {
                progress = false;
                progressBar.Value = 0;
                buttonRestore.Enabled = buttonCancel.Enabled = true;
            }
        }
コード例 #2
0
        protected override void RunInternal()
        {
            var config = BackupConfigurationSection.GetSection();
            var pathToWebConfig = FileUtility.GetRootedPath(config.WebConfigs.GetCurrentConfig());
            
            if (!pathToWebConfig.EndsWith(".config", StringComparison.InvariantCultureIgnoreCase))
                pathToWebConfig = Path.Combine(pathToWebConfig, "web.config");

            var tenant = CoreContext.TenantManager.GetTenant(TenantId);
            tenant.SetStatus(TenantStatus.Restoring);
            CoreContext.TenantManager.SaveTenant(tenant);

            var backupManager = new BackupManager(pathToBackupFile, pathToWebConfig);
            backupManager.ProgressChanged += (sender, args) => { Progress = (int)args.Progress; };
            backupManager.Load();
        }
コード例 #3
0
        protected override void RunInternal()
        {
            var config = BackupConfigurationSection.GetSection();
            var pathToWebConfig = FileUtility.GetRootedPath(config.WebConfigs.GetCurrentConfig());
            var tempFolderPath = FileUtility.GetRootedPath(config.TempFolder);

            if (!pathToWebConfig.EndsWith(".config", StringComparison.InvariantCultureIgnoreCase))
                pathToWebConfig = Path.Combine(pathToWebConfig, "web.config");

            if (!Directory.Exists(tempFolderPath))
                Directory.CreateDirectory(tempFolderPath);
            
            var backupFile = CreateBackupFilePath(tempFolderPath);
            try
            {
                var backuper = new BackupManager(backupFile, pathToWebConfig);
                backuper.ProgressChanged += (sender, args) =>
                    {
                        if (args.Progress > 0)
                        {
                            Progress = Math.Max(0, Math.Min((int)args.Progress/2, 50));
                        }
                    };

                backuper.Save(TenantId);

                using (var stream = new FileStream(backupFile, FileMode.Open))
                using (var progressStream = new ProgressStream(stream))
                {
                    progressStream.OnReadProgress += (sender, args) =>
                    {
                        Progress = Math.Max(0, Math.Min(100, 50 + args / 2));
                    };

                    ExpirationDate = DateTime.UtcNow + config.ExpirePeriod;

                    var storage = StorageFactory.GetStorage(pathToWebConfig, "backupfiles", "backup");
                    Link = storage.SavePrivate(string.Empty, Path.GetFileName(backupFile), progressStream, ExpirationDate);
                }

                NotifyHelper.SendAboutBackupCompleted(TenantId, notificationReceiverId, Link, ExpirationDate);
            }
            finally
            {
                File.Delete(backupFile);
            }
        }
コード例 #4
0
        public static void Load()
        {
            var foundConfig = false;

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                var config = Path.Combine(AppDataPath, "config.xml");
#if (SQUIRREL)
                if (File.Exists(config))
                {
                    _config = XmlManager <Config> .Load(config);

                    foundConfig = true;
                }
#else
                if (File.Exists("config.xml"))
                {
                    _config = XmlManager <Config> .Load("config.xml");

                    foundConfig = true;
                }
                else if (File.Exists(config))
                {
                    _config = XmlManager <Config> .Load(config);

                    foundConfig = true;
                }
                else if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
                {
                    //save locally if appdata doesn't exist (when e.g. not on C)
                    Instance.SaveConfigInAppData = false;
                }
#endif
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                try
                {
                    if (File.Exists("config.xml"))
                    {
                        File.Move("config.xml", Helper.GetValidFilePath(".", "config_corrupted", "xml"));
                    }
                    else if (File.Exists(AppDataPath + @"\config.xml"))
                    {
                        File.Move(AppDataPath + @"\config.xml", Helper.GetValidFilePath(AppDataPath, "config_corrupted", "xml"));
                    }
                }
                catch (Exception ex1)
                {
                    Log.Error(ex1);
                }
                _config = BackupManager.TryRestore <Config>("config.xml");
            }

            if (!foundConfig)
            {
                if (Instance.ConfigDir != string.Empty)
                {
                    Directory.CreateDirectory(Instance.ConfigDir);
                }
                Save();
            }
#if (!SQUIRREL)
            else if (Instance.SaveConfigInAppData != null)
            {
                if (Instance.SaveConfigInAppData.Value)                //check if config needs to be moved
                {
                    if (File.Exists("config.xml"))
                    {
                        Directory.CreateDirectory(Instance.ConfigDir);
                        SaveBackup(true);                         //backup in case the file already exists
                        File.Move("config.xml", Instance.ConfigPath);
                        Log.Info("Moved config to appdata");
                    }
                }
                else if (File.Exists(AppDataPath + @"\config.xml"))
                {
                    SaveBackup(true);                     //backup in case the file already exists
                    File.Move(AppDataPath + @"\config.xml", Instance.ConfigPath);
                    Log.Info("Moved config to local");
                }
            }
#endif
            if (Instance.Id == Guid.Empty.ToString())
            {
                Instance.Id = Guid.NewGuid().ToString();
                Save();
            }
        }
コード例 #5
0
        private static async void UpdateOverlayAsync()
        {
#if (!SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                Updater.CheckForUpdates(true);
            }
#endif
            var hsForegroundChanged = false;
            var useNoDeckMenuItem   = TrayIcon.NotifyIcon.ContextMenu.MenuItems.IndexOfKey("startHearthstone");
            while (UpdateOverlay)
            {
                if (User32.GetHearthstoneWindow() != IntPtr.Zero)
                {
                    if (Game.CurrentRegion == Region.UNKNOWN)
                    {
                        //game started
                        Game.CurrentRegion = Helper.GetCurrentRegion();
                        if (Game.CurrentRegion != Region.UNKNOWN)
                        {
                            BackupManager.Run();
                            Game.MetaData.HearthstoneBuild = null;
                        }
                    }
                    Overlay.UpdatePosition();

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

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

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

                    Game.IsRunning = 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;
                    Overlay.ShowOverlay(false);
                    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();
                    TurnTimer.Instance.Stop();

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

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

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

                await Task.Delay(UpdateDelay);
            }
            CanShutdown = true;
        }
コード例 #6
0
        private static void Install(PatchContext context)
        {
            try
            {
                bool installFiles = true;

                var fileVersion = GetInstalledVersion(context);

                if (fileVersion != null && fileVersion > Version)
                {
                    installFiles = false;
                }

                if (installFiles || ArgForce)
                {
                    var backup = new BackupUnit(context);

                    if (!ArgNoRevert)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Restoring old version... ");
                        if (BackupManager.HasBackup(context))
                        {
                            BackupManager.Restore(context);
                        }
                    }

                    var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                    bool isFlat             = Directory.Exists(nativePluginFolder) &&
                                              Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                    bool force        = !BackupManager.HasBackup(context) || ArgForce;
                    var  architecture = DetectArchitecture(context.Executable);

                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Installing files... ");

                    CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
                            backup);
                    CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
                            backup);
                    CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
                            backup,
                            null, false);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Not copying files because newer version already installed");
                }

                #region Create Plugin Folder

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                    Console.ResetColor();
                }

                #endregion
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Fail("Oops! This should not have happened.\n\n" + e);
            }
            Console.ResetColor();
        }
コード例 #7
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            ConfigManager.Run();
            Logger.Initialize();
            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();
            if (Config.Instance.ReselectLastDeckUsed)
            {
                MainWindow.SelectLastUsedDeck();
                Config.Instance.ReselectLastDeckUsed = false;
                Config.Save();
            }
            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().Forget();
            }

            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($"/app/v{Helper.GetCurrentVersion().ToVersionString()}/{loginType.ToString().ToLower()}{(newUser ? "/new" : "")}", "");
        }
コード例 #8
0
 public BackupController()
 {
     _backupManager = new BackupManager();
 }
コード例 #9
0
 public BackupController(ILogger <BackupController> logger, BackupManager backupManager)
 {
     _logger        = logger;
     _backupManager = backupManager;
 }
コード例 #10
0
        private static void Install(PatchContext context)
        {
            try
            {
                bool installFiles = true;
                // first, check currently installed version, if any
                if (File.Exists(Path.Combine(context.ProjectRoot, "winhttp.dll")))
                { // installed, so check version of installed assembly
                    string injectorPath = Path.Combine(context.ManagedPath, "IPA.Injector.dll");
                    if (File.Exists(injectorPath))
                    {
                        var verInfo     = FileVersionInfo.GetVersionInfo(injectorPath);
                        var fileVersion = new Version(verInfo.FileVersion);

                        if (fileVersion > Version)
                        {
                            installFiles = false;
                        }
                    }
                }

                if (installFiles || ArgForce)
                {
                    var backup = new BackupUnit(context);

                    if (!ArgNoRevert)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Restoring old version... ");
                        if (BackupManager.HasBackup(context))
                        {
                            BackupManager.Restore(context);
                        }
                    }

                    var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                    bool isFlat             = Directory.Exists(nativePluginFolder) &&
                                              Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                    bool force        = !BackupManager.HasBackup(context) || ArgForce;
                    var  architecture = DetectArchitecture(context.Executable);

                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Installing files... ");

                    CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
                            backup,
                            null, false);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Not copying files because newer version already installed");
                }

                #region Create Plugin Folder

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                    Console.ResetColor();
                }

                #endregion
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Fail("Oops! This should not have happened.\n\n" + e);
            }
            Console.ResetColor();
        }
コード例 #11
0
 private void CargarGvBackups()
 {
     gvBackups.DataSource = BackupManager.ObtenerBackups();
     gvBackups.DataBind();
 }
コード例 #12
0
        private static void InstallBootstrapPatch()
        {
            var cAsmName = Assembly.GetExecutingAssembly().GetName();

            loader.Debug("Finding backup");
            var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", "Beat Saber");
            var bkp        = BackupManager.FindLatestBackup(backupPath);

            if (bkp == null)
            {
                loader.Warn("No backup found! Was BSIPA installed using the installer?");
            }

            loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
            #region Insert patch into UnityEngine.CoreModule.dll
            var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed", "UnityEngine.CoreModule.dll");

            var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath);
            var unityModDef = unityAsmDef.MainModule;

            bool modified = false;
            foreach (var asmref in unityModDef.AssemblyReferences)
            {
                if (asmref.Name == cAsmName.Name)
                {
                    if (asmref.Version != cAsmName.Version)
                    {
                        asmref.Version = cAsmName.Version;
                        modified       = true;
                    }
                }
            }

            var application = unityModDef.GetType("UnityEngine", "Application");

            MethodDefinition cctor = null;
            foreach (var m in application.Methods)
            {
                if (m.IsRuntimeSpecialName && m.Name == ".cctor")
                {
                    cctor = m;
                }
            }

            var cbs = unityModDef.Import(((Action)CreateBootstrapper).Method);

            if (cctor == null)
            {
                cctor = new MethodDefinition(".cctor", MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName, unityModDef.TypeSystem.Void);
                application.Methods.Add(cctor);
                modified = true;

                var ilp = cctor.Body.GetILProcessor();
                ilp.Emit(OpCodes.Call, cbs);
                ilp.Emit(OpCodes.Ret);
            }
            else
            {
                var ilp = cctor.Body.GetILProcessor();
                for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
                {
                    var ins = cctor.Body.Instructions[i];
                    switch (i)
                    {
                    case 0 when ins.OpCode != OpCodes.Call:
                        ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                        modified = true;
                        break;

                    case 0:
                    {
                        var methodRef = ins.Operand as MethodReference;
                        if (methodRef?.FullName != cbs.FullName)
                        {
                            ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                            modified = true;
                        }

                        break;
                    }

                    case 1 when ins.OpCode != OpCodes.Ret:
                        ilp.Replace(ins, ilp.Create(OpCodes.Ret));
                        modified = true;
                        break;
                    }
                }
            }

            if (modified)
            {
                bkp?.Add(unityPath);
                unityAsmDef.Write(unityPath);
            }
            #endregion

            loader.Debug("Ensuring Assembly-CSharp is virtualized");
            #region Virtualize Assembly-CSharp.dll
            var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed", "Assembly-CSharp.dll");

            var ascModule = VirtualizedModule.Load(ascPath);
            ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
            #endregion
        }
コード例 #13
0
        private static void Install(PatchContext context)
        {
            try
            {
                var backup = new BackupUnit(context);

                // Copying
                Console.WriteLine("Updating files... ");
                var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                bool isFlat             = Directory.Exists(nativePluginFolder) && Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                bool force        = !BackupManager.HasBackup(context) || context.Args.Contains("-f") || context.Args.Contains("--force");
                var  architecture = DetectArchitecture(context.Executable);

                Console.WriteLine("Architecture: {0}", architecture);

                CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force, backup,
                        (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat, architecture));

                Console.WriteLine("Successfully updated files!");

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                }

                if (!Directory.Exists(context.LogsFolder))
                {
                    Console.WriteLine("Creating logs folder... ");
                    Directory.CreateDirectory(context.LogsFolder);
                }

                // Patching
                var patchedModule = PatchedModule.Load(context.EngineFile);
                if (!patchedModule.IsPatched)
                {
                    Console.Write("Patching UnityEngine.dll... ");
                    backup.Add(context.EngineFile);
                    patchedModule.Patch();
                    Console.WriteLine("Done!");
                }

                // Virtualizing
                if (File.Exists(context.AssemblyFile))
                {
                    var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
                    if (!virtualizedModule.IsVirtualized)
                    {
                        Console.Write("Virtualizing Assembly-Csharp.dll... ");
                        backup.Add(context.AssemblyFile);
                        virtualizedModule.Virtualize();
                        Console.WriteLine("Done!");
                    }
                }
            }
            catch (Exception e)
            {
                Fail("Oops! This should not have happened.\n\n" + e);
            }


            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Finished!");
            Console.ResetColor();
        }
コード例 #14
0
        private static void Install(PatchContext context)
        {
            try
            {
                var backup = new BackupUnit(context);

                if (ArgDestructive)
                {
                    #region Patch Version Check

                    var patchedModule = PatchedModule.Load(context.EngineFile);
#if DEBUG
                    var isCurrentNewer = Version.CompareTo(patchedModule.Data.Version) >= 0;
#else
                    var isCurrentNewer = Version.CompareTo(patchedModule.Data.Version) > 0;
#endif
                    Console.WriteLine($"Current: {Version} Patched: {patchedModule.Data.Version}");
                    if (isCurrentNewer)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(
                            $"Preparing for update, {(patchedModule.Data.Version == null ? "UnPatched" : patchedModule.Data.Version.ToString())} => {Version}");
                        Console.WriteLine("--- Starting ---");
                        Revert(context);
                        Console.ResetColor();

                        #region File Copying

                        Console.ForegroundColor = ConsoleColor.Magenta;
                        Console.WriteLine("Updating files... ");
                        var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                        bool isFlat             = Directory.Exists(nativePluginFolder) &&
                                                  Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                        bool force        = !BackupManager.HasBackup(context) || ArgForce;
                        var  architecture = DetectArchitecture(context.Executable);

                        Console.WriteLine("Architecture: {0}", architecture);

                        CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
                                backup,
                                (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                      architecture));
                        CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
                                backup,
                                (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                      architecture));

                        Console.WriteLine("Successfully updated files!");

                        #endregion
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Files up to date @ Version {Version}!");
                        Console.ResetColor();
                    }

                    #endregion

                    #region Patching

                    if (!patchedModule.Data.IsPatched || isCurrentNewer)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine($"Patching UnityEngine.dll with Version {Application.ProductVersion}... ");
                        backup.Add(context.EngineFile);
                        patchedModule.Patch(Version);
                        Console.WriteLine("Done!");
                        Console.ResetColor();
                    }

                    #endregion

                    #region Creating shortcut
                    if (!File.Exists(context.ShortcutPath))
                    {
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.WriteLine("Creating shortcut to IPA ({0})... ", context.IPA);
                        try
                        {
                            Shortcut.Create(
                                fileName: context.ShortcutPath,
                                targetPath: context.IPA,
                                arguments: Args(context.Executable, "-ln"),
                                workingDirectory: context.ProjectRoot,
                                description: "Launches the game and makes sure it's in a patched state",
                                hotkey: "",
                                iconPath: context.Executable
                                );
                        }
                        catch (Exception)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.Error.WriteLine("Failed to create shortcut, but game was patched!");
                        }
                        Console.ResetColor();
                    }
                    #endregion
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Restoring old version... ");
                    if (BackupManager.HasBackup(context))
                    {
                        BackupManager.Restore(context);
                    }

                    var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                    bool isFlat             = Directory.Exists(nativePluginFolder) &&
                                              Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                    bool force        = !BackupManager.HasBackup(context) || ArgForce;
                    var  architecture = DetectArchitecture(context.Executable);

                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Installing files... ");

                    CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
                            backup,
                            null, false);

                    //backup.Add(context.AssemblyFile);
                    //backup.Add(context.EngineFile);
                }

                #region Create Plugin Folder

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                    Console.ResetColor();
                }

                #endregion

                #region Virtualizing

                if (ArgDestructive && File.Exists(context.AssemblyFile))
                {
                    var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
                    if (!virtualizedModule.IsVirtualized)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Virtualizing Assembly-Csharp.dll... ");
                        backup.Add(context.AssemblyFile);
                        virtualizedModule.Virtualize();
                        Console.WriteLine("Done!");
                        Console.ResetColor();
                    }
                }

                #endregion
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Fail("Oops! This should not have happened.\n\n" + e);
            }
            Console.ResetColor();
        }
コード例 #15
0
        private void buttonNext_Click(object sender, EventArgs e)
        {
            switch (displayPage)
            {
            case -1:
                buttonBack.Visible = false;
                contentPanel.Controls.Clear();
                contentPanel.Controls.Add(introPage);
                displayPage = 0;
                break;

            case 0:
                // move to find installation
                buttonBack.Visible = true;
                buttonSkip.Visible = false;
                contentPanel.Controls.Clear();
                contentPanel.Controls.Add(findInstallPage);
                displayPage = 1;
                break;

            case 1:
                manager = new SettingsManager(SnakeBiteSettings);
                if (!manager.ValidInstallPath)
                {
                    MessageBox.Show("Please select a valid installation directory.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!BackupManager.GameFilesExist())
                {
                    MessageBox.Show("Some game data appears to be missing. If you have just revalidated the game data, please wait for Steam to finish downloading the new files before continuing.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                // show create backup page, without processing panel, enable skip
                createBackupPage.panelProcessing.Visible = false;
                contentPanel.Controls.Clear();
                contentPanel.Controls.Add(createBackupPage);
                buttonSkip.Visible = true;

                displayPage = 2;
                break;

            case 2:
                manager = new SettingsManager(SnakeBiteSettings);
                if (!(manager.IsVanilla0001Size() || manager.IsVanilla0001DatHash()) && (SettingsManager.IntendedGameVersion >= ModManager.GetMGSVersion()))     // not the right 00/01 and there hasn't been a game update
                {
                    var overWrite = MessageBox.Show(string.Format("Your existing game data contains unexpected filesizes, and is likely already modified or predates Game Version {0}." +
                                                                  "\n\nIt is recommended that you do NOT store these files as backups, unless you are absolutely certain that they can reliably restore your game to a safe state!" +
                                                                  "\n\nAre you sure you want to save these as backup data?", SettingsManager.IntendedGameVersion), "Unexpected 00.dat / 01.dat Filesizes", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (overWrite != DialogResult.Yes)
                    {
                        return;
                    }
                }

                string overWriteMessage;

                if (BackupManager.BackupExists())
                {
                    if (SettingsManager.IntendedGameVersion < ModManager.GetMGSVersion())     //A recent update has occurred and the user should probably create new backups
                    {
                        overWriteMessage = (string.Format("Some backup data already exists. Since this version of SnakeBite is intended for MGSV Version {0} and is now MGSV Version {1}, it is recommended that you overwrite your old backup files with new data.", SettingsManager.IntendedGameVersion, ModManager.GetMGSVersion()) +
                                            "\n\nContinue?");
                    }
                    else
                    {
                        overWriteMessage = "Some backup data already exists. Continuing will overwrite your existing backups." +
                                           "\n\nAre you sure you want to continue?";
                    }

                    var overWrite = MessageBox.Show(overWriteMessage, "Overwrite Existing Files?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (overWrite != DialogResult.Yes)
                    {
                        return;
                    }
                }

                // create backup
                buttonSkip.Visible = false;
                buttonBack.Visible = false;
                buttonNext.Enabled = false;
                createBackupPage.panelProcessing.Visible = true;
                Application.UseWaitCursor = true;

                // do backup processing
                BackgroundWorker backupProcessor = new BackgroundWorker();
                backupProcessor.DoWork += new DoWorkEventHandler(BackupManager.backgroundWorker_CopyBackupFiles);
                backupProcessor.WorkerReportsProgress = true;
                backupProcessor.ProgressChanged      += new ProgressChangedEventHandler(backupProcessor_ProgressChanged);
                backupProcessor.RunWorkerAsync();

                while (backupProcessor.IsBusy)
                {
                    Application.DoEvents();
                    Thread.Sleep(10);
                }

                // move to merge dats
                mergeDatPage.panelProcessing.Visible = false;
                Application.UseWaitCursor            = false;

                contentPanel.Controls.Clear();
                contentPanel.Controls.Add(mergeDatPage);
                buttonNext.Enabled = true;

                displayPage = 3;
                break;

            case 3:
                // move 00/01 to a_chunk/a_texture
                buttonNext.Enabled = false;
                buttonBack.Visible = false;
                Tag = "noclose";
                mergeDatPage.panelProcessing.Visible = true;
                Application.UseWaitCursor            = true;

                BackgroundWorker mergeProcessor = new BackgroundWorker();
                mergeProcessor.WorkerSupportsCancellation = true;
                mergeProcessor.DoWork += new DoWorkEventHandler(ModManager.backgroundWorker_MergeAndCleanup);
                mergeProcessor.WorkerReportsProgress = true;
                mergeProcessor.ProgressChanged      += new ProgressChangedEventHandler(mergeProcessor_ProgressChanged);
                mergeProcessor.RunWorkerCompleted   += new RunWorkerCompletedEventHandler(mergeProcessor_Completed);
                mergeProcessor.RunWorkerAsync();

                while (mergeProcessor.IsBusy)
                {
                    Application.DoEvents();
                    Thread.Sleep(40);
                }

                if (setupComplete)
                {
                    Debug.LogLine("[Setup Wizard] Setup Complete. Snakebite is configured and ready to use.");
                    mergeDatPage.panelProcessing.Visible = false;
                    Application.UseWaitCursor            = false;

                    mergeDatPage.labelWelcome.Text     = "Setup complete";
                    mergeDatPage.labelWelcomeText.Text = "SnakeBite is configured and ready to use.";

                    buttonNext.Text    = "Do&ne";
                    buttonNext.Enabled = true;

                    displayPage = 4;
                }
                else
                {
                    Debug.LogLine("[Setup Wizard] Setup Incomplete.");
                    Tag = null;
                    GoToMergeDatPage();

                    buttonNext.Text = "Retry";
                }
                break;

            case 4:
                displayPage  = 5;
                DialogResult = DialogResult.OK;
                Close();
                break;
            }
        }
コード例 #16
0
        private static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            var commandName = string.Empty;
            var commandArgs = new List <string>();

            if (args.Length >= 1)
            {
                for (var i = 0; i < args.Length; i++)
                {
                    if (i == 0)
                    {
                        commandName = args[i];
                    }
                    else
                    {
                        commandArgs.Add(args[i]);
                    }
                }
            }

            Console.WriteLine("Welcome to SiteServer Cli Tool");
            Console.WriteLine();

            try
            {
                if (StringUtils.EqualsIgnoreCase(commandName, BackupManager.CommandName))
                {
                    BackupManager.Execute(commandArgs.ToArray());
                }
                else if (StringUtils.EqualsIgnoreCase(commandName, RestoreManager.CommandName))
                {
                    RestoreManager.Execute(commandArgs.ToArray());
                }
                else if (StringUtils.EqualsIgnoreCase(commandName, UpdateManager.CommandName))
                {
                    UpdateManager.Execute(commandArgs.ToArray());
                }
                else if (StringUtils.EqualsIgnoreCase(commandName, VersionManager.CommandName))
                {
                    VersionManager.Execute(commandArgs.ToArray());
                }
                else if (StringUtils.EqualsIgnoreCase(commandName, TestManager.CommandName))
                {
                    TestManager.Execute(commandArgs.ToArray());
                }
                else
                {
                    CliUtils.PrintLine();
                    CliUtils.PrintRow("Usage");
                    CliUtils.PrintLine();
                    BackupManager.PrintUsage();
                    RestoreManager.PrintUsage();
                    UpdateManager.PrintUsage();
                    VersionManager.PrintUsage();
                    CliUtils.PrintLine();
                    CliUtils.PrintRow("http://www.siteserver.cn/docs/cli");
                    CliUtils.PrintLine();
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                CliUtils.PrintError(ex.Message);

                var errorLogFilePath = CliUtils.CreateErrorLogFile("siteserver");

                CliUtils.AppendErrorLogs(errorLogFilePath, new List <TextLogInfo> {
                    new TextLogInfo
                    {
                        DateTime  = DateTime.Now,
                        Detail    = "Console Error",
                        Exception = ex
                    }
                });
            }
        }
コード例 #17
0
        private static void InstallBootstrapPatch()
        {
            var cAsmName    = Assembly.GetExecutingAssembly().GetName();
            var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var dataDir  = new DirectoryInfo(managedPath).Parent.Name;
            var gameName = dataDir.Substring(0, dataDir.Length - 5);

            loader.Debug("Finding backup");
            var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
            var bkp        = BackupManager.FindLatestBackup(backupPath);

            if (bkp == null)
            {
                loader.Warn("No backup found! Was BSIPA installed using the installer?");
            }

            loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");

            #region Insert patch into UnityEngine.CoreModule.dll

            {
                var unityPath = Path.Combine(managedPath,
                                             "UnityEngine.CoreModule.dll");

                var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
                {
                    ReadWrite   = false,
                    InMemory    = true,
                    ReadingMode = ReadingMode.Immediate
                });
                var unityModDef = unityAsmDef.MainModule;

                bool modified = false;
                foreach (var asmref in unityModDef.AssemblyReferences)
                {
                    if (asmref.Name == cAsmName.Name)
                    {
                        if (asmref.Version != cAsmName.Version)
                        {
                            asmref.Version = cAsmName.Version;
                            modified       = true;
                        }
                    }
                }

                var application = unityModDef.GetType("UnityEngine", "Application");

                MethodDefinition cctor = null;
                foreach (var m in application.Methods)
                {
                    if (m.IsRuntimeSpecialName && m.Name == ".cctor")
                    {
                        cctor = m;
                    }
                }

                var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);

                if (cctor == null)
                {
                    cctor = new MethodDefinition(".cctor",
                                                 MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
                                                 unityModDef.TypeSystem.Void);
                    application.Methods.Add(cctor);
                    modified = true;

                    var ilp = cctor.Body.GetILProcessor();
                    ilp.Emit(OpCodes.Call, cbs);
                    ilp.Emit(OpCodes.Ret);
                }
                else
                {
                    var ilp = cctor.Body.GetILProcessor();
                    for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
                    {
                        var ins = cctor.Body.Instructions[i];
                        switch (i)
                        {
                        case 0 when ins.OpCode != OpCodes.Call:
                            ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                            modified = true;
                            break;

                        case 0:
                        {
                            var methodRef = ins.Operand as MethodReference;
                            if (methodRef?.FullName != cbs.FullName)
                            {
                                ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                                modified = true;
                            }

                            break;
                        }

                        case 1 when ins.OpCode != OpCodes.Ret:
                            ilp.Replace(ins, ilp.Create(OpCodes.Ret));
                            modified = true;
                            break;
                        }
                    }
                }

                if (modified)
                {
                    bkp?.Add(unityPath);
                    unityAsmDef.Write(unityPath);
                }
                else
                {
                    return; // shortcut
                }
            }

            #endregion Insert patch into UnityEngine.CoreModule.dll

            loader.Debug("Ensuring Assembly-CSharp is virtualized");

            {
                var ascPath = Path.Combine(managedPath,
                                           "Assembly-CSharp.dll");

                #region Virtualize Assembly-CSharp.dll

                {
                    var ascModule = VirtualizedModule.Load(ascPath);
                    ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
                }

                #endregion Virtualize Assembly-CSharp.dll

                #region Anti-Yeet

                if (SelfConfig.SelfConfigRef.Value.ApplyAntiYeet)
                {
                    loader.Debug("Applying anti-yeet patch");

                    var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
                    {
                        ReadWrite   = false,
                        InMemory    = true,
                        ReadingMode = ReadingMode.Immediate
                    });
                    var ascModDef = ascAsmDef.MainModule;

                    var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
                    deleter.Methods.Clear(); // delete all methods

                    ascAsmDef.Write(ascPath);
                }

                #endregion
            }
        }
コード例 #18
0
        static void Main(string[] args)
        {
            string debugTag = "";

            #if DEBUG
            debugTag = " DEBUG";
            #endif

            Console.WriteLine("vellum v{0} build {1}\n{2}by clarkx86 & DeepBlue\n", UpdateChecker.ParseVersion(_localVersion, VersionFormatting.MAJOR_MINOR_REVISION) + debugTag, _localVersion.Build, new string(' ', 7));

            bool printHelp = false;

            OptionSet options = new OptionSet()
            {
                { "h|help", "Displays a help screen.", (string h) => { printHelp = h != null; } },
                { "c=|configuration=", "The configuration file to load settings from.", (string c) => { if (!String.IsNullOrWhiteSpace(c))
                                                                                                        {
                                                                                                            _configPath = c.Trim();
                                                                                                        }
                  } }
            };
            System.Collections.Generic.List <string> extraOptions = options.Parse(args);

            if (printHelp)
            {
                System.Console.WriteLine("Overview of available parameters:");
                options.WriteOptionDescriptions(Console.Out);
                System.Environment.Exit(0);
            }

            if (File.Exists(_configPath))
            {
                RunConfig = LoadConfiguration(_configPath);

                #if !DEBUG
                // Not yet supported due to file permission issues
                if (!RunConfig.Backups.StopBeforeBackup && System.Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    Console.WriteLine("NOTICE: Hot-backups are currently not supported on Windows. Please enable \"StopBeforeBackup\" in the \"{0}\" instead.", _configPath);
                    System.Environment.Exit(0);
                }
                #endif

                #region CONDITIONAL UPDATE CHECK
                if (RunConfig.CheckForUpdates)
                {
                    Console.WriteLine("Checking for updates... ");

                    if (_updateChecker.GetLatestVersion())
                    {
                        if (_updateChecker.RemoteVersion > _localVersion)
                        {
                            Console.WriteLine("\nA new update is available!\nLocal version:\t{0}\nRemote version:\t{1}\nVisit {2} to update.\n", UpdateChecker.ParseVersion(_localVersion, VersionFormatting.MAJOR_MINOR_REVISION), UpdateChecker.ParseVersion(_updateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION), @"https://git.io/vellum-latest");
                        }
                    }
                    else
                    {
                        System.Console.WriteLine("Could not check for updates.");
                    }
                }
                #endregion

                if (RunConfig.Renders.EnableRenders && String.IsNullOrWhiteSpace(RunConfig.Renders.PapyrusBinPath))
                {
                    Console.WriteLine("Disabling renders because no valid path to a Papyrus executable has been specified");
                    RunConfig.Renders.EnableRenders = false;
                }

                string bdsDirPath = Path.GetDirectoryName(RunConfig.BdsBinPath);

                #region BDS process and input thread
                // BDS
                ProcessStartInfo serverStartInfo = new ProcessStartInfo()
                {
                    FileName         = RunConfig.BdsBinPath,
                    WorkingDirectory = bdsDirPath
                };

                // Set environment variable for linux-based systems
                if (System.Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    serverStartInfo.EnvironmentVariables.Add("LD_LIBRARY_PATH", bdsDirPath);
                }

                ProcessManager bds = new ProcessManager(serverStartInfo, new string[] {
                    "^(" + RunConfig.WorldName.Trim() + @"(?>\/db)?\/\d+\.\w+\:\d+)",
                    "^(Saving...)",
                    "^(A previous save has not been completed.)",
                    "^(Data saved. Files are now ready to be copied.)",
                    "^(Changes to the level are resumed.)",
                    "Running AutoCompaction..."
                });

                // Stop BDS gracefully on unhandled exceptions
                if (RunConfig.StopBdsOnException)
                {
                    System.AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                    {
                        System.Console.WriteLine("Stopping Bedrock server due to an unhandled exception from vellum...");

                        if (bds.IsRunning)
                        {
                            bds.SendInput("stop");
                            bds.Process.WaitForExit();
                            bds.Close();
                        }
                    };
                }

                // Input thread
                _ioThread = new Thread(() =>
                {
                    while (_readInput)
                    {
                        inStream?.Invoke(Console.ReadLine());
                    }
                });
                _ioThread.Start();
                #endregion

                // Store current BDS version
                bds.RegisterMatchHandler(@"^.+ Version (\d+\.\d+\.\d+(?>\.\d+)?)", (object sender, MatchedEventArgs e) =>
                {
                    _bdsVersion = UpdateChecker.ParseVersion(e.Matches[0].Groups[1].Value, VersionFormatting.MAJOR_MINOR_REVISION_BUILD);
                });


                uint playerCount = 0;
                bool nextBackup  = true;
                if (RunConfig.Backups.OnActivityOnly)
                {
                    nextBackup = false;

                    // Player connect/ disconnect messages
                    bds.RegisterMatchHandler(@".+Player connected:\s(.+),", (object sender, MatchedEventArgs e) =>
                    {
                        playerCount++;
                        nextBackup = true;
                    });

                    bds.RegisterMatchHandler(@".+Player disconnected:\s(.+),", (object sender, MatchedEventArgs e) =>
                    {
                        playerCount--;
                    });
                }


                string worldPath     = Path.Join(bdsDirPath, "worlds", RunConfig.WorldName);
                string tempWorldPath = Path.Join(Directory.GetCurrentDirectory(), _tempPath, RunConfig.WorldName);

                _renderManager = new RenderManager(bds, RunConfig);
                _backupManager = new BackupManager(bds, RunConfig);

                if (RunConfig.Backups.BackupOnStartup)
                {
                    // Create initial world backup
                    Console.WriteLine("Creating initial world backup...");
                    _backupManager.CreateWorldBackup(worldPath, tempWorldPath, true, false); // If "StopBeforeBackup" is set to "true" this will also automatically start the server when it's done
                }

                // Start server in case the BackupManager hasn't started it yet
                if (!bds.IsRunning)
                {
                    bds.Start();
                    bds.WaitForMatch(@"^.+ (Server started\.)"); // Wait until BDS successfully started
                }

                // Backup interval
                if (RunConfig.Backups.EnableBackups)
                {
                    System.Timers.Timer backupIntervalTimer = new System.Timers.Timer(RunConfig.Backups.BackupInterval * 60000);
                    backupIntervalTimer.AutoReset = true;
                    backupIntervalTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                    {
                        if (nextBackup)
                        {
                            InvokeBackup(worldPath, tempWorldPath);

                            if (RunConfig.Backups.OnActivityOnly && playerCount == 0)
                            {
                                nextBackup = false;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Skipping this backup because no players were online since the last one was taken...");
                        }
                    };
                    backupIntervalTimer.Start();

                    if (RunConfig.Backups.StopBeforeBackup)
                    {
                        System.Timers.Timer backupNotificationTimer = new System.Timers.Timer((RunConfig.Backups.BackupInterval * 60000) - Math.Clamp(RunConfig.Backups.NotifyBeforeStop * 1000, 0, RunConfig.Backups.BackupInterval * 60000));
                        backupNotificationTimer.AutoReset = false;
                        backupNotificationTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                        {
                            bds.SendTellraw(String.Format("Shutting down server in {0} seconds to take a backup.", RunConfig.Backups.NotifyBeforeStop));
                        };
                        backupIntervalTimer.Start();
                    }
                }

                // Render interval
                if (RunConfig.Renders.EnableRenders)
                {
                    System.Timers.Timer renderIntervalTimer = new System.Timers.Timer(RunConfig.Renders.RenderInterval * 60000);
                    renderIntervalTimer.AutoReset = true;
                    renderIntervalTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                    {
                        InvokeRender(worldPath, tempWorldPath);
                    };
                    renderIntervalTimer.Start();
                }

                // Input thread
                inStream = (string text) =>
                {
                    if (RunConfig.BusyCommands || (!_backupManager.Processing && !_renderManager.Processing))
                    {
                        #region CUSTOM COMMANDS
                        MatchCollection cmd = Regex.Matches(text.ToLower().Trim(), @"(\S+)");

                        if (cmd.Count > 0)
                        {
                            bool result = false;
                            switch (cmd[0].Captures[0].Value)
                            {
                            case "force":
                                if (cmd.Count >= 3)
                                {
                                    switch (cmd[1].Captures[0].Value)
                                    {
                                    case "start":
                                        switch (cmd[2].Captures[0].Value)
                                        {
                                        case "backup":
                                            InvokeBackup(worldPath, tempWorldPath);
                                            result = true;
                                            break;

                                        case "render":
                                            InvokeRender(worldPath, tempWorldPath);
                                            result = true;
                                            break;
                                        }
                                        break;
                                    }
                                }
                                break;

                            case "stop":
                                System.Timers.Timer shutdownTimer = new System.Timers.Timer();
                                shutdownTimer.AutoReset = false;
                                shutdownTimer.Elapsed  += (object sender, ElapsedEventArgs e) => {
                                    // _renderManager.Abort();
                                    bds.SendInput("stop");
                                    bds.Process.WaitForExit();
                                    bds.Close();
                                    _readInput = false;
                                    shutdownTimer.Close();
                                    Console.WriteLine("vellum quit correctly");
                                };

                                if (cmd.Count == 2 && !String.IsNullOrWhiteSpace(cmd[1].Captures[0].Value))
                                {
                                    try
                                    {
                                        double interval = Convert.ToDouble(cmd[1].Captures[0].Value);
                                        shutdownTimer.Interval = (interval > 0 ? interval * 1000 : 1);
                                        bds.SendTellraw(String.Format("Scheduled shutdown in {0} seconds...", interval));
                                        result = true;
                                    } catch
                                    {
                                        Console.WriteLine("Could not schedule shutdown because \"{0}\" is not a valid number.", cmd[1].Captures[0].Value);
                                        result = false;
                                    }
                                }
                                else
                                {
                                    shutdownTimer.Interval = 1;
                                    result = true;
                                }

                                if (result)
                                {
                                    shutdownTimer.Start();
                                }
                                break;

                            case "reload":
                                if (cmd.Count == 2 && cmd[1].Captures[0].Value == "vellum")
                                {
                                    RunConfig = LoadConfiguration(_configPath);
                                }
                                else
                                {
                                    bds.SendInput(text);
                                }
                                result = true;
                                break;

                            case "updatecheck":
                                Console.WriteLine("Checking for updates...");

                                // BDS
                                UpdateChecker bdsUpdateChecker = new UpdateChecker(ReleaseProvider.HTML, "https://minecraft.net/en-us/download/server/bedrock/", @"https:\/\/minecraft\.azureedge\.net\/bin-" + (System.Environment.OSVersion.Platform == PlatformID.Win32NT ? "win" : "linux") + @"\/bedrock-server-(\d+\.\d+\.\d+(?>\.\d+)?)\.zip");
                                if (bdsUpdateChecker.GetLatestVersion())
                                {
                                    Console.WriteLine(String.Format("Bedrock Server:\t{0} -> {1}\t({2})", UpdateChecker.ParseVersion(_bdsVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), UpdateChecker.ParseVersion(bdsUpdateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), bdsUpdateChecker.RemoteVersion > _bdsVersion ? "outdated" : "up to date"));
                                }
                                else
                                {
                                    Console.WriteLine("Could not check for Bedrock server updates...");
                                }

                                // vellum
                                if (_updateChecker.GetLatestVersion())
                                {
                                    Console.WriteLine(String.Format("vellum:\t\t{0} -> {1}\t({2})", UpdateChecker.ParseVersion(_localVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), UpdateChecker.ParseVersion(_updateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), _updateChecker.RemoteVersion > _localVersion ? "outdated" : "up to date"));
                                }
                                else
                                {
                                    Console.WriteLine("Could not check for vellum updates...");
                                }

                                result = true;
                                break;

                            default:
                                result = true;
                                bds.SendInput(text);
                                break;
                            }

                            if (!result)
                            {
                                Console.WriteLine("Could not execute vellum command \"{0}\".", text);
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        Console.WriteLine("Could not execute vellum command \"{0}\". Please wait until all tasks have finished or enable \"BusyCommands\" in your \"{1}\".", text, _configPath);
                    }
                };
            }
            else
            {
                Console.WriteLine("No previous configuration file found. Creating one...");

                using (StreamWriter writer = new StreamWriter(_configPath))
                {
                    writer.Write(JsonConvert.SerializeObject(new RunConfiguration()
                    {
                        BdsBinPath = System.Environment.OSVersion.Platform != PlatformID.Win32NT ? "bedrock_server" : "bedrock_server.exe",
                        WorldName  = "Bedrock level",
                        Backups    = new BackupConfig()
                        {
                            EnableBackups    = true,
                            StopBeforeBackup = (System.Environment.OSVersion.Platform != PlatformID.Win32NT ? false : true), // Should be reverted to "false" by default when 1.16 releases
                            NotifyBeforeStop = 60,
                            ArchivePath      = "./backups/",
                            BackupsToKeep    = 10,
                            OnActivityOnly   = false,
                            BackupOnStartup  = true,
                            BackupInterval   = 60,
                            PreExec          = "",
                            PostExec         = "",
                        },
                        Renders = new RenderConfig()
                        {
                            EnableRenders     = true,
                            RenderInterval    = 180,
                            PapyrusBinPath    = "",
                            PapyrusGlobalArgs = "-w $WORLD_PATH -o $OUTPUT_PATH --htmlfile index.html -f png -q 100 --deleteexistingupdatefolder",
                            PapyrusTasks      = new string[] {
                                "--dim 0",
                                "--dim 1",
                                "--dim 2"
                            },
                            PapyrusOutputPath = ""
                        },
                        QuietMode          = false,
                        HideStdout         = true,
                        BusyCommands       = true,
                        CheckForUpdates    = true,
                        StopBdsOnException = true
                    }, Formatting.Indented));
                }

                Console.WriteLine(String.Format("Done! Please edit the \"{0}\" file and restart this application.", _configPath));
            }
        }
コード例 #19
0
ファイル: MainForm.cs プロジェクト: ridhouan/teamlab.v6.5
        private void buttonRestore_Click(object sender, EventArgs e)
        {
            var backuper = new BackupManager(textBoxBackup.Text, textBoxCoreConfig.Text, textBoxWebConfig.Text);
            backuper.AddBackupProvider(new Restarter());
            backuper.ProgressChanged += backuper_ProgressChanged;
            backuper.ProgressError += backuper_ProgressError;

            try
            {
                progress = true;
                error = false;
                labelStatus.Text = string.Empty;
                buttonRestore.Enabled = buttonCancel.Enabled = false;
                
                backuper.Load();
            }
            catch
            {
                progress = false;
                buttonRestore.Enabled = buttonCancel.Enabled = true;
                throw;
            }
        }
コード例 #20
0
        public void Start()
        {
            running = true;
            while (running)
            {
                List <Database> list = ReadFromXML();


                foreach (Database d in list)
                {
                    ConnectionData connectionData = new ConnectionData(d.ConnectionString);

                    var           builder       = new System.Data.SqlClient.SqlConnectionStringBuilder(d.ConnectionString);
                    string        database      = builder.InitialCatalog;
                    BackupManager backupManager = new BackupManager(connectionData);
                    string        lastRunResult = string.Empty;


                    using (var connection = JobStorage.Current.GetConnection())
                    {
                        var recurringJobs = connection.GetRecurringJobs();
                        if (recurringJobs.Count == 0)
                        {
                            RecurringJob.AddOrUpdate(database, () => BackupM.BackupDB(connectionData, database), d.Cronos);
                        }
                        else
                        {
                            var job = recurringJobs.FirstOrDefault(p => p.Id.Equals(database));

                            if (job != null)
                            {
                                try
                                {
                                    if (job.LastJobId != null)
                                    {
                                        var jobState = connection.GetStateData(job.LastJobId);
                                        lastRunResult = jobState.Name;


                                        if ((!job.Cron.Equals(d.Cronos)) || (lastRunResult.Equals("Failed")) || (lastRunResult.Equals("Expired")))
                                        {
                                            RecurringJob.AddOrUpdate(database, () => BackupM.BackupDB(connectionData, database), d.Cronos);
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Log.Error("Eroor job", e.Message);
                                }
                            }
                            else
                            {
                                RecurringJob.AddOrUpdate(database, () => BackupM.BackupDB(connectionData, database), d.Cronos);
                            }
                        }
                    }
                }
                FTP.FtpConnectionInfo ftpCon    = ReadFTPFromXML();
                FTP.FTPClient         fTPClient = new FTP.FTPClient(ftpCon.Host, ftpCon.Username, ftpCon.Password);

                foreach (var p in BackupM.dict)
                {
                    fTPClient.UploadFile(p.Value);
                }
            }
        }
コード例 #21
0
 public BackupsController()
 {
     BackupManager = Program.GetManager <BackupManager>();
 }
コード例 #22
0
        private static void Install(PatchContext context)
        {
            try
            {
                var backup = new BackupUnit(context);

                // Copying
                Console.WriteLine("Updating files... ");
                var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                bool isFlat             = Directory.Exists(nativePluginFolder) && Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                bool force        = !BackupManager.HasBackup(context) || context.Args.Contains("-f") || context.Args.Contains("--force");
                var  architecture = DetectArchitecture(context.Executable);

                Console.WriteLine("Architecture: {0}", architecture);

                CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force, backup,
                        (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat, architecture));

                Console.WriteLine("Successfully updated files!");

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                }

                // Deobfuscating

                /*var options = new Deobfuscator.Options();
                 * options.OneFileAtATime = false;
                 * var searchDir = new Deobfuscator.SearchDir() { InputDirectory = context.ManagedPath, OutputDirectory = Path.Combine(context.ManagedPath, "decompiled/"), SkipUnknownObfuscators = false };
                 * options.SearchDirs = new List<Deobfuscator.SearchDir>() { searchDir };
                 *              new Deobfuscator(options).DoIt();*/

                // Patching
                var patchedModule = PatchedModule.Load(context.EngineFile);
                if (!patchedModule.IsPatched)
                {
                    Console.Write("Patching UnityEngine.dll... ");
                    backup.Add(context.EngineFile);
                    patchedModule.Patch();
                    Console.WriteLine("Done!");
                }

                // Virtualizing
                if (File.Exists(context.AssemblyFile))
                {
                    var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
                    if (!virtualizedModule.IsVirtualized)
                    {
                        Console.Write("Virtualizing Assembly-Csharp.dll... ");
                        backup.Add(context.AssemblyFile);
                        virtualizedModule.Virtualize();
                        Console.WriteLine("Done!");
                    }
                }

                // Creating shortcut
                if (!File.Exists(context.ShortcutPath))
                {
                    Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
                    try
                    {
                        Shortcut.Create(
                            fileName: context.ShortcutPath,
                            targetPath: context.IPA,
                            arguments: Args(context.Executable, "--launch"),
                            workingDirectory: context.ProjectRoot,
                            description: "Launches the game and makes sure it's in a patched state",
                            hotkey: "",
                            iconPath: context.Executable
                            );
                        Console.WriteLine("Created");
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("Failed to create shortcut, but game was patched!");
                    }
                }
            }
            catch (Exception e)
            {
                Fail("Oops! This should not have happened.\n\n" + e);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Finished!");
            Console.ResetColor();
        }
コード例 #23
0
        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;
                        }
                        Watchers.ExperienceWatcher.Run();
                    }
                    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;
        }
コード例 #24
0
ファイル: NoteViewModel.cs プロジェクト: nelinory/tefterly
        private void NotesBackupHandler(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"{DateTime.Now.TimeOfDay} - [Action] Regular notes backup initiated");

            BackupManager.RegularBackup(_settingsService.Settings.BackupLocation, _settingsService.Settings.NotesLocation, _settingsService.Settings.Backup.MaxRegularBackups);
        }
コード例 #25
0
        public void BasicIncrementalBackupScenario2()
        {
            var dbName             = "basic_scenario_two";
            var backupFile         = "";
            var testConfigFileName = tmpFolder + "BasicScenario2.ini";

            var parser = new FileIniDataParser();
            var config = parser.ReadFile(defaultConfigIni);

            config["sqlserver"].SetKeyData(new KeyData("database")
            {
                Value = dbName
            });

            parser.WriteFile(testConfigFileName, config);

            var conn = new SqlConnection(string.Format("Server={0};Database=master;Trusted_Connection=True;", config["sqlserver"]["server"]));

            conn.Open();

            var logBackups = new List <string>();

            try
            {
                // Create the database and insert some data
                conn.Execute("create database " + dbName);
                conn.Execute("alter database " + dbName + " set recovery full");
                conn.ChangeDatabase(dbName);
                conn.Execute("create table test1 (test1 varchar(50))");
                conn.Execute("insert into test1 values ('data_full')");

                // Backup the database
                var backupManager = new BackupManager();
                var backupResult  = backupManager.Backup(new string[2] {
                    "full", testConfigFileName
                });

                Assert.AreEqual(0, backupResult.ReturnCode);
                Assert.IsFalse(File.Exists(backupResult.BackupName));

                // Do incremental stuff
                for (int i = 1; i <= 3; i++)
                {
                    // The minimum increment is a second between log backups
                    System.Threading.Thread.Sleep(1000);
                    conn.Execute(string.Format("insert into test1 values ('data_log_{0}')", i));

                    var backupLogResult = backupManager.Backup(new string[2] {
                        "incremental", testConfigFileName
                    });

                    Assert.AreEqual(0, backupLogResult.ReturnCode);
                    Assert.IsFalse(File.Exists(backupLogResult.BackupName));

                    logBackups.Add(backupLogResult.BackupName);
                }

                // Drop the database
                conn.ChangeDatabase("master");
                conn.Execute("drop database " + dbName);

                // Restore the backup using the restore manager
                var restoreMan = new RestoreManager();

                var argList = new List <string>()
                {
                    testConfigFileName, backupResult.BackupName
                };

                argList.AddRange(logBackups);

                restoreMan.Restore(argList.ToArray());

                // Verify that the restore worked
                conn.ChangeDatabase(dbName);
                var result = conn.Query("select test1 from test1 where test1 in ('data_full', 'data_log_1', 'data_log_2', 'data_log_3')");

                Assert.IsTrue(result.Count() == 4);
            }
            finally
            {
                // Cleanup our mess
                // S3
                var awsProfile = config["aws"]["profile"];
                Amazon.Util.ProfileManager.RegisterProfile(awsProfile, config["aws"]["access_key"], config["aws"]["secret_key"]);
                var creds     = Amazon.Util.ProfileManager.GetAWSCredentials(awsProfile);
                var awsClient = new AmazonS3Client(creds, Amazon.RegionEndpoint.USEast1);
                var listReq   = new ListObjectsRequest()
                {
                    BucketName = config["aws"]["bucket"]
                };

                var objects = awsClient.ListObjects(listReq);

                foreach (var obj in objects.S3Objects)
                {
                    if (obj.Key.IndexOf(dbName) != -1)
                    {
                        var delReq = new DeleteObjectRequest()
                        {
                            BucketName = config["aws"]["bucket"], Key = obj.Key
                        };

                        awsClient.DeleteObject(delReq);
                    }
                }

                // Testing database server
                conn.ChangeDatabase("master");
                conn.Execute("drop database " + dbName);

                if (File.Exists(backupFile))
                {
                    File.Delete(backupFile);
                }
            }
        }
コード例 #26
0
        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();
                        BackupManager.Run();
                    }
                    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");
                        await Reset();

                        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;
        }
コード例 #27
0
        public void BasicFullBackupScenario1()
        {
            var dbName             = "basic_scenario_one";
            var backupFile         = "";
            var testConfigFileName = tmpFolder + "BasicScenario1.ini";

            var parser = new FileIniDataParser();
            var config = parser.ReadFile(defaultConfigIni);

            config["sqlserver"].SetKeyData(new KeyData("database")
            {
                Value = dbName
            });

            parser.WriteFile(testConfigFileName, config);

            var conn = new SqlConnection(string.Format("Server={0};Database=master;Trusted_Connection=True;", config["sqlserver"]["server"]));

            conn.Open();

            try
            {
                // Create the database and insert some data
                conn.Execute("create database " + dbName);
                conn.ChangeDatabase(dbName);
                conn.Execute("create table test1 (test1 varchar(50))");
                conn.Execute("insert into test1 values ('data')");

                // Backup the database
                var backupManager = new BackupManager();
                var backupResult  = backupManager.Backup(new string[2] {
                    "full", testConfigFileName
                });

                Assert.AreEqual(0, backupResult.ReturnCode);
                Assert.IsFalse(File.Exists(backupFile));

                // Drop the database
                conn.ChangeDatabase("master");
                conn.Execute("drop database " + dbName);

                // Restore the backup from S3
                var restoreMan = new RestoreManager();

                restoreMan.Restore(new string[2] {
                    testConfigFileName, backupResult.BackupName
                });

                var awsProfile = config["aws"]["profile"];

                Amazon.Util.ProfileManager.RegisterProfile(awsProfile, config["aws"]["access_key"], config["aws"]["secret_key"]);

                var creds = Amazon.Util.ProfileManager.GetAWSCredentials(awsProfile);

                var awsClient = new AmazonS3Client(creds, Amazon.RegionEndpoint.USEast1);

                conn.ChangeDatabase(dbName);
                var result = conn.Query("select test1 from test1 where test1 = 'data'");

                Assert.IsTrue(result.Count() == 1);

                var listReq = new ListObjectsRequest()
                {
                    BucketName = config["aws"]["bucket"]
                };

                var objects = awsClient.ListObjects(listReq);

                foreach (var obj in objects.S3Objects)
                {
                    if (obj.Key.IndexOf(dbName) != -1)
                    {
                        var delReq = new DeleteObjectRequest()
                        {
                            BucketName = config["aws"]["bucket"], Key = obj.Key
                        };

                        awsClient.DeleteObject(delReq);
                    }
                }
            }
            finally
            {
                conn.ChangeDatabase("master");
                conn.Execute("drop database " + dbName);

                if (File.Exists(backupFile))
                {
                    File.Delete(backupFile);
                }
            }
        }
コード例 #28
0
 private void ButtonCreateNew_Click(object sender, RoutedEventArgs e)
 {
     BackupManager.CreateBackup($"BackupManual_{DateTime.Today.ToString("ddMMyyyy")}.zip");
     ListBoxBackups.Items.Clear();
     Load();
 }
コード例 #29
0
        static void Main(string[] args)
        {
            _logger = LogManager.GetCurrentClassLogger();
            var options = new Options();

            try
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                System.Console.WriteLine("HyperVBackup 3");
                System.Console.WriteLine("Copyright (C) 2012 Cloudbase Solutions SRL");
                System.Console.WriteLine("Copyright (C) 2016/2017 Coliseo Software SRL");
                System.Console.WriteLine("Copyright (C) 2021 Conrad Henke - 7ke.de");

                _logger.Info($"HyperVBackup started at {DateTime.Now}");

                var parser = new Parser(ConfigureSettings);
                if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(1)))
                {
                    GetConsoleWidth();
                    System.Console.WriteLine();

                    var vmNames = GetVmNames(options);

                    if (vmNames == null)
                    {
                        _logger.Info("Backing up all VMs on this server");
                    }

                    if (!Directory.Exists(options.Output))
                    {
                        throw new Exception($"The folder \"{options.Output}\" is not valid");
                    }

                    if (options.CleanOutputDays != 0)
                    {
                        CleanOutputByDays(options.Output, options.CleanOutputDays);
                    }

                    if (options.CleanOutputMb != 0)
                    {
                        CleanOutputByMegabytes(options.Output, options.CleanOutputMb);
                    }

                    var nameType = options.Name ? VmNameType.ElementName : VmNameType.SystemName;

                    var mgr = new BackupManager();
                    mgr.BackupProgress += MgrBackupProgress;

                    System.Console.CancelKeyPress += Console_CancelKeyPress;

                    var backupOptions = new HyperVBackUp.Engine.Options
                    {
                        CompressionLevel = options.CompressionLevel,
                        Output           = options.Output,
                        OutputFormat     = options.OutputFormat,
                        SingleSnapshot   = options.SingleSnapshot,
                        VhdInclude       = options.VhdInclude,
                        VhdIgnore        = options.VhdIgnore,
                        Password         = options.Password,
                        ZipFormat        = options.ZipFormat,
                        DirectCopy       = options.DirectCopy,
                        MultiThreaded    = options.MultiThreaded
                    };

                    var vmNamesMap = mgr.VssBackup(vmNames, nameType, backupOptions, _logger);

                    CheckRequiredVMs(vmNames, nameType, vmNamesMap);

                    ShowElapsedTime(stopwatch);

                    if (!string.IsNullOrEmpty(options.OnSuccess))
                    {
                        _logger.Info("Executing OnSucess program");
                        ExecuteProcess(options.OnSuccess, _logger);
                    }

                    _logger.Info($"HyperVBackup ended at {DateTime.Now}");
                }
            }
            catch (BackupCancelledException ex)
            {
                System.Console.Error.WriteLine(string.Format(ex.Message));
                _logger.Error(ex.ToString());

                if (!string.IsNullOrEmpty(options.OnFailure))
                {
                    _logger.Info("Executing OnFailure program");
                    ExecuteProcess(options.OnFailure, _logger);
                }

                Environment.Exit(3);
            }
            catch (Exception ex)
            {
                System.Console.Error.WriteLine($"Error: {ex.Message}");
                System.Console.Error.WriteLine(ex.StackTrace);
                _logger.Error(ex.ToString());

                if (!string.IsNullOrEmpty(options.OnFailure))
                {
                    _logger.Info("Executing OnFailure program");
                    ExecuteProcess(options.OnFailure, _logger);
                }

                Environment.Exit(2);
            }

            Environment.Exit(_cancel ? 3 : 0);
        }
コード例 #30
0
#pragma warning disable 1998
        public static async void Initialize()
#pragma warning restore 1998
        {
            LocalizeDictionary.Instance.Culture = CultureInfo.GetCultureInfo("en-US");
            _startUpTime = DateTime.UtcNow;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Config.Load();
            Log.Info($"HDT: {Helper.GetCurrentVersion()}, Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}");
            var splashScreenWindow = new SplashScreenWindow();

#if (SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow);
                while (!updateCheck.IsCompleted)
                {
                    await Task.Delay(500);

                    if (splashScreenWindow.SkipUpdate)
                    {
                        break;
                    }
                }
            }
#endif
            splashScreenWindow.ShowConditional();
            Log.Initialize();
            ConfigManager.Run();
            LocUtil.UpdateCultureInfo();
            var newUser = ConfigManager.PreviousVersion == null;
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            UITheme.InitializeTheme();
            ThemeManager.Run();
            ResourceMonitor.Run();
            Game = new GameV2();
            Game.SecretsManager.OnSecretsChanged += cards => Overlay.ShowSecrets(cards);
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();
            splashScreenWindow.Close();

            if (Config.Instance.DisplayHsReplayNoteLive && ConfigManager.PreviousVersion != null && ConfigManager.PreviousVersion < new Version(1, 1, 0))
            {
                MainWindow.FlyoutHsReplayNote.IsOpen = true;
            }

            if (ConfigManager.UpdatedVersion != null)
            {
#if (!SQUIRREL)
                Updater.Cleanup();
#endif
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
#if (SQUIRREL && !DEV)
                if (Config.Instance.CheckForDevUpdates && !Config.Instance.AllowDevUpdates.HasValue)
                {
                    MainWindow.ShowDevUpdatesMessage();
                }
#endif
            }
            DataIssueResolver.Run();

#if (!SQUIRREL)
            Helper.CopyReplayFiles();
#endif
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            PluginManager.Instance.LoadPluginsFromDefaultPath();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Config.Instance.ShowCapturableOverlay)
            {
                Windows.CapturableOverlay = new CapturableOverlayWindow();
                Windows.CapturableOverlay.Show();
            }

            if (LogConfigUpdater.LogConfigUpdateFailed)
            {
                MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
            }
            else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
            {
                MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.").Forget();
                Overlay.ShowRestartRequiredWarning();
            }
            LogWatcherManger.Start(Game).Forget();

            NewsManager.LoadNews();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync().Forget();
            }

            ApiWrapper.UpdateAccountStatus().Forget();

            Initialized = true;

            Influx.OnAppStart(
                Helper.GetCurrentVersion(),
                newUser,
                (int)(DateTime.UtcNow - _startUpTime).TotalSeconds,
                PluginManager.Instance.Plugins.Count
                );
        }
コード例 #31
0
        private static void InstallBootstrapPatch()
        {
            var cAsmName    = Assembly.GetExecutingAssembly().GetName();
            var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var dataDir  = new DirectoryInfo(managedPath).Parent.Name;
            var gameName = dataDir.Substring(0, dataDir.Length - 5);

            injector.Debug("Finding backup");
            var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
            var bkp        = BackupManager.FindLatestBackup(backupPath);

            if (bkp == null)
            {
                injector.Warn("No backup found! Was BSIPA installed using the installer?");
            }

            injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");

            #region Insert patch into UnityEngine.CoreModule.dll

            {
                var unityPath = Path.Combine(managedPath,
                                             "UnityEngine.CoreModule.dll");

                // this is a critical section because if you exit in here, CoreModule can die
                using var critSec = CriticalSection.ExecuteSection();

                var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
                {
                    ReadWrite   = false,
                    InMemory    = true,
                    ReadingMode = ReadingMode.Immediate
                });
                var unityModDef = unityAsmDef.MainModule;

                bool modified = false;
                foreach (var asmref in unityModDef.AssemblyReferences)
                {
                    if (asmref.Name == cAsmName.Name)
                    {
                        if (asmref.Version != cAsmName.Version)
                        {
                            asmref.Version = cAsmName.Version;
                            modified       = true;
                        }
                    }
                }

                var application = unityModDef.GetType("UnityEngine", "Application");

                if (application == null)
                {
                    injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Application!"
                                      + "Nothing to patch to get ourselves into the Unity run cycle!");
                    goto endPatchCoreModule;
                }

                MethodDefinition cctor = null;
                foreach (var m in application.Methods)
                {
                    if (m.IsRuntimeSpecialName && m.Name == ".cctor")
                    {
                        cctor = m;
                    }
                }

                var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);

                if (cctor == null)
                {
                    cctor = new MethodDefinition(".cctor",
                                                 MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
                                                 unityModDef.TypeSystem.Void);
                    application.Methods.Add(cctor);
                    modified = true;

                    var ilp = cctor.Body.GetILProcessor();
                    ilp.Emit(OpCodes.Call, cbs);
                    ilp.Emit(OpCodes.Ret);
                }
                else
                {
                    var ilp = cctor.Body.GetILProcessor();
                    for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
                    {
                        var ins = cctor.Body.Instructions[i];
                        switch (i)
                        {
                        case 0 when ins.OpCode != OpCodes.Call:
                            ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                            modified = true;
                            break;

                        case 0:
                        {
                            var methodRef = ins.Operand as MethodReference;
                            if (methodRef?.FullName != cbs.FullName)
                            {
                                ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
                                modified = true;
                            }

                            break;
                        }

                        case 1 when ins.OpCode != OpCodes.Ret:
                            ilp.Replace(ins, ilp.Create(OpCodes.Ret));
                            modified = true;
                            break;
                        }
                    }
                }

                if (modified)
                {
                    bkp?.Add(unityPath);
                    unityAsmDef.Write(unityPath);
                }
            }
endPatchCoreModule:
            #endregion Insert patch into UnityEngine.CoreModule.dll

            injector.Debug("Ensuring game assemblies are virtualized");

            #region Virtualize game assemblies
            bool isFirst = true;
            foreach (var name in SelfConfig.GameAssemblies_)
            {
                var ascPath = Path.Combine(managedPath, name);

                using var execSec = CriticalSection.ExecuteSection();

                try
                {
                    injector.Debug($"Virtualizing {name}");
                    using var ascModule = VirtualizedModule.Load(ascPath);
                    ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
                }
                catch (Exception e)
                {
                    injector.Error($"Could not virtualize {ascPath}");
                    if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
                    {
                        injector.Error(e);
                    }
                }

                if (isFirst)
                {
                    try
                    {
                        injector.Debug("Applying anti-yeet patch");

                        var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
                        {
                            ReadWrite   = false,
                            InMemory    = true,
                            ReadingMode = ReadingMode.Immediate
                        });
                        var ascModDef = ascAsmDef.MainModule;

                        var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
                        deleter.Methods.Clear(); // delete all methods

                        ascAsmDef.Write(ascPath);

                        isFirst = false;
                    }
                    catch (Exception e)
                    {
                        injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
                        if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
                        {
                            injector.Warn(e);
                        }
                    }
                }
            }
            #endregion
        }
コード例 #32
0
        public static async void Initialize()
        {
            Log.Info($"Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Config.Load();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
#if (SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow);
                while (!updateCheck.IsCompleted)
                {
                    await Task.Delay(500);

                    if (splashScreenWindow.SkipUpdate)
                    {
                        break;
                    }
                }
            }
#endif
            Log.Initialize();
            ConfigManager.Run();
            var newUser = ConfigManager.PreviousVersion == null;
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            Helper.UpdateAppTheme();
            ThemeManager.Run();
            ResourceMonitor.Run();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();
            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            if (Config.Instance.ReselectLastDeckUsed)
            {
                MainWindow.SelectLastUsedDeck();
                Config.Instance.ReselectLastDeckUsed = false;
                Config.Save();
            }
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
#if (!SQUIRREL)
                Updater.Cleanup();
#endif
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

#if (!SQUIRREL)
            Helper.CopyReplayFiles();
#endif
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Config.Instance.ShowCapturableOverlay)
            {
                Windows.CapturableOverlay = new CapturableOverlayWindow();
                Windows.CapturableOverlay.Show();
            }

            if (LogConfigUpdater.LogConfigUpdateFailed)
            {
                MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
            }
            else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
            {
                MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.");
                Overlay.ShowRestartRequiredWarning();
            }
            LogReaderManager.Start(Game).Forget();

            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync().Forget();
            }

            Initialized = true;

            Influx.OnAppStart(Helper.GetCurrentVersion(), loginType, newUser);
        }
コード例 #33
0
            private void Window(int id)
            {
                Configuration config = SAVE.configuration;

                DISPLAY lastDisplay = display;

                BackupManager manager = SAVE.manager;

                try
                {
                    GUILayout.BeginVertical();
                    GUILayout.BeginHorizontal();
                    GUI.enabled = manager.RestoreCompleted() && manager.BackupsCompleted() && manager.NumberOfBackupSets() > 0;
                    if (GUILayout.Button("Backup All", GUI.skin.button))
                    {
                        display = DISPLAY.BACKUP;
                        // don't start another backup if there is still a backup running
                        if (SAVE.manager.BackupsCompleted())
                        {
                            backupCount     = manager.BackupAll();
                            backupCloseTime = DateTime.Now.AddSeconds(BACKUP_DISPLAY_REMAINS_OPEN_TIME);
                        }
                        else
                        {
                            Log.Warning("won't start another backup until all backups finished");
                        }
                    }
                    GUI.enabled = true;
                    // Restore
                    GUI.enabled = manager.NumberOfBackupSets() > 0;
                    if (DrawDisplayToggle("Restore", DISPLAY.RESTORE) && !SAVE.manager.RestoreCompleted())
                    {
                        display = DISPLAY.RESTORING;
                    }
                    GUI.enabled = true;
                    // Configure
                    DrawDisplayToggle("Configure", DISPLAY.CONFIGURE);
                    // Status
                    DrawDisplayToggle("Status", DISPLAY.STATUS);
                    // Hide
                    DrawDisplayToggle("Clone", DISPLAY.CLONE);
                    // Hide
                    DrawDisplayToggle("Hide", DISPLAY.HIDDEN);
                    GUILayout.EndHorizontal();
                    //
                    switch (display)
                    {
                    case DISPLAY.BACKUP:
                        DisplayBackup();
                        break;

                    case DISPLAY.RESTORING:
                        DisplayRestoring();
                        break;

                    case DISPLAY.RESTORE:
                        DisplayRestore();
                        break;

                    case DISPLAY.CONFIGURE:
                        DisplayConfigure();
                        break;

                    case DISPLAY.STATUS:
                        DisplayStatus();
                        break;

                    case DISPLAY.CLONE:
                        DisplayClone();
                        break;

                    case DISPLAY.CLONING:
                        DisplayCloning();
                        break;

                    case DISPLAY.HIDDEN:
                        // are we ingame? then make the window disappear (this shouldn't be neccessary, but just to be sure...)
                        if (HighLogic.LoadedScene == GameScenes.MAINMENU)
                        {
                            SetVisible(true);
                        }
                        else
                        {
                            SetVisible(false);
                        }
                        break;
                    }
                    GUILayout.EndVertical();

                    if (display == DISPLAY.BACKUP && backupCloseTime < DateTime.Now && manager.Queuedbackups() == 0)
                    {
                        display = DISPLAY.HIDDEN;
                    }
                }
                catch (Exception e)
                {
                    Log.Error("exception: " + e.Message);
                }

                // resize GUI if display changes
                if (lastDisplay != display)
                {
                    this.bounds.height = 0;
                }
                if (S.A.V.E.src.util.io.ConfigNodeIO.fixedWindowFloating)
                {
                    GUI.DragWindow();
                }
            }
コード例 #34
0
            public void RunJob()
            {
                var filename = Path.Combine(tmpfolder, Id + ".tbm");
                try
                {
                    if (!Directory.Exists(tmpfolder))
                    {
                        Directory.CreateDirectory(tmpfolder);
                    }

                    var backuper = new BackupManager(filename, currentWebConfigPath);
                    backuper.ProgressChanged += (o, e) =>
                    {
                        Percentage = Math.Max(0, Math.Min((int)e.Progress / 2, 50));
                    };

                    backuper.Save(Tenant);

                    using (var stream = new FileStream(filename, FileMode.Open))
                    using (var progressStream = new ProgressStream(stream))
                    {
                        progressStream.OnReadProgress += (o, e) =>
                        {
                            Percentage = Math.Max(0, Math.Min(100, 50 + e / 2));
                        };

                        var uploadname = string.Format("{0}-{1:yyyyMMdd-HHmmss}.zip", CoreContext.TenantManager.GetTenant(Tenant).TenantDomain, DateTime.UtcNow).ToLowerInvariant();
                        ExpireDate = DateTime.UtcNow.Add(expire);
                        Status = GetStore().SavePrivate(string.Empty, uploadname, progressStream, ExpireDate);
                    }

                    IsCompleted = true;
                    Percentage = 100;

                    NotifyHelper.SendAboutBackupCompleted(Tenant, userId, (string)Status, ExpireDate);
                }
                catch (Exception e)
                {
                    Error = e;
                    log.Error(e);
                }
                finally
                {
                    try
                    {
                        if (File.Exists(filename))
                        {
                            File.Delete(filename);
                        }
                    }
                    catch (Exception e)
                    {
                        log.Error(e);
                    }
                }
            }
コード例 #35
0
        public MainWindow()
        {
            InitializeComponent();

            // Set up the content grids.
            contentGrids = new List <Grid>
            {
                StatusGrid,
                BackupsGrid
            };

            // show only the status content grid.
            hideAllContentGrids();
            contentGrids[0].Visibility = Visibility.Visible;

            // Set up the backupmanager.
            bm = new BackupManager(this);
            Thread bmthr = new Thread(() => bm.MainAsync());

            bmthr.Priority = ThreadPriority.AboveNormal;
            bmthr.Start();

            // Set up backuplist
            backupListContents     = new ObservableCollection <backupListRow>();
            backupList.ItemsSource = backupListContents;

            //Set up taskbar icon.
            taskbarIcon                    = new TaskbarIcon();
            taskbarIcon.ToolTip            = "SharpBackup";
            taskbarIcon.Icon               = SystemIcons.Application;
            taskbarIcon.Visibility         = Visibility.Collapsed;
            taskbarIcon.DoubleClickCommand = new RelayCommand(this);

            bm.backups.CollectionChanged += (object sender, NotifyCollectionChangedEventArgs e) =>
            {
                ObservableCollection <backupListRow> newBackupListContents = new ObservableCollection <backupListRow>();

                for (int i = 0; i < bm.backups.Count; i++)
                {
                    var item = bm.backups[i];
                    newBackupListContents.Add(new backupListRow()
                    {
                        Name = item.name, Path = item.url, LastBackup = item.lastBackup.ToLongDateString(), Status = item.StatusString, Progress = item.progressString, SizeProgress = item.sizeProgress, AllProgress = item.allProgress, paused = item.paused
                    });
                }

                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() {
                    backupListContents.Clear();
                    for (int i = 0; i < newBackupListContents.Count; i++)
                    {
                        backupListContents.Add(newBackupListContents[i]);

                        /*Button pauseButton = (Button)((ListViewItem)backupList.Items.GetItemAt(i)).FindName("pauseButton");
                         * if  (newBackupListContents[i].paused)
                         * {
                         *  pauseButton.Content = "Resume";
                         * }
                         * else
                         * {
                         *  pauseButton.Content = "Pause";
                         * }*/
                    }
                    statusText.Text = String.Format("Loaded {0} backups.", bm.backups.Count());
                }));
            };
        }