예제 #1
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
#if x86
                var curPath64 = PathEx.Combine(PathEx.LocalDir, "LMMS64Portable.exe");
                if (Environment.Is64BitOperatingSystem && File.Exists(curPath64))
                {
                    ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                    return;
                }
                var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\lmms");
                var updPath = PathEx.Combine(appDir, "LMMSUpdater.exe");
#else
                var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\lmms64");
                var updPath = PathEx.Combine(appDir, "LMMSUpdater64.exe");
#endif
                var altAppDir = PathEx.AltCombine(appDir);
                var appPath   = Path.Combine(appDir, "lmms.exe");
                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || !File.Exists(updPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updPath)))
                {
                    return;
                }

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine(false));
                    return;
                }

                Helper.ApplicationStart(updPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    return;
                }

                var dataDir    = PathEx.Combine(PathEx.LocalDir, "Data");
                var altDataDir = PathEx.AltCombine(dataDir);
                var dataDirs   = new[]
                {
                    Path.Combine(dataDir, "lmms\\presets"),
                    Path.Combine(dataDir, "lmms\\projects"),
                    Path.Combine(dataDir, "lmms\\samples\\gig"),
                    Path.Combine(dataDir, "lmms\\samples\\sf2")
                };
                foreach (var dir in dataDirs)
                {
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }

                var configPath = PathEx.Combine(dataDir, ".lmmsrc.xml");
                var fileMap    = new Dictionary <string, string>
                {
                    {
                        "%UserProfile%\\.lmmsrc.xml",
                        configPath
                    }
                };
                var config = string.Empty;
                if (File.Exists(configPath))
                {
                    config = File.ReadAllText(configPath);
                }
                if (!config.ContainsEx("{0}", "{1}", "{2}", "{3}"))
                {
                    config = Resources.DefaultConfig;
                }
                config = string.Format(config, appDir, dataDir, altDataDir, altAppDir);
                File.WriteAllText(configPath, config);
                Helper.FileForwarding(Helper.Options.Start, fileMap);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.FileForwarding(Helper.Options.Exit, fileMap);
                if (!File.Exists(configPath))
                {
                    return;
                }
                config = File.ReadAllText(configPath);
                config = config.Replace(appDir, "{0}")
                         .Replace(dataDir, "{1}")
                         .Replace(altDataDir, "{2}")
                         .Replace(altAppDir, "{3}");
                File.WriteAllText(configPath, config);
            }
        }
예제 #2
0
        internal static void Enable(bool enabled, bool quiet = false)
        {
            if (!Elevation.IsAdministrator)
            {
                using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.SystemIntegration} {enabled} {quiet}", true, false))
                    if (process?.HasExited == false)
                    {
                        process.WaitForExit();
                    }
                return;
            }
            var varKey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
            var varDir = Reg.ReadString(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
            var curDir = PathEx.LocalDir;

            if (!enabled || !varDir.EqualsEx(curDir))
            {
                var curPath    = EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false);
                var sendToPath = PathEx.Combine(Environment.SpecialFolder.SendTo, "Apps Launcher.lnk");
                if (enabled)
                {
                    Reg.Write(Registry.LocalMachine, varKey, Settings.EnvironmentVariable, curDir);
                    FileEx.CreateShellLink(curPath, sendToPath);
                }
                else
                {
                    Reg.RemoveEntry(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
                    PathEx.ForceDelete(sendToPath);
                }
                if (WinApi.NativeHelper.SendNotifyMessage((IntPtr)0xffff, (uint)WinApi.WindowMenuFlags.WmSettingChange, (UIntPtr)0, "Environment"))
                {
                    foreach (var baseKey in new[]
                    {
                        "*",
                        "Folder"
                    })
                    {
                        varKey = Path.Combine(baseKey, "shell\\portableapps");
                        if (enabled)
                        {
                            if (string.IsNullOrWhiteSpace(Reg.ReadString(Registry.ClassesRoot, varKey, null)))
                            {
                                Reg.Write(Registry.ClassesRoot, varKey, null, Language.GetText(nameof(en_US.shellText)));
                            }
                            Reg.Write(Registry.ClassesRoot, varKey, "Icon", $"\"{PathEx.LocalPath}\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                        varKey = Path.Combine(varKey, "command");
                        if (enabled)
                        {
                            Reg.Write(Registry.ClassesRoot, varKey, null, $"\"{PathEx.LocalPath}\" \"%1\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                    }
                    var desktopPath = PathEx.Combine(Environment.SpecialFolder.Desktop, "Apps Launcher.lnk");
                    if (enabled)
                    {
                        FileEx.CreateShellLink(curPath, desktopPath);
                    }
                    else
                    {
                        PathEx.ForceDelete(sendToPath);
                    }

                    if (enabled)
                    {
                        using (var process = ProcessEx.Start(PathEx.LocalPath, ActionGuid.FileTypeAssociationAll, true, false))
                            if (process?.HasExited == false)
                            {
                                process.WaitForExit();
                            }
                    }

                    if (!quiet)
                    {
                        MessageBox.Show(Language.GetText(nameof(en_US.OperationCompletedMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    return;
                }
            }
            if (!quiet)
            {
                MessageBox.Show(Language.GetText(nameof(en_US.OperationCanceledMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
예제 #3
0
        /// <summary>
        /// Injects the specified process with the r77 DLL using reflective DLL injection.
        /// <para>Helper32.exe or Helper64.exe is invoked to perform injection.</para>
        /// </summary>
        /// <param name="process">The process to inject.</param>
        /// <returns>
        /// An enumerable of <see cref="LogMessage" /> entries to be displayed in the log view.
        /// </returns>
        public static IEnumerable <LogMessage> Inject(ProcessView process)
        {
            string helperPath = GetFilePath(process.Is64Bit == true ? "Helper64.exe" : "Helper32.exe", out LogMessage helperPathLogMessage);

            if (helperPath == null)
            {
                yield return(helperPathLogMessage);

                yield break;
            }

            string dllPath = GetFilePath(process.Is64Bit == true ? "r77-x64.dll" : "r77-x86.dll", out LogMessage dllPathLogMessage);

            if (dllPath == null)
            {
                yield return(dllPathLogMessage);

                yield break;
            }

            if (!Win32.IsProcessRunning(process.Id))
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Warning,
                                 new LogFileItem(process.Name),
                                 new LogTextItem("(PID " + process.Id + ") is no longer running.")
                             ));

                yield break;
            }

            if (ProcessEx.Execute(helperPath, "-inject " + process.Id + " \"" + dllPath + "\"") == 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Information,
                                 new LogTextItem("Injected"),
                                 new LogFileItem(process.Name),
                                 new LogTextItem("(PID " + process.Id + ").")
                             ));
            }
            else
            {
                string reason;
                if (process.Name.StartsWith(Config.HidePrefix))
                {
                    reason = "The filename starts with '" + Config.HidePrefix + "'.";
                }
                else if (process.IsR77Service)
                {
                    reason = "The process is the r77 service process.";
                }
                else if (process.IsHelper)
                {
                    reason = "The process is a helper process.";
                }
                else if (process.IntegrityLevel < ProcessIntegrityLevel.Medium)
                {
                    reason = "Sandboxes are not supported";
                }
                else
                {
                    reason = Path.GetFileName(helperPath) + " returned an error code.";
                }

                yield return(new LogMessage
                             (
                                 LogMessageType.Warning,
                                 new LogTextItem("Injection of"),
                                 new LogFileItem(process.Name),
                                 new LogTextItem("(PID " + process.Id + ") failed."),
                                 new LogDetailsItem(reason)
                             ));
            }
        }
예제 #4
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                var appDir = PathEx.Combine(PathEx.LocalDir, "App", Environment.Is64BitOperatingSystem ? "p95win64" : "p95win32");
                if (!Directory.Exists(appDir))
                {
                    return;
                }
                var appPath = Path.Combine(appDir, "prime95.exe");

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine(false));
                    return;
                }

#if LEGACY
                if (!File.Exists(appPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)))
                {
                    return;
                }
#else
                var updaterPath = Path.Combine(appDir, Environment.Is64BitOperatingSystem ? "Prime95Updater64.exe" : "Prime95Updater.exe");
                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || !File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
                {
                    return;
                }

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }
#endif

                try
                {
                    var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");
                    var cfgPath = PathEx.Combine(appDir, "prime.txt");
                    if (!File.Exists(cfgPath))
                    {
                        File.Create(cfgPath).Close();
                    }
                    if (!File.ReadAllText(cfgPath).EqualsEx(dataDir))
                    {
                        File.WriteAllText(cfgPath, $"WorkingDir={dataDir}");
                    }
                    cfgPath = PathEx.Combine(dataDir, "prime.txt");
                    if (!File.Exists(cfgPath))
                    {
                        if (!Directory.Exists(dataDir))
                        {
                            Directory.CreateDirectory(dataDir);
                        }
                        File.WriteAllText(cfgPath, "TrayIcon=0");
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), ProcessWindowStyle.Maximized, false);
            }
        }
예제 #5
0
        public static void RedistHandling(Options options, params EnvironmentEx.Redist.Flags[] versions)
        {
            var dict = new Dictionary <EnvironmentEx.Redist.Flags, Dictionary <int, List <int> > >();

            foreach (var version in versions)
            {
                if (!dict.ContainsKey(version))
                {
                    dict.Add(version, new Dictionary <int, List <int> >());
                }
                switch (version)
                {
                case EnvironmentEx.Redist.Flags.VC2005X86:
                    if (!dict[version].ContainsKey(2005))
                    {
                        dict[version].Add(2005, new List <int>());
                    }
                    dict[version][2005].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2005X64:
                    if (!dict[version].ContainsKey(2005))
                    {
                        dict[version].Add(2005, new List <int>());
                    }
                    dict[version][2005].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2008X86:
                    if (!dict[version].ContainsKey(2008))
                    {
                        dict[version].Add(2008, new List <int>());
                    }
                    dict[version][2008].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2008X64:
                    if (!dict[version].ContainsKey(2008))
                    {
                        dict[version].Add(2008, new List <int>());
                    }
                    dict[version][2008].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2010X86:
                    if (!dict[version].ContainsKey(2010))
                    {
                        dict[version].Add(2010, new List <int>());
                    }
                    dict[version][2010].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2010X64:
                    if (!dict[version].ContainsKey(2010))
                    {
                        dict[version].Add(2010, new List <int>());
                    }
                    dict[version][2010].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2012X86:
                    if (!dict[version].ContainsKey(2012))
                    {
                        dict[version].Add(2012, new List <int>());
                    }
                    dict[version][2012].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2012X64:
                    if (!dict[version].ContainsKey(2012))
                    {
                        dict[version].Add(2012, new List <int>());
                    }
                    dict[version][2012].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2013X86:
                    if (!dict[version].ContainsKey(2013))
                    {
                        dict[version].Add(2013, new List <int>());
                    }
                    dict[version][2013].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2013X64:
                    if (!dict[version].ContainsKey(2013))
                    {
                        dict[version].Add(2013, new List <int>());
                    }
                    dict[version][2013].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2015X86:
                    if (!dict[version].ContainsKey(2015))
                    {
                        dict[version].Add(2015, new List <int>());
                    }
                    dict[version][2015].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2015X64:
                    if (!dict[version].ContainsKey(2015))
                    {
                        dict[version].Add(2015, new List <int>());
                    }
                    dict[version][2015].Add(64);
                    break;

                case EnvironmentEx.Redist.Flags.VC2017X86:
                    if (!dict[version].ContainsKey(2017))
                    {
                        dict[version].Add(2017, new List <int>());
                    }
                    dict[version][2017].Add(86);
                    break;

                case EnvironmentEx.Redist.Flags.VC2017X64:
                    if (!dict[version].ContainsKey(2017))
                    {
                        dict[version].Add(2017, new List <int>());
                    }
                    dict[version][2017].Add(64);
                    break;

                default:
                    return;
                }
            }
            foreach (var data in dict)
            {
                var version = data.Key;
                foreach (var vars in data.Value)
                {
                    var year = vars.Key;
                    foreach (var arch in vars.Value)
                    {
                        var path = PathEx.Combine(PathEx.LocalDir, $"_CommonRedist\\vcredist\\{year}\\vcredist_x{arch}.exe");
                        if (!File.Exists(path))
                        {
                            return;
                        }
                        var iniPath = Path.ChangeExtension(PathEx.LocalPath, ".ini");
                        switch (options)
                        {
                        case Options.Exit:
                            if (Ini.ReadDirect("Redist", version.ToString(), iniPath).EqualsEx("True"))
                            {
                                return;
                            }
                            using (var p = ProcessEx.Start(path, "/q /uninstall /norestart", Elevation.IsAdministrator, false))
                                if (p?.HasExited == false)
                                {
                                    p.WaitForExit();
                                }
                            break;

                        default:
                            if (Ini.ReadDirect("Redist", version.ToString(), iniPath).EqualsEx("False"))
                            {
                                Elevation.RestartAsAdministrator(EnvironmentEx.CommandLine(false));
                            }
                            if (EnvironmentEx.Redist.IsInstalled(version))
                            {
                                Ini.WriteDirect("Redist", version.ToString(), true, iniPath);
                                break;
                            }
                            var info = FileVersionInfo.GetVersionInfo(PathEx.LocalPath);
                            if (!Ini.ReadDirect("Redist", version.ToString(), iniPath).EqualsEx("True", "False"))
                            {
                                MessageBoxEx.TopMost = true;
                                MessageBoxEx.ButtonText.OverrideEnabled = true;
                                MessageBoxEx.ButtonText.Yes             = "&Yes";
                                MessageBoxEx.ButtonText.No     = "&No";
                                MessageBoxEx.ButtonText.Cancel = "&Cancel";
                                var msg    = $"Microsoft Visual C++ {year} Redistributable Package (x{arch}) is required to run this porgram.{Environment.NewLine}{Environment.NewLine}Would you like to permanently install this package (yes) or temporarily (no)?";
                                var result = MessageBoxEx.Show(msg, info.FileDescription, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                if (result == DialogResult.Cancel)
                                {
                                    RedistHandling(Options.Exit, versions);
                                    Environment.Exit(Environment.ExitCode);
                                }
                                Ini.WriteDirect("Redist", version.ToString(), result == DialogResult.Yes, iniPath);
                                if (result != DialogResult.Yes)
                                {
                                    Elevation.RestartAsAdministrator(EnvironmentEx.CommandLine(false));
                                }
                            }
                            var notifyBox = new NotifyBox();
                            notifyBox.Show($"Microsoft Visual C++ {year} Redistributable Package (x{arch}) has been initialized . . .", info.FileDescription, NotifyBox.NotifyBoxStartPosition.Center);
                            using (var p = ProcessEx.Start(path, "/q /norestart", Elevation.IsAdministrator, false))
                                if (p?.HasExited == false)
                                {
                                    p.WaitForExit();
                                }
                            notifyBox.Close();
                            if (!EnvironmentEx.Redist.IsInstalled(version))
                            {
                                Environment.ExitCode = 1;
                                Environment.Exit(Environment.ExitCode);
                            }
                            break;
                        }
                    }
                }
            }
        }
예제 #6
0
        public bool StartInstall()
        {
            InstallStarted = false;
            if (Transfer.IsBusy || !File.Exists(DestPath))
            {
                return(false);
            }

            const string nonHash  = "None";
            var          fileHash = default(string);

            foreach (var(_, item2, _, item4) in SrcData)
            {
                if (!item4)
                {
                    continue;
                }

                if (fileHash == default || fileHash == nonHash)
                {
                    switch (item2.Length)
                    {
                    case Crypto.Md5.HashLength:
                        fileHash = DestPath.EncryptFile();
                        break;

                    case Crypto.Sha1.HashLength:
                        fileHash = DestPath.EncryptFile(ChecksumAlgorithm.Sha1);
                        break;

                    case Crypto.Sha256.HashLength:
                        fileHash = DestPath.EncryptFile(ChecksumAlgorithm.Sha256);
                        break;

                    case Crypto.Sha384.HashLength:
                        fileHash = DestPath.EncryptFile(ChecksumAlgorithm.Sha384);
                        break;

                    case Crypto.Sha512.HashLength:
                        fileHash = DestPath.EncryptFile(ChecksumAlgorithm.Sha512);
                        break;

                    default:
                        fileHash = nonHash;
                        break;
                    }
                }

                if (fileHash != nonHash && !fileHash.EqualsEx(item2))
                {
                    switch (MessageBoxEx.Show(string.Format(CultureInfo.InvariantCulture, Language.GetText(nameof(en_US.ChecksumErrorMsg)), Path.GetFileName(DestPath)), Resources.GlobalTitle, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3))
                    {
                    case DialogResult.Ignore:
                        break;

                    case DialogResult.Retry:
                        AutoRetry = true;
                        continue;

                    default:
                        continue;
                    }
                }

                if (Directory.Exists(AppData.InstallDir))
                {
                    if (!BreakFileLocks(AppData.InstallDir, false))
                    {
                        MessageBoxEx.Show(string.Format(CultureInfo.InvariantCulture, Language.GetText(nameof(en_US.InstallSkippedMsg)), AppData.Name), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        continue;
                    }
                }

                if (DestPath.EndsWithEx(".7z", ".rar", ".zip"))
                {
                    if (!File.Exists(CorePaths.FileArchiver))
                    {
                        throw new PathNotFoundException(CorePaths.FileArchiver);
                    }
                    using (var process = SevenZip.DefaultArchiver.Extract(DestPath, AppData.InstallDir))
                        if (process?.HasExited == false)
                        {
                            process.WaitForExit();
                        }
                }
                else
                {
                    var appsDir = CorePaths.AppsDir;
                    using (var process = ProcessEx.Start(DestPath, appsDir, $"/DESTINATION=\"{appsDir}\\\"", Elevation.IsAdministrator, false))
                        if (process?.HasExited == false)
                        {
                            process.WaitForInputIdle(0x1000);
                            try
                            {
                                var buttons = Settings.NsisButtons;
                                if (buttons == null)
                                {
                                    throw new NotSupportedException();
                                }
                                var okButton  = buttons.Take(2).ToArray();
                                var langId    = WinApi.NativeHelper.GetUserDefaultUILanguage();
                                var wndState  = langId == 1031 || langId == 1033 || langId == 2057 ? WinApi.ShowWindowFlags.ShowMinNoActive : WinApi.ShowWindowFlags.ShowNa;
                                var stopwatch = Stopwatch.StartNew();
                                var minimized = new List <IntPtr>();
                                var counter   = new CounterInvestor <int>();
                                while (stopwatch.Elapsed.TotalMinutes < 5d)
                                {
                                    if (process.HasExited)
                                    {
                                        break;
                                    }
                                    string title;
                                    using (var proc = Process.GetProcessById(process.Id))
                                        title = proc.MainWindowTitle;
                                    if (string.IsNullOrEmpty(title))
                                    {
                                        continue;
                                    }
                                    var parent = WinApi.NativeHelper.FindWindow(null, title);
                                    if (parent == IntPtr.Zero)
                                    {
                                        continue;
                                    }
                                    if (!minimized.Contains(parent) && WinApi.NativeHelper.ShowWindowAsync(parent, wndState))
                                    {
                                        minimized.Add(parent);
                                    }
                                    foreach (var button in buttons)
                                    {
                                        var child = WinApi.NativeHelper.FindWindowEx(parent, IntPtr.Zero, "Button", button);
                                        if (child == IntPtr.Zero)
                                        {
                                            continue;
                                        }
                                        if (counter.Increase(button.GetHashCode()) > 10)
                                        {
                                            if (button.EqualsEx(okButton))
                                            {
                                                goto Manually;
                                            }
                                            continue;
                                        }
                                        WinApi.NativeHelper.SendMessage(child, 0xf5u, IntPtr.Zero, IntPtr.Zero);
                                    }
                                }
                            }
                            catch (Exception ex) when(ex.IsCaught())
                            {
                                Log.Write(ex);
                            }
Manually:
                            if (!process.HasExited)
                            {
                                try
                                {
                                    using (var proc = Process.GetProcessById(process.Id))
                                    {
                                        var hWnd = WinApi.NativeHelper.FindWindow(null, proc.MainWindowTitle);
                                        WinApi.NativeHelper.ShowWindowAsync(hWnd, WinApi.ShowWindowFlags.ShowNormal);
                                        WinApi.NativeHelper.SetForegroundWindow(hWnd);
                                        WinApi.NativeHelper.SetWindowPos(hWnd, new IntPtr(-1), 0, 0, 0, 0, WinApi.SetWindowPosFlags.NoMove | WinApi.SetWindowPosFlags.NoSize);
                                    }
                                }
                                catch (Exception ex) when(ex.IsCaught())
                                {
                                    Log.Write(ex);
                                }
                                process.WaitForExit();
                            }
                        }

                    // fix for messy app installer
                    var retries = 0;
retry:
                    try
                    {
                        var appDirs = new[]
                        {
                            Path.Combine(appsDir, "App"),
                            Path.Combine(appsDir, "Data"),
                            Path.Combine(appsDir, "Other")
                        };
                        if (appDirs.Any(Directory.Exists))
                        {
                            if (!Directory.Exists(AppData.InstallDir))
                            {
                                Directory.CreateDirectory(AppData.InstallDir);
                            }
                            else
                            {
                                BreakFileLocks(AppData.InstallDir);
                                foreach (var dir in new[] { "App", "Other" }.Select(name => Path.Combine(AppData.InstallDir, name)).Where(Directory.Exists))
                                {
                                    Directory.Delete(dir, true);
                                }
                                foreach (var file in Directory.EnumerateFiles(AppData.InstallDir, "*.*", SearchOption.TopDirectoryOnly))
                                {
                                    File.Delete(file);
                                }
                            }
                            foreach (var dir in appDirs)
                            {
                                if (!Directory.Exists(dir))
                                {
                                    continue;
                                }
                                var dirName = Path.GetFileName(dir);
                                if (string.IsNullOrEmpty(dirName))
                                {
                                    continue;
                                }
                                BreakFileLocks(dir);
                                if (dirName.EqualsEx("Data"))
                                {
                                    Directory.Delete(dir, true);
                                    continue;
                                }
                                var innerDir = Path.Combine(AppData.InstallDir, dirName);
                                Directory.Move(innerDir, dir);
                            }
                            foreach (var file in Directory.EnumerateFiles(appsDir, "*.*", SearchOption.TopDirectoryOnly))
                            {
                                if (FileEx.IsHidden(file) || file.EndsWithEx(".7z", ".rar", ".zip", ".paf.exe"))
                                {
                                    continue;
                                }
                                var fileName = Path.GetFileName(file);
                                if (string.IsNullOrEmpty(fileName))
                                {
                                    continue;
                                }
                                BreakFileLocks(file);
                                var innerFile = Path.Combine(AppData.InstallDir, fileName);
                                File.Move(innerFile, file);
                            }
                        }
                    }
                    catch (Exception ex) when(ex.IsCaught())
                    {
                        Log.Write(ex);
                        if (retries >= 15)
                        {
                            return(false);
                        }
                        retries++;
                        Thread.Sleep(1000);
                        goto retry;
                    }
                }

                FileEx.TryDelete(DestPath);
                InstallStarted = true;
                return(true);
            }
            return(false);
        }
예제 #7
0
        internal static void Associate(LocalAppData appData, bool quiet = false, Form owner = default(Form))
        {
            if (appData?.Settings?.FileTypes?.Any() != true)
            {
                MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.associateBtnMsg)), Settings.Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (!Elevation.IsAdministrator)
            {
                if (owner != default(Form))
                {
                    owner.TopMost = false;
                    owner.Enabled = false;
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressFlags.Indeterminate);
                }
                var bw = new BackgroundWorker();
                bw.DoWork += (sender, args) =>
                {
                    using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.FileTypeAssociation} \"{appData.Key}\"", true, false))
                        if (!process?.HasExited == true)
                        {
                            process.WaitForExit();
                        }
                };
                bw.RunWorkerCompleted += (sender, args) =>
                {
                    if (owner == default(Form))
                    {
                        return;
                    }
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressFlags.NoProgress);
                    if (WinApi.NativeHelper.GetForegroundWindow() != owner.Handle)
                    {
                        WinApi.NativeHelper.SetForegroundWindow(owner.Handle);
                    }
                    owner.Enabled = true;
                    owner.TopMost = true;
                };
                bw.RunWorkerAsync();
                return;
            }

            var assocData = new FileTypeAssocData
            {
                AppKey    = appData.Key,
                InstallId = Settings.SystemInstallId
            };

            using (var dialog = new ResourcesEx.IconBrowserDialog(Settings.IconResourcePath, Settings.Window.Colors.BaseDark, Settings.Window.Colors.ControlText, Settings.Window.Colors.Button, Settings.Window.Colors.ButtonText, Settings.Window.Colors.ButtonHover))
            {
                dialog.TopMost = true;
                dialog.Plus();
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.IconPath))
                {
                    assocData.IconPath = dialog.IconPath;
                    assocData.IconId   = dialog.IconId.ToString();
                }
            }

            if (!FileEx.Exists(assocData.IconPath) || string.IsNullOrEmpty(assocData.IconId))
            {
                goto Cancel;
            }

            MessageBoxEx.ButtonText.OverrideEnabled = true;
            MessageBoxEx.ButtonText.Yes             = "App";
            MessageBoxEx.ButtonText.No     = "Launcher";
            MessageBoxEx.ButtonText.Cancel = Language.GetText(nameof(en_US.Cancel));
            var result = MessageBoxEx.Show(Language.GetText(nameof(en_US.AssociateAppWayQuestion)), Settings.Title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            switch (result)
            {
            case DialogResult.Yes:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(appData.FilePath, false, false);
                break;

            case DialogResult.No:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false, false);
                break;

            default:
                goto Cancel;
            }

            if (FileEx.Exists(assocData.StarterPath))
            {
                appData.Settings.FileTypeAssoc = assocData;
            }
            else
            {
                goto Cancel;
            }

            assocData = appData.Settings?.FileTypeAssoc;
            assocData?.SystemRegistryAccess?.AssociateFileTypes(false);
            return;

Cancel:
            MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.OperationCanceledMsg)), MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #8
0
 /// <summary>
 /// Initializes an instance of <see cref="StartedCommandEvent"/>.
 /// </summary>
 public StartedCommandEvent(ProcessEx process) => Process = process;
예제 #9
0
 public void ShowAbout() => ProcessEx.StartShellExecute(App.GitHubProjectUrl);
예제 #10
0
        private async void DownloadAndInstallProfileIfNecessary()
        {
            if (_job.IosAdhoc || _job.IosAppStore)
            {
                var appId = _job.Company.CompanySettings.Any(s => s.Key == "Package")
                    ? _job.Company.CompanySettings.First(s => s.Key == "Package").Value
                    : null;

                if (string.IsNullOrWhiteSpace(_job.Company.AppleAppStoreCredentials.Username) ||
                    string.IsNullOrWhiteSpace(_job.Company.AppleAppStoreCredentials.Password))
                {
                    UpdateJob("Skipping download of provisioning profile, missing Apple Store Credentials");
                    return;
                }

                var     credential = ProcessEx.GetProcess("/usr/local/bin/fastlane-credentials", string.Format("add --user {0} --password {1}", _job.Company.AppleAppStoreCredentials.Username, _job.Company.AppleAppStoreCredentials.Password));
                Process process    = Process.Start(credential);

                if (process != null)
                {
                    UpdateJob(process.StandardOutput.ReadToEnd());
                }
                else
                {
                    UpdateJob("fastlane-credentials process not found");
                }

                var cert = ProcessEx.GetProcess("/usr/local/bin/cert", string.Format("-u {0}", _job.Company.AppleAppStoreCredentials.Username));
                process = Process.Start(cert);

                if (process != null)
                {
                    UpdateJob(process.StandardOutput.ReadToEnd());
                }
                else
                {
                    UpdateJob("Cert process not found");
                }

                if (_job.IosAdhoc)
                {
                    var sigh = ProcessEx.GetProcess("/usr/local/bin/sigh", string.Format("-a  {0} -u {1} --adhoc", appId, _job.Company.AppleAppStoreCredentials.Username));
                    process = Process.Start(sigh);

                    if (process != null)
                    {
                        UpdateJob(process.StandardOutput.ReadToEnd());
                    }
                }

                if (_job.IosAppStore)
                {
                    var sigh = ProcessEx.GetProcess("/usr/local/bin/sigh", string.Format("-a  {0} -u {1}", appId, _job.Company.AppleAppStoreCredentials.Username));
                    process = Process.Start(sigh);

                    if (process != null)
                    {
                        UpdateJob(process.StandardOutput.ReadToEnd());
                    }
                }
            }
        }
예제 #11
0
        private void Customize(string sourceDirectory, DeploymentJob job)
        {
            var company = job.Company;

            UpdateJob("Service Url : " + job.ServerUrl);
            UpdateJob("Customize - Build Config Tool Customization");

            var sln         = string.Format("{0}/ConfigTool.iOS.sln", Path.Combine(sourceDirectory, "Src", "ConfigTool"));
            var projectName = "NinePatchMaker.Lib";

            if (_builder.ProjectIsInSolution(sln, projectName))
            {
                var ninePatchProjectConfi = String.Format("\"--project:{0}\" \"--configuration:{1}\"", projectName, "Release");
                _builder.BuildProjectUsingMdTool(string.Format("build " + ninePatchProjectConfi + "  \"{0}\"", sln));
            }
            else
            {
                UpdateJob("Skipping NinePatch.Lib because it does not exist on this version");
            }

            projectName = "NinePatchMaker";
            if (_builder.ProjectIsInSolution(sln, projectName))
            {
                var ninePatchProjectConfi = String.Format("\"--project:{0}\" \"--configuration:{1}\"", projectName, "Release");
                _builder.BuildProjectUsingMdTool(string.Format("build " + ninePatchProjectConfi + "  \"{0}\"", sln));
            }
            else
            {
                UpdateJob("Skipping NinePatch because it does not exist on this version");
            }

            var mainConfig = String.Format("\"--project:{0}\" \"--configuration:{1}\"", "apcurium.MK.Booking.ConfigTool", "Release");

            _builder.BuildProjectUsingMdTool(string.Format("build " + mainConfig + "  \"{0}/ConfigTool.iOS.sln\"", Path.Combine(sourceDirectory, "Src", "ConfigTool")));

            UpdateJob("Run Config Tool Customization");

            var workingDirectory = Path.Combine(sourceDirectory, "Src", "ConfigTool", "apcurium.MK.Booking.ConfigTool.Console", "bin", "Release");
            var configToolRun    = ProcessEx.GetProcess("/usr/local/bin/mono", string.Format("apcurium.MK.Booking.ConfigTool.exe {0} {1}", company.CompanyKey, job.ServerUrl), workingDirectory);

            using (var exeProcess = Process.Start(configToolRun))
            {
                var output = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during customization, " + output);
                }
                UpdateJob("Customize Successful");
            }

            SleepFor(5);

            UpdateJob("Customization Finished");
            UpdateJob("Run Localization tool for Android");

            var localizationToolRun = new ProcessStartInfo {
                FileName               = "/usr/local/bin/mono",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments              = "output/LocalizationTool.exe -t=android -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/Android/Resources/Values/String.xml\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputAndroid = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for android");
                }
                UpdateJob(outputAndroid);
            }

            SleepFor(5);

            UpdateJob("Run Localization tool for Android Finished");
            UpdateJob("Run Localization tool for iOS");

            localizationToolRun = new ProcessStartInfo
            {
                FileName = "/usr/local/bin/mono",
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments = "output/LocalizationTool.exe -t=ios -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/iOS/en.lproj/Localizable.strings\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputiOS = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for iOS");
                }
                UpdateJob(outputiOS);
            }

            SleepFor(5);
            UpdateJob("Run Localization tool for iOS Finished");

            if (!job.CallBox)
            {
                return;
            }

            UpdateJob("Run Localization tool for Callbox");

            localizationToolRun = new ProcessStartInfo
            {
                FileName               = "/usr/local/bin/mono",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments              = "output/LocalizationTool.exe -t=callbox -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/MK.Callbox.Mobile.Client.Android/Resources/Values/Strings.xml\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputCallbox = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for callbox");
                }
                UpdateJob(outputCallbox);
            }

            SleepFor(5);
            UpdateJob("Run Localization tool for Callbox Finished");
        }
예제 #12
0
    internal async Task <ProcessResult> RunDotNetNewAsync(
        string templateName,
        string auth              = null,
        string language          = null,
        bool useLocalDB          = false,
        bool noHttps             = false,
        bool errorOnRestoreError = true,
        string[] args            = null,
        // Used to set special options in MSBuild
        IDictionary <string, string> environmentVariables = null)
    {
        var hiveArg   = $" --debug:disable-sdk-templates --debug:custom-hive \"{TemplatePackageInstaller.CustomHivePath}\"";
        var argString = $"new {templateName} {hiveArg}";

        environmentVariables ??= new Dictionary <string, string>();
        if (!string.IsNullOrEmpty(auth))
        {
            argString += $" --auth {auth}";
        }

        if (!string.IsNullOrEmpty(language))
        {
            argString += $" -lang {language}";
        }

        if (useLocalDB)
        {
            argString += $" --use-local-db";
        }

        if (noHttps)
        {
            argString += $" --no-https";
        }

        if (args != null)
        {
            foreach (var arg in args)
            {
                argString += " " + arg;
            }
        }

        // Save a copy of the arguments used for better diagnostic error messages later.
        // We omit the hive argument and the template output dir as they are not relevant and add noise.
        ProjectArguments = argString.Replace(hiveArg, "");

        argString += $" -o {TemplateOutputDir}";

        // Only run one instance of 'dotnet new' at once, as a workaround for
        // https://github.com/aspnet/templating/issues/63

        await DotNetNewLock.WaitAsync();

        try
        {
            Output.WriteLine("Acquired DotNetNewLock");

            if (Directory.Exists(TemplateOutputDir))
            {
                Output.WriteLine($"Template directory already exists, deleting contents of {TemplateOutputDir}");
                Directory.Delete(TemplateOutputDir, recursive: true);
            }

            using var execution = ProcessEx.Run(Output, AppContext.BaseDirectory, DotNetMuxer.MuxerPathOrDefault(), argString, environmentVariables);
            await execution.Exited;

            var result = new ProcessResult(execution);

            // Because dotnet new automatically restores but silently ignores restore errors, need to handle restore errors explicitly
            if (errorOnRestoreError && (execution.Output.Contains("Restore failed.") || execution.Error.Contains("Restore failed.")))
            {
                result.ExitCode = -1;
            }

            return(result);
        }
        finally
        {
            DotNetNewLock.Release();
            Output.WriteLine("Released DotNetNewLock");
        }
    }
예제 #13
0
        protected async Task <string> RunProcessAsync(string filePath, string arguments)
        {
            var result = await ProcessEx.RunAsync(filePath, arguments);

            return(string.Join("", result.StandardOutput));
        }
예제 #14
0
 private void AddBtn_Click(object sender, EventArgs e) =>
 ProcessEx.Start(CorePaths.AppsDownloader);
예제 #15
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
#if x86
                if (Environment.Is64BitOperatingSystem)
                {
                    var curName   = Path.GetFileNameWithoutExtension(PathEx.LocalPath);
                    var curPath64 = PathEx.Combine(PathEx.LocalDir, $"{curName}64.exe");
                    ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                    return;
                }
#endif

                var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\Steam");
                var appPath = Path.Combine(appDir, "Steam.exe");
                var cmdLine = EnvironmentEx.CommandLine(false);

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, cmdLine, true);
                    return;
                }

                var iniPath = Path.ChangeExtension(PathEx.LocalPath, ".ini");
                if (string.IsNullOrEmpty(iniPath))
                {
                    return;
                }

                const string steamAppsDefVar = "%CurDir%\\Data\\steamapps";
                if (!File.Exists(iniPath))
                {
                    var iniContent = new[]
                    {
                        "[Settings]",
                        "",
                        "; True to clear caches when Steam is closed; otherwise, False.",
                        "ImproveSteamStartTime=True",
                        "",
                        "; This option allows forwarding of the default steam game install directory.",
                        "; Steam handles this directory as if would be still on the default location.",
                        $"SteamAppsPathOverride={steamAppsDefVar}",
                        "",
                        "; Set start arguments that are used when Steam Portable creates a new instance.",
                        "; Options: https://developer.valvesoftware.com/wiki/Command_Line_Options",
                        ";StartArguments=-silent steam://friends/status/online"
                    };
                    File.WriteAllLines(iniPath, iniContent);
                }

                var steamAppsVar = Ini.Read("Settings", "SteamAppsPathOverride", steamAppsDefVar, iniPath);
                if (!steamAppsVar.EqualsEx(steamAppsDefVar))
                {
                    var steamAppsDir = PathEx.Combine(steamAppsVar);
                    if (!PathEx.IsValidPath(steamAppsDir))
                    {
                        steamAppsVar = steamAppsDefVar;
                    }
                }

                var defServiceDir = PathEx.Combine("%CommonProgramFiles(x86)%\\Steam");
                var serviceDir    = PathEx.Combine(PathEx.LocalDir, "App\\Service");
                var dirMap        = new Dictionary <string, string>
                {
                    {
                        defServiceDir,
                        serviceDir
                    },
                    {
                        "%LocalAppData%\\Steam",
                        "%CurDir%\\Data\\cache"
                    },
                    {
                        "%CurDir%\\App\\Steam\\steamapps",
                        steamAppsVar
                    }
                };

                var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");
                foreach (var d in dirMap.Keys.Skip(2))
                {
                    var dir = PathEx.Combine(d);
                    if (!Directory.Exists(dir) || Data.DirIsLink(dir))
                    {
                        continue;
                    }
                    using (var p = ProcessEx.Send(string.Format(Resources.ForceMove, dir, dataDir), true, false))
                        if (p?.HasExited == false)
                        {
                            p.WaitForExit();
                        }
                    if (!Directory.Exists(dir))
                    {
                        continue;
                    }
                    try
                    {
                        Directory.Delete(dir, true);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                        if (Data.ForceDelete(dir, true))
                        {
                            continue;
                        }
                        if (Ini.ReadDirect("Cache", "Hard", iniPath).EqualsEx("True"))
                        {
                            Ini.WriteDirect("Cache", null, null, iniPath);
                            continue;
                        }
                        Ini.WriteDirect("Cache", "Hard", true, iniPath);
                        ProcessEx.Start(PathEx.LocalPath, EnvironmentEx.CommandLine(false), true);
                    }
                }
                if (Ini.ReadDirect("Cache", "Hard", iniPath).EqualsEx("True"))
                {
                    Ini.WriteDirect("Cache", null, null, iniPath);
                }

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                var scMap = new Dictionary <string, string>
                {
                    {
                        "%CurDir%\\App\\Steam\\appcache",
                        "%CurDir%\\Data\\shortcuts\\appcache"
                    },
                    {
                        "%CurDir%\\App\\Steam\\config",
                        "%CurDir%\\Data\\shortcuts\\config"
                    },
                    {
                        "%CurDir%\\App\\Steam\\depotcache",
                        "%CurDir%\\Data\\shortcuts\\depotcache"
                    },
                    {
                        "%CurDir%\\App\\Steam\\dumps",
                        "%CurDir%\\Data\\shortcuts\\dumps"
                    },
                    {
                        "%CurDir%\\App\\Steam\\htmlcache",
                        "%CurDir%\\Data\\shortcuts\\htmlcache"
                    },
                    {
                        "%CurDir%\\App\\Steam\\logs",
                        "%CurDir%\\Data\\shortcuts\\logs"
                    },
                    {
                        "%CurDir%\\App\\Steam\\music",
                        "%CurDir%\\Data\\shortcuts\\music"
                    },
                    {
                        "%CurDir%\\App\\Steam\\remoteui",
                        "%CurDir%\\Data\\shortcuts\\remoteui"
                    },
                    {
                        "%CurDir%\\App\\Steam\\skins",
                        "%CurDir%\\Data\\shortcuts\\skins"
                    },
                    {
                        "%CurDir%\\App\\Steam\\userdata",
                        "%CurDir%\\Data\\shortcuts\\userdata"
                    },
                    {
                        "%CurDir%\\App\\Steam\\vrpanorama",
                        "%CurDir%\\Data\\shortcuts\\vrpanorama"
                    }
                };

                var scDir = Path.Combine(dataDir, "shortcuts");
                foreach (var data in scMap)
                {
                    var dir1 = PathEx.Combine(data.Key);
                    var dir2 = PathEx.Combine(data.Value);
                    try
                    {
                        if (Directory.Exists(dir2))
                        {
                            Data.DirCopy(dir2, dir1, true, true);
                            Directory.Delete(dir2, true);
                        }
                        if (!Directory.Exists(dir1))
                        {
                            Directory.CreateDirectory(dir1);
                        }
                        if (!Directory.Exists(scDir))
                        {
                            Directory.CreateDirectory(scDir);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    Data.CreateShortcut(dir1, dir2);
                }

                var regKeys = new[]
                {
                    "HKCU\\Software\\Valve",
                    "HKLM\\SOFTWARE\\Valve"
#if !x86
                    ,
                    "HKLM\\SOFTWARE\\Wow6432Node\\Valve"
#endif
                };

                Helper.RegForwarding(Helper.Options.Start, regKeys);

                for (var i = 0; i < regKeys.Length; i++)
                {
                    var regKey = $"{regKeys[i]}\\Steam";
                    switch (i)
                    {
                    case 0:
                        Reg.Write(regKey, "SteamExe", PathEx.AltCombine(appPath).ToLower());
                        Reg.Write(regKey, "SteamPath", PathEx.AltCombine(appDir).ToLower());
                        Reg.Write(regKey, "SourceModInstallPath", PathEx.AltCombine(appDir, "steamapps\\sourcemods").ToLower());

                        regKey = $"{regKey}\\ActiveProcess";
                        Reg.Write(regKey, "SteamClientDll", PathEx.AltCombine(appDir, "steamclient.dll").ToLower());
                        Reg.Write(regKey, "SteamClientDll64", PathEx.AltCombine(appDir, "steamclient64.dll").ToLower());
                        break;

                    case 1:
#if !x86
                    case 2:
#endif
                        Reg.Write(regKey, "InstallPath", appDir);

#if !x86
                        if (i == 1)
                        {
                            continue;
                        }
#endif

                        regKey = $"{regKey}\\Apps\\CommonRedist";
                        Reg.Write($"{regKey}\\.NET\\3.5", "3.5 SP1", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\3.5 Client Profile", "3.5 Client Profile SP1", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.0", "4.0", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.0 Client Profile", "4.0 Client Profile", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.5", "4.5", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.5.1", "4.5.1", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.5.2", "4.5.2", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.6", "4.6", 1, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\.NET\\4.6.1", "4.6.1", 1, RegistryValueKind.DWord);

                        var value = File.Exists(PathEx.Combine("%system%\\d3d9.dll")) ? 1 : 0;
                        Reg.Write($"{regKey}\\DirectX", "June2010", value, RegistryValueKind.DWord);
                        Reg.Write($"{regKey}\\DirectX\\Jun2010", "dxsetup", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2005X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2005", "x86 SP1", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2005X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2005", "x64 SP1", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2008X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2008", "x86 SP1", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2008X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2008", "x64 SP1", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2010X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2010", "x86", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2010X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2010", "x64", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2012X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2012", "x86 Update 2", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2012X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2012", "x64 Update 2", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2013X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2013", "x86 Update 1", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2013X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2013", "x64 Update 1", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2015X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2015", "x86", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2015X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2015", "x64", value, RegistryValueKind.DWord);

                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2017X86) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2017", "x86", value, RegistryValueKind.DWord);
                        value = EnvironmentEx.Redist.IsInstalled(EnvironmentEx.Redist.Flags.VC2017X64) ? 1 : 0;
                        Reg.Write($"{regKey}\\vcredist\\2017", "x64", value, RegistryValueKind.DWord);
                        break;
                    }
                }

                const string serviceName = "Steam Client Service";
                if (!Service.Exists(serviceName))
                {
                    try
                    {
                        var binSrvPath = Path.Combine(appDir, "bin\\steamservice.exe");
                        var srvPath    = Path.Combine(serviceDir, "SteamService.exe");
                        File.Copy(binSrvPath, srvPath, true);
                        binSrvPath = Path.ChangeExtension(binSrvPath, ".dll");
                        srvPath    = Path.ChangeExtension(srvPath, ".dll");
                        File.Copy(binSrvPath, srvPath, true);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    var defSrvPath = Path.Combine(defServiceDir, "SteamService.exe");
                    Service.Install(serviceName, serviceName, defSrvPath, "/RunAsService");
                    Service.Start(serviceName);
                }

                var startArgs = Ini.Read("Settings", "StartArguments", iniPath);
                if (!string.IsNullOrWhiteSpace(startArgs))
                {
                    cmdLine = $"{startArgs} {cmdLine}".Trim();
                }

                Helper.ApplicationStart(appPath, cmdLine);

                if (Service.Exists(serviceName))
                {
                    Service.Stop(serviceName);
                    Service.Uninstall(serviceName);
                }

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);

                Helper.RegForwarding(Helper.Options.Exit, regKeys);

                var regSecureMap = new Dictionary <string, Dictionary <string, string> >
                {
                    {
                        "-HKCR\\steam", null
                    }
                };
                Helper.RegSecureOverwrite(regSecureMap);

                if (!Ini.Read("Settings", "ImproveSteamStartTime", false, iniPath))
                {
                    return;
                }
                if (Directory.Exists(scDir))
                {
                    try
                    {
                        Directory.Delete(scDir, true);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                }
                var patternDict = new Dictionary <string, SearchOption>
                {
                    { ".crash", SearchOption.TopDirectoryOnly },
                    { "*.old", SearchOption.TopDirectoryOnly },
                    { "*.log", SearchOption.AllDirectories },
                    { "*.log.last", SearchOption.TopDirectoryOnly },
                    { "ClientRegistry.blob", SearchOption.TopDirectoryOnly }
                };
                foreach (var p in patternDict)
                {
                    try
                    {
                        foreach (var f in Directory.EnumerateFiles(appDir, p.Key, p.Value))
                        {
                            try
                            {
                                File.Delete(f);
                            }
                            catch (Exception ex)
                            {
                                Log.Write(ex);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                }
                var dirs = new[]
                {
                    Path.Combine(appDir, "appcache"),
                    Path.Combine(appDir, "depotcache"),
                    Path.Combine(appDir, "dumps"),
                    Path.Combine(appDir, "htmlcache"),
                    Path.Combine(dataDir, "cache")
                };
                foreach (var d in dirs)
                {
                    try
                    {
                        if (Directory.Exists(d))
                        {
                            Directory.Delete(d, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                }
            }
        }
예제 #16
0
        private async Task <CommandResult> ExecuteAsync(ProcessEx process, CancellationToken cancellationToken = default)
        {
            using var _ = process;
            process.Start();

            // Stdin pipe may need to be canceled early if the process terminates before it finishes
            using var stdInCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            // Register early process termination
            using var cancellation = cancellationToken.Register(() => process.TryKill());

            // Stdin must be closed after it finished to avoid deadlock if the process reads the stream to end
            async Task HandleStdInAsync()
            {
                try
                {
                    // Some streams don't support cancellation, in which case we need a fallback mechanism to avoid deadlocks.
                    // For example, WindowsConsoleStream (from Console.OpenStandardInput()) in particular doesn't support cancellation.
                    // In the following case the operation will terminate but a rogue Task will leak and might cause problems.
                    // This is a non-issue, however, if the user closes the stream at the earliest opportunity.
                    // Otherwise we enter an indeterminate state and tell ourselves we did everything we could to avoid it.
                    await Task.WhenAny(
                        StandardInputPipe.CopyToAsync(process.StdIn, stdInCts.Token),
                        Task.Delay(-1, stdInCts.Token)
                        );
                }
                // Ignore cancellation here, will propagate later
                catch (OperationCanceledException)
                {
                }
                // We want to ignore I/O exceptions that happen when the output stream has already closed.
                // This can happen when the process reads only a portion of stdin and then exits.
                // Unfortunately we can't catch a specific exception for this exact event so we have no choice but to catch all of them.
                catch (IOException)
                {
                }
                finally
                {
                    await process.StdIn.DisposeAsync();
                }
            }

            // Stdout doesn't need to be closed but we do it for good measure
            async Task HandleStdOutAsync()
            {
                try
                {
                    await StandardOutputPipe.CopyFromAsync(process.StdOut, cancellationToken);
                }
                // Ignore cancellation here, will propagate later
                catch (OperationCanceledException)
                {
                }
                finally
                {
                    await process.StdOut.DisposeAsync();
                }
            }

            // Stderr doesn't need to be closed but we do it for good measure
            async Task HandleStdErrAsync()
            {
                try
                {
                    await StandardErrorPipe.CopyFromAsync(process.StdErr, cancellationToken);
                }
                // Ignore cancellation here, will propagate later
                catch (OperationCanceledException)
                {
                }
                finally
                {
                    await process.StdErr.DisposeAsync();
                }
            }

            // Handle pipes in background and in parallel to avoid deadlocks
            var pipingTasks = new[]
            {
                HandleStdInAsync(),
                HandleStdOutAsync(),
                HandleStdErrAsync()
            };

            // Wait until the process terminates or gets killed
            await process.WaitUntilExitAsync();

            // Stop piping stdin if the process has already exited (can happen if not all of stdin is read)
            stdInCts.Cancel();

            // Ensure all pipes are finished
            await Task.WhenAll(pipingTasks);

            // Propagate cancellation to the user
            cancellationToken.ThrowIfCancellationRequested();

            // Validate exit code
            if (process.ExitCode != 0 && Validation.IsZeroExitCodeValidationEnabled())
            {
                throw CommandExecutionException.ExitCodeValidation(TargetFilePath, Arguments, process.ExitCode);
            }

            return(new CommandResult(process.ExitCode, process.StartTime, process.ExitTime));
        }
예제 #17
0
        public async Task <(string, string)> ExecuteWithRunProcessAsTask()
        {
            var result = await ProcessEx.RunAsync(FilePath, Args);

            return(string.Join(Environment.NewLine, result.StandardOutput), string.Join(Environment.NewLine, result.StandardError));
        }
예제 #18
0
        private static void Main()
        {
            Log.AllowLogging();
#if x86
            var curPath64 = PathEx.Combine(PathEx.LocalDir, "NTLite64Portable.exe");
            if (Environment.Is64BitOperatingSystem && File.Exists(curPath64))
            {
                ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                return;
            }

            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\NTLite");
            var updaterPath = PathEx.Combine(appDir, "NTLiteUpdater.exe");
#else
            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\NTLite64");
            var updaterPath = PathEx.Combine(appDir, "NTLiteUpdater64.exe");
#endif
            var appPath = Path.Combine(appDir, "NTLite.exe");

            if (!File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
            {
                return;
            }

            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");

                try
                {
                    var temp = Path.Combine(dataDir, "TEMP");
                    if (!Directory.Exists(temp))
                    {
                        Directory.CreateDirectory(temp);
                    }
                    var cfgPath = Path.Combine(dataDir, "settings.xml");
                    if (File.Exists(cfgPath))
                    {
                        var match = Regex.Match(File.ReadAllText(cfgPath), "<TempFolder>(.+?)</TempFolder>", RegexOptions.IgnoreCase).Groups[1].Value;
                        if (!string.IsNullOrWhiteSpace(match))
                        {
                            Encoding encoding;
                            var      sb = new StringBuilder();
                            using (var sr = new StreamReader(cfgPath))
                            {
                                string line;
                                encoding = sr.CurrentEncoding;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    var m = Regex.Match(line, "<TempFolder>(.+?)</TempFolder>", RegexOptions.IgnoreCase).Groups[1].Value;
                                    if (!string.IsNullOrWhiteSpace(m))
                                    {
                                        var dirName = Path.GetFileName(EnvironmentEx.GetVariableValue("CurDir"));
                                        if (dirName != null)
                                        {
                                            line = line.Replace(m, line.ToLower().Contains($"{dirName.ToLower()}\\data\\temp") ? temp : "%TEMP%");
                                        }
                                    }
                                    sb.AppendLine(line);
                                }
                            }
                            using (var sw = new StreamWriter(cfgPath, false, encoding))
                                sw.Write(sb.ToString());
                        }
                    }
                    else
                    {
                        var content = Resources.DefaultSetting;
                        content = content.Replace("%TEMP%", temp);
                        using (var sw = File.CreateText(cfgPath))
                            sw.Write(content);
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }

                try
                {
                    var srcDir = PathEx.Combine(appDir, "Presets");
                    if (Directory.Exists(srcDir) && !Data.DirIsLink(srcDir))
                    {
                        var destDir = PathEx.Combine(dataDir, "Presets");
                        Data.DirCopy(srcDir, destDir, true, true);
                        Directory.Delete(srcDir, true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }

                var dirMap = new Dictionary <string, string>
                {
                    {
                        PathEx.Combine(appDir, "Presets"),
                        PathEx.Combine(dataDir, "Presets")
                    }
                };

                var fileMap = new Dictionary <string, string>
                {
                    {
                        Path.Combine(appDir, "settings.xml"),
                        Path.Combine(dataDir, "settings.xml")
                    },
                    {
                        Path.Combine(appDir, "settingsUI.xml"),
                        Path.Combine(dataDir, "settingsUI.xml")
                    }
                };

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);
                Helper.FileForwarding(Helper.Options.Start, fileMap, true);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
                Helper.FileForwarding(Helper.Options.Exit, fileMap, true);
            }
        }
예제 #19
0
        private static bool BreakFileLocks(string path, bool force = true)
        {
            if (!PathEx.DirOrFileExists(path))
            {
                return(true);
            }
            var doubleTap = false;

Check:
            var locks = PathEx.GetLocks(path)?.ToArray();

            if (locks?.Any() != true)
            {
                return(true);
            }
            if (doubleTap)
            {
                ProcessEx.Terminate(locks);
                return(true);
            }
            if (!force)
            {
                var lockData    = locks.Select(p => $"ID: {p.Id:d5}; Name: '{p.ProcessName}.exe'").ToArray();
                var information = string.Format(CultureInfo.InvariantCulture, Language.GetText(lockData.Length == 1 ? nameof(en_US.FileLockMsg) : nameof(en_US.FileLocksMsg)), lockData.Join(Environment.NewLine));
                if (MessageBoxEx.Show(information, Resources.GlobalTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                {
                    return(false);
                }
            }
            locks.Where(process => !process.ProcessName.EndsWithEx("64Portable", "Portable64", "Portable")).ForEach(process => ProcessEx.Close(process));
            Thread.Sleep(400);
            doubleTap = true;
            goto Check;
        }
예제 #20
0
 public void Add(ProcessEx Server)
 {
     Servers.Add(Server);
     Server.Exited  += cmd_Exited;
     Server.Started += cmd_Started;
 }
예제 #21
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
#if x86
                var curPath64 = PathEx.Combine(PathEx.LocalDir, "CheatEngine64Portable.exe");
                if (Environment.Is64BitOperatingSystem)
                {
                    if (!File.Exists(curPath64))
                    {
                        return;
                    }
                    ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                    return;
                }
#endif

                var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\CheatEngine");
                var appPath = PathEx.Combine(appDir, "Cheat Engine.exe");

                if (!newInstance)
                {
                    if (!File.Exists(appPath))
                    {
                        return;
                    }
                    ProcessEx.Start(appDir, true);
                    return;
                }

                var updaterPath = PathEx.Combine(appDir, "CheatEngineUpdater.exe");
                if (!File.Exists(updaterPath))
                {
                    return;
                }

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                var dataDir   = PathEx.Combine(PathEx.LocalDir, "Data");
                var tablesDir = PathEx.Combine(dataDir, "My Cheat Tables");
                var dirMap    = new Dictionary <string, string>
                {
                    {
                        "%MyDocuments%\\My Cheat Tables",
                        tablesDir
                    }
                };

                var regKeys = new[]
                {
                    "HKCU\\Software\\Cheat Engine"
                };

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                Helper.RegForwarding(Helper.Options.Start, regKeys);
                Reg.Write(regKeys.First(), "Initial tables dir", tablesDir, RegistryValueKind.String);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), Elevation.IsAdministrator);

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);

                Helper.RegForwarding(Helper.Options.Exit, regKeys);
            }
        }
예제 #22
0
        private void bgwWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Process exeProcess;

            this._fileList.Clear();
            this._fileList.AddRange(
                from p in GlobalData.PresetsManager
                select new PatchInfo(p));
            if (this._fileList.Count == 0)
            {
                return;
            }
            this.ReportProgress(BackgroundFilePatcher.States.PreparingFilesStarted, 0);
            for (int i = 0; i < this._fileList.Count; i++)
            {
                if (this._bgwWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                PatchInfo item = this._fileList[i];
                if (!FileEx.Equals(item.ModdedFile, item.TempFile))
                {
                    File.Copy(item.ModdedFile, item.TempFile, true);
                }
                this.ReportProgress(BackgroundFilePatcher.States.PreparingFiles, BackgroundFilePatcher.CalculateProgress(i, this._fileList.Count));
            }
            BackgroundFilePatcher.BlockLogs();
            if (!Settings.Default.SkipLauncher || string.IsNullOrWhiteSpace(Settings.Default.X2Args))
            {
                BackgroundFilePatcher.RunLauncher();
                this.ReportProgress(BackgroundFilePatcher.States.WaitingForX2ToOpen, 0);
                while (!this._bgwWorker.CancellationPending)
                {
                    exeProcess = ProcessEx.GetExeProcess(Paths.Elsword.ClientExe);
                    Thread.Sleep(1000);
                    if (exeProcess != null)
                    {
                        this.ReportProgress(BackgroundFilePatcher.States.BackupStarted, 0);
                        this.CreateBackup();
                        this.ReportProgress(BackgroundFilePatcher.States.PatchingStarted, 0);
                        this.PatchFiles();
                        (new DirectoryInfo(Paths.Main.Cache)).Empty();
                        this.ReportProgress(BackgroundFilePatcher.States.WaitingForX2ToClose, 100);
                        exeProcess.WaitForExit();
                        this.ReportProgress(BackgroundFilePatcher.States.RestoringBackupStarted, 0);
                        this.RestoreBackup();
                        BackgroundFilePatcher.ClearRegistry("Software\\ElswordINT");
                        BackgroundFilePatcher.ClearRegistry("Software\\Nexon\\Elsword\\PatcherOption");
                        this.ReportProgress(BackgroundFilePatcher.States.Done, 100);
                        return;
                    }
                }
                e.Cancel = true;
                return;
            }
            else
            {
                exeProcess = Paths.Elsword.RunClient();
            }
            this.ReportProgress(BackgroundFilePatcher.States.BackupStarted, 0);
            this.CreateBackup();
            this.ReportProgress(BackgroundFilePatcher.States.PatchingStarted, 0);
            this.PatchFiles();
            (new DirectoryInfo(Paths.Main.Cache)).Empty();
            this.ReportProgress(BackgroundFilePatcher.States.WaitingForX2ToClose, 100);
            exeProcess.WaitForExit();
            this.ReportProgress(BackgroundFilePatcher.States.RestoringBackupStarted, 0);
            this.RestoreBackup();
            BackgroundFilePatcher.ClearRegistry("Software\\ElswordINT");
            BackgroundFilePatcher.ClearRegistry("Software\\Nexon\\Elsword\\PatcherOption");
            this.ReportProgress(BackgroundFilePatcher.States.Done, 100);
        }
예제 #23
0
 /// <summary>
 ///     Extracts all the files in the specified archive to the specified directory
 ///     on the file system.
 /// </summary>
 /// <param name="srcFile">
 ///     The path of the archive to extract.
 /// </param>
 /// <param name="destDir">
 ///     The path to the directory to place the extracted files in.
 /// </param>
 /// <param name="windowStyle">
 ///     The window state to use when the process is started.
 /// </param>
 /// <param name="dispose">
 ///     <see langword="true"/> to release all resources used by the
 ///     <see cref="Process"/> component; otherwise, <see langword="false"/>.
 /// </param>
 public Process Extract(string srcFile, string destDir, ProcessWindowStyle windowStyle = ProcessWindowStyle.Minimized, bool dispose = false) =>
 !File.Exists(ExtractExePath) ? null : ProcessEx.Start(ExtractExePath, ExtractArgs.FormatCurrent(srcFile, destDir), false, windowStyle, dispose);
예제 #24
0
        private void ExtractDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            var updDir = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempDirName()}");

            try
            {
                if (_transfer?.FilePath == null || !File.Exists(_transfer.FilePath))
                {
                    return;
                }
                var helperPath = PathEx.Combine(_tmpDir, "iu.exe");
                if (!File.Exists(helperPath))
                {
                    throw new FileNotFoundException();
                }
                if (!Directory.Exists(updDir))
                {
                    Directory.CreateDirectory(updDir);
                }
                using (var p = ProcessEx.Start(helperPath, string.Format(Resources.Extract, _transfer.FilePath, updDir), Elevation.IsAdministrator, ProcessWindowStyle.Minimized, false))
                    if (p?.HasExited == false)
                    {
                        p.WaitForExit();
                    }
                Thread.Sleep(1500);
                var innerDir = Path.Combine(updDir, "{app}");
                var updFiles = Directory.GetFiles(innerDir, "*", SearchOption.TopDirectoryOnly);
                if (updFiles.Length == 0)
                {
                    throw new ArgumentNullException(nameof(updFiles));
                }
                var appPath = Directory.EnumerateFiles(updDir, $"*{Resources.AppName}.exe", SearchOption.AllDirectories).FirstOrDefault();
                if (string.IsNullOrEmpty(appPath))
                {
                    throw new ArgumentNullException(nameof(appPath));
                }
                var curFiles = Directory.EnumerateFiles(PathEx.LocalDir, "*", SearchOption.AllDirectories).Where(x => !Resources.WhiteList.ContainsEx(Path.GetFileName(x)));
                foreach (var file in curFiles)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                        try
                        {
                            File.Move(file, $"{file}.{{{Path.GetDirectoryName(updDir)}}}");
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                    }
                }
                Data.DirCopy(innerDir, PathEx.LocalDir, true, true);
                if (Directory.Exists(updDir))
                {
                    Directory.Delete(updDir, true);
                }
                if (File.Exists(_appPath))
                {
                    File.SetLastWriteTime(_appPath, DateTime.Now);
                }
                e.Result = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                e.Result = false;
                Data.ForceDelete(updDir);
            }
        }
예제 #25
0
        // Rather than using [Theory] to pass each of the different values for 'template',
        // it's important to distribute the SPA template tests over different test classes
        // so they can be run in parallel. Xunit doesn't parallelize within a test class.
        protected async Task SpaTemplateImplAsync(
            string key,
            string template,
            bool useLocalDb = false,
            bool usesAuth   = false)
        {
            Project = await ProjectFactory.GetOrCreateProject(key, Output);

            using var createResult = await Project.RunDotNetNewAsync(template, auth : usesAuth? "Individual" : null, language : null, useLocalDb);

            Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", Project, createResult));

            // We shouldn't have to do the NPM restore in tests because it should happen
            // automatically at build time, but by doing it up front we can avoid having
            // multiple NPM installs run concurrently which otherwise causes errors when
            // tests run in parallel.
            var clientAppSubdirPath = Path.Combine(Project.TemplateOutputDir, "ClientApp");

            ValidatePackageJson(clientAppSubdirPath);

            var projectFileContents = ReadFile(Project.TemplateOutputDir, $"{Project.ProjectName}.csproj");

            if (usesAuth && !useLocalDb)
            {
                Assert.Contains(".db", projectFileContents);
            }

            using var npmRestoreResult = await Project.RestoreWithRetryAsync(Output, clientAppSubdirPath);

            Assert.True(0 == npmRestoreResult.ExitCode, ErrorMessages.GetFailedProcessMessage("npm restore", Project, npmRestoreResult));

            using var lintResult = ProcessEx.RunViaShell(Output, clientAppSubdirPath, "npm run lint");
            Assert.True(0 == lintResult.ExitCode, ErrorMessages.GetFailedProcessMessage("npm run lint", Project, lintResult));

            // The default behavior of angular tests is watch mode, which leaves the test process open after it finishes, which leads to delays/hangs.
            var testcommand = "npm run test" + template == "angular" ? "-- --watch=false" : "";

            using var testResult = ProcessEx.RunViaShell(Output, clientAppSubdirPath, testcommand);
            Assert.True(0 == testResult.ExitCode, ErrorMessages.GetFailedProcessMessage("npm run test", Project, testResult));

            using var publishResult = await Project.RunDotNetPublishAsync();

            Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, publishResult));

            // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release
            // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build
            // later, while the opposite is not true.

            using var buildResult = await Project.RunDotNetBuildAsync();

            Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, buildResult));

            // localdb is not installed on the CI machines, so skip it.
            var shouldVisitFetchData = !(useLocalDb && Project.IsCIEnvironment);

            if (usesAuth)
            {
                using var migrationsResult = await Project.RunDotNetEfCreateMigrationAsync(template);

                Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", Project, migrationsResult));
                Project.AssertEmptyMigration(template);

                if (shouldVisitFetchData)
                {
                    using var dbUpdateResult = await Project.RunDotNetEfUpdateDatabaseAsync();

                    Assert.True(0 == dbUpdateResult.ExitCode, ErrorMessages.GetFailedProcessMessage("update database", Project, dbUpdateResult));
                }
            }

            if (template == "react" || template == "reactredux")
            {
                await CleanupReactClientAppBuildFolder(clientAppSubdirPath);
            }

            using (var aspNetProcess = Project.StartBuiltProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process));

                await WarmUpServer(aspNetProcess);

                await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");

                if (BrowserFixture.IsHostAutomationSupported())
                {
                    var(browser, logs) = await BrowserFixture.GetOrCreateBrowserAsync(Output, $"{Project.ProjectName}.build");

                    aspNetProcess.VisitInBrowser(browser);
                    TestBasicNavigation(visitFetchData: shouldVisitFetchData, usesAuth, browser, logs);
                }
                else
                {
                    BrowserFixture.EnforceSupportedConfigurations();
                }
            }

            if (usesAuth)
            {
                UpdatePublishedSettings();
            }

            using (var aspNetProcess = Project.StartPublishedProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", Project, aspNetProcess.Process));

                await WarmUpServer(aspNetProcess);

                await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");

                if (BrowserFixture.IsHostAutomationSupported())
                {
                    var(browser, logs) = await BrowserFixture.GetOrCreateBrowserAsync(Output, $"{Project.ProjectName}.publish");

                    aspNetProcess.VisitInBrowser(browser);
                    TestBasicNavigation(visitFetchData: shouldVisitFetchData, usesAuth, browser, logs);
                }
                else
                {
                    BrowserFixture.EnforceSupportedConfigurations();
                }
            }
        }
예제 #26
0
        /// <summary>
        /// Renders a file to WAV using VGMPlay and reads it into a PCM16Audio object.
        /// </summary>
        /// <param name="filename">The path of the file to read</param>
        /// <param name="preferredSampleRate">The sample rate to render the VGM at</param>
        /// <returns>A PCM16Audio, which may or may not be looping</returns>
        public async Task <PCM16Audio> ReadFileAsync(string filename)
        {
            if (!File.Exists(ExePath))
            {
                throw new AudioImporterException("VGMPlay not found at path: " + ExePath);
            }
            if (filename.Contains('"'))
            {
                throw new AudioImporterException("File paths with double quote marks (\") are not supported");
            }

            try {
                string tmpDir = Path.Combine(Path.GetTempPath(), "LoopingaudioConverter-" + Guid.NewGuid());
                Directory.CreateDirectory(tmpDir);

                string inFile = Path.Combine(tmpDir, "audio" + Path.GetExtension(filename));
                File.Copy(filename, inFile);
                using (var sw = new StreamWriter(new FileStream(Path.Combine(tmpDir, "VGMPlay.ini"), FileMode.Create, FileAccess.Write))) {
                    sw.WriteLine("[General]");
                    if (SampleRate != null)
                    {
                        sw.WriteLine("SampleRate = " + SampleRate);
                    }
                    sw.WriteLine("FadeTime = 500");
                    sw.WriteLine("LogSound = 1");
                    sw.WriteLine("MaxLoops = 0x01");
                }

                ProcessStartInfo psi = new ProcessStartInfo {
                    FileName         = Path.GetFullPath(ExePath),
                    WorkingDirectory = tmpDir,
                    UseShellExecute  = false,
                    CreateNoWindow   = true,
                    Arguments        = inFile
                };
                var pr = await ProcessEx.RunAsync(psi);

                var data = PCM16Factory.FromFile(Path.Combine(tmpDir, "audio.wav"), true);
                Directory.Delete(tmpDir, true);

                // Read loop points from file
                using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    using (var gz = new GZipStream(fs, CompressionMode.Decompress))
                        using (var br = new BinaryReader(gz)) {
                            int tag = br.ReadInt32();
                            if (tag == 0x56676D20)
                            {
                                throw new Exception("Machine is big-endian");
                            }
                            if (tag != 0x206D6756)
                            {
                                throw new Exception($"File not in Vgm format ({tag.ToString("X8")})");
                            }

                            for (int i = 0; i < 5; i++)
                            {
                                br.ReadInt32();
                            }

                            int samples = br.ReadInt32();
                            br.ReadInt32();
                            int loopSamples = br.ReadInt32();

                            double sampleRateRatio = data.SampleRate / 44100.0;
                            samples     = (int)(samples * sampleRateRatio);
                            loopSamples = (int)(loopSamples * sampleRateRatio);

                            if (loopSamples == 0)
                            {
                                data.NonLooping = true;
                            }
                            else
                            {
                                data.Looping   = true;
                                data.LoopStart = samples - loopSamples;
                                data.LoopEnd   = samples;
                            }
                        }

                return(data);
            } catch (Exception e) {
                Console.Error.WriteLine(e.GetType());
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine(e.StackTrace);
                throw new AudioImporterException("Could not read output of VGMPlay: " + e.Message);
            }
        }
예제 #27
0
        /// <summary>
        /// Injects all processes with the r77 DLL using reflective DLL injection.
        /// <para>Both Helper32.exe and Helper64.exe are invoked using the "-inject -all" commandline.</para>
        /// </summary>
        /// <returns>
        /// An enumerable of <see cref="LogMessage" /> entries to be displayed in the log view.
        /// </returns>
        public static IEnumerable <LogMessage> InjectAll()
        {
            int injectedCount = GetInjectedCount();

            string helper32Path = GetFilePath("Helper32.exe", out LogMessage helper32PathLogMessage);

            if (helper32Path == null)
            {
                yield return(helper32PathLogMessage);

                yield break;
            }

            string helper64Path = null;

            if (Environment.Is64BitOperatingSystem)
            {
                helper64Path = GetFilePath("Helper64.exe", out LogMessage helper64PathLogMessage);
                if (helper64Path == null)
                {
                    yield return(helper64PathLogMessage);

                    yield break;
                }
            }


            string dll32Path = GetFilePath("r77-x86.dll", out LogMessage dll32PathLogMessage);

            if (dll32Path == null)
            {
                yield return(dll32PathLogMessage);

                yield break;
            }

            string dll64Path = null;

            if (Environment.Is64BitOperatingSystem)
            {
                dll64Path = GetFilePath("r77-x64.dll", out LogMessage dll64PathLogMessage);
                if (dll64Path == null)
                {
                    yield return(dll64PathLogMessage);

                    yield break;
                }
            }

            if (ProcessEx.Execute(helper32Path, "-inject -all \"" + dll32Path + "\"") != 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Error,
                                 new LogFileItem(Path.GetFileName(helper32Path)),
                                 new LogTextItem("returned an error code.")
                             ));
            }

            if (Environment.Is64BitOperatingSystem && ProcessEx.Execute(helper64Path, "-inject -all \"" + dll64Path + "\"") != 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Error,
                                 new LogFileItem(Path.GetFileName(helper64Path)),
                                 new LogTextItem("returned an error code.")
                             ));
            }

            int newInjectedCount = GetInjectedCount();

            if (newInjectedCount == injectedCount)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Information,
                                 new LogTextItem("No processes were injected")
                             ));
            }
            else if (newInjectedCount > injectedCount)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Information,
                                 new LogTextItem("Injected " + (newInjectedCount - injectedCount) + " processes.")
                             ));
            }
        }
예제 #28
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appDir = PathEx.Combine(PathEx.LocalDir, "App\\Defraggler");
                if (!Directory.Exists(appDir))
                {
                    return;
                }

                var appPath     = Path.Combine(appDir, "Defraggler.exe");
                var updaterPath = Path.Combine(appDir, "DefragglerUpdater.exe");
                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || !File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
                {
                    return;
                }

                var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");
                var fileMap = new Dictionary <string, string>
                {
                    {
                        PathEx.Combine(appDir, "defraggler.ini"),
                        PathEx.Combine(dataDir, "defraggler.ini")
                    },
                    {
                        PathEx.Combine(appDir, "statistics.bin"),
                        PathEx.Combine(dataDir, "statistics.bin")
                    }
                };

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                Helper.FileForwarding(Helper.Options.Start, fileMap);

                var portableDat = Path.Combine(appDir, "portable.dat");
                if (!File.Exists(portableDat))
                {
                    File.WriteAllText(portableDat, @"#PORTABLE#");
                }

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.FileForwarding(Helper.Options.Exit, fileMap);
            }
        }
예제 #29
0
        /// <summary>
        /// Detaches r77 from all running processes.
        /// <para>Both Helper32.exe and Helper64.exe are invoked using the "-detach -all" commandline.</para>
        /// </summary>
        /// <returns>
        /// An enumerable of <see cref="LogMessage" /> entries to be displayed in the log view.
        /// </returns>
        public static IEnumerable <LogMessage> DetachAll()
        {
            int injectedCount = GetInjectedCount();

            if (injectedCount == 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Information,
                                 new LogTextItem("No processes are injected.")
                             ));

                yield break;
            }

            string helper32Path = GetFilePath("Helper32.exe", out LogMessage helper32PathLogMessage);

            if (helper32Path == null)
            {
                yield return(helper32PathLogMessage);

                yield break;
            }

            string helper64Path = null;

            if (Environment.Is64BitOperatingSystem)
            {
                helper64Path = GetFilePath("Helper64.exe", out LogMessage helper64PathLogMessage);
                if (helper64Path == null)
                {
                    yield return(helper64PathLogMessage);

                    yield break;
                }
            }

            if (ProcessEx.Execute(helper32Path, "-detach -all") != 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Error,
                                 new LogFileItem(Path.GetFileName(helper32Path)),
                                 new LogTextItem("returned an error code.")
                             ));
            }

            if (Environment.Is64BitOperatingSystem && ProcessEx.Execute(helper64Path, "-detach -all") != 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Error,
                                 new LogFileItem(Path.GetFileName(helper64Path)),
                                 new LogTextItem("returned an error code.")
                             ));
            }

            int newInjectedCount = GetInjectedCount();

            if (newInjectedCount < injectedCount)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Information,
                                 new LogTextItem("Detached from " + (injectedCount - newInjectedCount) + " processes.")
                             ));
            }

            if (newInjectedCount > 0)
            {
                yield return(new LogMessage
                             (
                                 LogMessageType.Warning,
                                 new LogTextItem(newInjectedCount + " processes could not be detached.")
                             ));
            }
        }
예제 #30
0
        private static void Main()
        {
            Log.AllowLogging();

#if x86
            var curPath64 = PathEx.Combine(PathEx.LocalDir, "WinRAR64Portable.exe");
            if (Environment.Is64BitOperatingSystem && File.Exists(curPath64))
            {
                ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                return;
            }
            var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\winrar");
            var updPath = PathEx.Combine(appDir, "WinRARUpdater.exe");
#else
            var appDir  = PathEx.Combine(PathEx.LocalDir, "App\\winrar-x64");
            var updPath = PathEx.Combine(appDir, "WinRARUpdater64.exe");
#endif

            var appPath = PathEx.Combine(appDir, "WinRAR.exe");
            var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");
            var iniPath = Path.ChangeExtension(PathEx.LocalPath, ".ini");

            if (!File.Exists(iniPath))
            {
                Ini.SetFile(iniPath);
                Ini.Write("ContextMenu", "EntriesAllowed", false);
                Ini.Write("Associations", "FileTypes", "001,7z,ace,arj,bz2,bzip2,cab,gz,gzip,iso,lha,lzh,lzma,rar,tar,taz,tbz,tbz2,tgz,tpz,txz,xy,z,zip");
                Ini.WriteAll();
            }
            else
            {
                Ini.SetFile(iniPath);
            }

            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance && !Environment.CommandLine.ContainsEx("{5C1A7995-36C7-4346-B549-D6392EFC86E4}"))
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine(false));
                    return;
                }

                var entries = Ini.Read("ContextMenu", "EntriesAllowed", false);
                RegistryHelper(appDir, entries);

                var dirMap = new Dictionary <string, string>
                {
                    {
                        "%AppData%\\WinRAR",
                        PathEx.Combine(dataDir, "WinRAR")
                    }
                };

                var fileMap = new Dictionary <string, string>
                {
                    {
                        PathEx.Combine(appDir, "WinRAR.ini"),
                        PathEx.Combine(dataDir, "WinRAR.ini")
                    }
                };

                Helper.ApplicationStart(updPath, "/archlock /silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);
                Helper.FileForwarding(Helper.Options.Start, fileMap, entries);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
                Helper.FileForwarding(Helper.Options.Exit, fileMap, entries);

                var regKeys = new[]
                {
                    "HKCR\\WinRAR",
                    "HKCR\\WinRAR.REV",
                    "HKCR\\WinRAR.ZIP",
                    "HKCU\\Software\\Classes\\WinRAR",
                    "HKCU\\Software\\Classes\\WinRAR.REV",
                    "HKCU\\Software\\Classes\\WinRAR.ZIP",
                    "HKCU\\Software\\WinRAR"
                };

                if (!entries && regKeys.Any(Reg.SubKeyExists))
                {
                    Elevation.RestartAsAdministrator("{CFFB1200-8B38-451D-80A0-BE187E64EC61}");
                }
            }
        }