Пример #1
0
 private static void Main()
 {
     Log.AllowLogging();
     MessageBoxEx.TopMost = true;
     if (Process.GetProcessesByName(Resources.AppName).Length > 0)
     {
         MessageBoxEx.Show(Resources.Msg_Warn_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
         Environment.Exit(1);
     }
     using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
     {
         if (!newInstance)
         {
             return;
         }
         if (!Elevation.WritableLocation())
         {
             Elevation.RestartAsAdministrator();
         }
         Ini.SetFile(Path.ChangeExtension(PathEx.LocalPath, ".ini"));
         if ((DateTime.Now - Ini.Read("History", "LastCheck", DateTime.MinValue)).Days < 7)
         {
             return;
         }
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
     }
 }
Пример #2
0
        public static void Initialize()
        {
            using (new Mutex(true, ProcessEx.CurrentName, out var newInstance))
            {
#if x86
                if (Environment.Is64BitOperatingSystem)
                {
                    var curPath64 = PathEx.Combine(PathEx.LocalDir, $"{ProcessEx.CurrentName}64.exe");
                    if (File.Exists(curPath64))
                    {
                        ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                        return;
                    }
                }
#endif

                if (!string.IsNullOrWhiteSpace(Attributes.DefIni) && !string.IsNullOrWhiteSpace(Attributes.ConfigPath) && !File.Exists(Attributes.ConfigPath))
                {
                    try
                    {
                        File.WriteAllText(Attributes.ConfigPath, Attributes.DefIni);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Elevation.RestartAsAdministrator();
                    }
                }
Пример #3
0
 private static void Main()
 {
     Log.AllowLogging();
     using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
     {
         if (!newInstance)
         {
             return;
         }
         if (!Elevation.WritableLocation())
         {
             Elevation.RestartAsAdministrator();
         }
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         try
         {
             Application.Run(new MainForm());
         }
         catch (Exception ex)
         {
             Log.Write(ex);
         }
     }
 }
Пример #4
0
        internal static bool AppsSuiteIsHealthy(bool repair = true)
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator();
            }
            while (true)
            {
                try
                {
                    if (!File.Exists(CorePaths.AppsLauncher) ||
                        !File.Exists(CorePaths.AppsSuiteUpdater) ||
                        !File.Exists(CorePaths.FileArchiver))
                    {
                        throw new FileNotFoundException();
                    }
                }
                catch (FileNotFoundException ex)
                {
                    Log.Write(ex);
                    if (!repair)
                    {
                        return(false);
                    }
                    Repair(ActionGuid.RepairAppsSuite, true);
                }

                try
                {
                    foreach (var dir in CorePaths.AppDirs)
                    {
                        if (!Directory.Exists(dir))
                        {
                            throw new PathNotFoundException(dir);
                        }
                    }
                }
                catch (PathNotFoundException ex)
                {
                    Log.Write(ex);
                    if (!repair)
                    {
                        return(false);
                    }
                    Repair(ActionGuid.RepairDirs, false);
                }

                if (!repair)
                {
                    return(true);
                }
                repair = false;
            }
        }
Пример #5
0
        private static bool RequirementsAvailable()
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator();
            }
            string[] sArray =
            {
                "Apps\\.free\\",
                "Apps\\.repack\\",
                "Apps\\.share\\",
                "Assets\\images.dat",
#if x86
                "Binaries\\AppsDownloader.exe",
#else
                "Binaries\\AppsDownloader64.exe",
#endif
                "Binaries\\Updater.exe"
            };
            foreach (var s in sArray)
            {
                var path = PathEx.Combine(PathEx.LocalDir, s);
                if (s.EndsWith("\\"))
                {
                    try
                    {
                        if (!Directory.Exists(path))
                        {
                            RepairAppsSuiteHandler();
                        }
                        if (!Directory.Exists(path))
                        {
                            throw new PathNotFoundException(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                        return(false);
                    }
                }
                else
                {
                    if (!File.Exists(path))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #6
0
 private static bool RequirementsAvailable()
 {
     if (!Elevation.WritableLocation())
     {
         Elevation.RestartAsAdministrator();
     }
     string[] rArray =
     {
         "..\\Assets\\images.dat",
         "Helper\\7z\\7z.dll",
         "Helper\\7z\\7zG.exe",
         "Helper\\7z\\x64\\7z.dll",
         "Helper\\7z\\x64\\7zG.exe"
     };
     return(rArray.Select(s => PathEx.Combine(PathEx.LocalDir, s)).All(File.Exists));
 }
Пример #7
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var regKeys = new[]
                {
                    "HKCR\\Discord"
                };

                if (Elevation.IsAdministrator && Environment.CommandLine.ContainsEx("{E429830E-A5A1-4FA0-9D5F-B21964F4698E}"))
                {
                    goto ClearRegistry;
                }

                var updaterPath = PathEx.Combine(PathEx.LocalDir, "App\\Discord\\Update.exe");
                if (!File.Exists(updaterPath) || ProcessEx.IsRunning("Discord"))
                {
                    return;
                }

                var anyKeyExists = regKeys.Any(Reg.SubKeyExists);

                var dirMap = new Dictionary <string, string>
                {
                    {
                        "%LocalAppData%\\Discord",
                        "%CurDir%\\App\\Discord"
                    },
                    {
                        "%LocalAppData%\\SquirrelTemp",
                        "%CurDir%\\App\\Discord\\packages\\SquirrelTemp"
                    },
                    {
                        "%AppData%\\discord",
                        "%CurDir%\\Data\\AppData"
                    }
                };

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

                Helper.ApplicationStart(updaterPath, "--processStart Discord.exe", false);

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

                if (anyKeyExists)
                {
                    return;
                }

ClearRegistry:
                foreach (var key in regKeys)
                {
                    Reg.RemoveSubKey(key);
                }
                if (!Elevation.IsAdministrator && regKeys.Any(Reg.SubKeyExists))
                {
                    Elevation.RestartAsAdministrator("{E429830E-A5A1-4FA0-9D5F-B21964F4698E}");
                }
            }
        }
Пример #8
0
        internal static bool AppsSuiteIsHealthy(bool repair = true)
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator();
            }

            VersionValidation();

            while (true)
            {
                try
                {
                    if (!File.Exists(CorePaths.AppsDownloader) ||
                        !File.Exists(CorePaths.AppsSuiteUpdater) ||
                        !File.Exists(CorePaths.FileArchiver))
                    {
                        throw new FileNotFoundException();
                    }
                }
                catch (FileNotFoundException ex)
                {
                    Log.Write(ex);
                    if (!repair)
                    {
                        return(false);
                    }
                    RepairAppsSuite();
                }

                try
                {
                    foreach (var dir in CorePaths.AppDirs.Where(dir => !Directory.Exists(dir)))
                    {
                        throw new PathNotFoundException(dir);
                    }
                }
                catch (PathNotFoundException ex)
                {
                    Log.Write(ex);
                    if (!repair)
                    {
                        return(false);
                    }
                    RepairAppsSuiteDirs();
                }

                try
                {
                    var envDir = EnvironmentEx.GetVariableValue(Settings.EnvironmentVariable);
                    if (!Settings.DeveloperVersion && !string.IsNullOrWhiteSpace(envDir) && !envDir.EqualsEx(PathEx.LocalDir))
                    {
                        throw new ArgumentInvalidException(nameof(envDir));
                    }
                }
                catch (ArgumentInvalidException ex)
                {
                    Log.Write(ex);
                    if (!repair)
                    {
                        return(false);
                    }
                    RepairEnvironmentVariable();
                }

                if (!repair)
                {
                    return(true);
                }
                repair = false;
            }
        }
Пример #9
0
        internal static void RepairAppsSuiteDirs()
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
            }

            foreach (var dirs in new[]
            {
                CorePaths.AppDirs,
                CorePaths.UserDirs
            })
            {
                foreach (var dir in dirs)
                {
                    if (!DirectoryEx.Create(dir))
                    {
                        Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
                    }
                }
            }

            var iniMap = new[]
            {
                new[]
                {
                    CorePaths.AppDirs.First(),
                    "IconResource=..\\Assets\\FolderIcons.dll,3"
                },
                new[]
                {
                    CorePaths.AppDirs.Second(),
                    "LocalizedResourceName=\"Port-Able\" - Freeware",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,4"
                },
                new[]
                {
                    CorePaths.AppDirs.Third(),
                    "LocalizedResourceName=\"PortableApps\" - Repacks",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,2"
                },
                new[]
                {
                    CorePaths.AppDirs.Last(),
                    "LocalizedResourceName=\"Custom\" - Shareware",
                    "IconResource=..\\..\\Assets\\FolderIcons.dll,1"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Assets"),
                    "IconResource=FolderIcons.dll,5"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Binaries"),
                    "IconResource=..\\Assets\\FolderIcons.dll,5"
                },
                new[]
                {
                    CorePaths.UserDirs.First(),
                    "LocalizedResourceName=Profile",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,117",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-235"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Documents", ".cache"),
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,112"
                },
                new[]
                {
                    CorePaths.UserDirs.Second(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21770",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-112",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-235"
                },
                new[]
                {
                    CorePaths.UserDirs.Third(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21790",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-108",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-237",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12689"
                },
                new[]
                {
                    CorePaths.UserDirs.Fourth(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21779",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-113",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-236",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12688"
                },
                new[]
                {
                    CorePaths.UserDirs.Last(),
                    "LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-21791",
                    "IconResource=%SystemRoot%\\system32\\imageres.dll,-189",
                    "IconFile=%SystemRoot%\\system32\\shell32.dll",
                    "IconIndex=-238",
                    "InfoTip=@%SystemRoot%\\system32\\shell32.dll,-12690"
                },
                new[]
                {
                    PathEx.Combine(PathEx.LocalDir, "Help"),
                    "IconResource=..\\Assets\\FolderIcons.dll,4"
                }
            };

            for (var i = 0; i < iniMap.Length; i++)
            {
                var array = iniMap[i];
                var dir   = array.FirstOrDefault();
                if (!PathEx.IsValidPath(dir) || i >= iniMap.Length - 2 && !Directory.Exists(dir))
                {
                    continue;
                }
                if (!Elevation.WritableLocation(dir))
                {
                    Elevation.RestartAsAdministrator(ActionGuid.RepairDirs);
                }
                var path = PathEx.Combine(dir, "desktop.ini");
                foreach (var str in array.Skip(1))
                {
                    var ent = str?.Split('=');
                    if (ent?.Length != 2)
                    {
                        continue;
                    }
                    var key = ent.FirstOrDefault();
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    var val = ent.LastOrDefault();
                    if (string.IsNullOrEmpty(val))
                    {
                        continue;
                    }
                    Ini.WriteDirect(".ShellClassInfo", key, val, path);
                }
                FileEx.SetAttributes(path, FileAttributes.System | FileAttributes.Hidden);
                DirectoryEx.SetAttributes(dir, FileAttributes.ReadOnly);
            }
        }
Пример #10
0
        private static bool RequirementsAvailable()
        {
            if (!Elevation.WritableLocation())
            {
                Elevation.RestartAsAdministrator();
            }
            const string repairAppsSuite  = "{48FDE635-60E6-41B5-8F9D-674E9F535AC7}";
            const string disableInterface = "{9AB50CEB-3D99-404E-BD31-4E635C09AF0F}";

            string[] sArray =
            {
                "..\\Apps\\.free\\",
                "..\\Apps\\.repack\\",
                "..\\Apps\\.share\\",
                "..\\Assets\\images.dat",
                "Updater.exe",
#if x86
                "Helper\\7z\\7z.dll",
                "Helper\\7z\\7zG.exe",
                "..\\AppsLauncher.exe",
#else
                "Helper\\7z\\x64\\7z.dll",
                "Helper\\7z\\x64\\7zG.exe",
                "..\\AppsLauncher64.exe"
#endif
            };
            foreach (var s in sArray)
            {
                var path = PathEx.Combine(PathEx.LocalDir, s);
                if (s.EndsWith("\\"))
                {
                    try
                    {
                        if (!Directory.Exists(path))
                        {
                            var psi = new ProcessStartInfo
                            {
                                Arguments = $"{repairAppsSuite} {disableInterface}",
#if x86
                                FileName = "%CurDir%\\..\\AppsLauncher.exe"
#else
                                FileName = "%CurDir%\\..\\AppsLauncher64.exe"
#endif
                            };
                            ProcessEx.Start(psi)?.WaitForExit();
                        }
                        if (!Directory.Exists(path))
                        {
                            throw new PathNotFoundException(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                        return(false);
                    }
                }
                else
                {
                    if (!File.Exists(path))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #11
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;
                        }
                    }
                }
            }
        }
Пример #12
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}");
                }
            }
        }
        /// <summary>
        ///     Enables/disables the specified redistributable packages.
        /// </summary>
        /// <param name="option">
        ///     The option that determines whether the redistributable packages will be
        ///     enabled or disabled.
        /// </param>
        /// <param name="versions">
        ///     The redistributable package versions to handle.
        /// </param>
        public static void Handler(PortalizerActions option, params EnvironmentEx.RedistFlags[] versions)
        {
            if (versions == null)
            {
                return;
            }
            var dict = new Dictionary <EnvironmentEx.RedistFlags, Dictionary <int, List <int> > >();

            foreach (var version in versions)
            {
                try
                {
                    var data = Enum.GetName(typeof(EnvironmentEx.RedistFlags), version)?.Split('X')
                               .Select(s => new string(s.Where(char.IsDigit).ToArray())).ToArray();
                    if (data == null)
                    {
                        throw new ArgumentNullException(nameof(data));
                    }
                    if (data.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException(nameof(data));
                    }
                    var year = Convert.ToInt32(data.First());
                    if (year < 2005)
                    {
                        throw new ArgumentOutOfRangeException(nameof(year));
                    }
                    var arch = Convert.ToInt32(data.Last());
                    if (arch != 64 && arch != 86)
                    {
                        throw new ArgumentOutOfRangeException(nameof(arch));
                    }
                    if (!dict.ContainsKey(version))
                    {
                        dict.Add(version, new Dictionary <int, List <int> >());
                    }
                    if (!dict[version].ContainsKey(year))
                    {
                        dict[version].Add(year, new List <int>());
                    }
                    dict[version][year].Add(arch);
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
            }
            foreach (var data in dict)
            {
                var version = data.Key;
                if (version == EnvironmentEx.RedistFlags.VC2005X86 ||
                    version == EnvironmentEx.RedistFlags.VC2005X64)
                {
                    continue;
                }
                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");
                        string args;
                        switch (option)
                        {
                        case PortalizerActions.Disable:
                            if (Ini.ReadDirect("Redist", version.ToString(), iniPath).EqualsEx("True"))
                            {
                                return;
                            }
                            switch (year)
                            {
                            case 2008:
                                args = "/qu";
                                break;

                            case 2010:
                            case 2012:
                                args = "/uninstall /q /norestart";
                                break;

                            default:
                                args = "/uninstall /quiet /norestart";
                                break;
                            }
                            using (var p = ProcessEx.Start(path, args, 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;
                            }
                            if (!Ini.ReadDirect("Redist", version.ToString(), iniPath).EqualsEx("True", "False"))
                            {
                                MessageBoxEx.TopMost = true;
                                MessageBoxEx.ButtonText.OverrideEnabled = true;
                                MessageBoxEx.ButtonText.Yes             = Strings.RedistRequestButtonYes;
                                MessageBoxEx.ButtonText.No     = Strings.RedistRequestButtonNo;
                                MessageBoxEx.ButtonText.Cancel = Strings.RedistRequestButtonCancel;
                                var msg    = string.Format(Strings.RedistRequestMessage, year, arch);
                                var result = MessageBoxEx.Show(msg, AssemblyInfo.Title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                if (result == DialogResult.Cancel)
                                {
                                    Handler(PortalizerActions.Disable, 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(string.Format(Strings.RedistProgressNotify, year, arch), AssemblyInfo.Title, NotifyBoxStartPosition.Center);
                            switch (year)
                            {
                            case 2008:
                                args = "/q";
                                break;

                            case 2010:
                            case 2012:
                                args = "/q /norestart";
                                break;

                            default:
                                args = "/install /quiet /norestart";
                                break;
                            }
                            using (var p = ProcessEx.Start(path, args, Elevation.IsAdministrator, false))
                                if (p?.HasExited == false)
                                {
                                    p.WaitForExit();
                                }
                            notifyBox.Close();
                            if (!EnvironmentEx.Redist.IsInstalled(version))
                            {
                                Environment.ExitCode = 1;
                                Environment.Exit(Environment.ExitCode);
                            }
                            break;
                        }
                    }
                }
            }
        }
Пример #14
0
        private static void Main()
        {
            Log.AllowLogging();

            var ixiPath = PathEx.Combine(PathEx.LocalDir, $"App\\{ProcessEx.CurrentName}.ixi");
            var iniPath = PathEx.Combine(PathEx.LocalDir, $"App\\{ProcessEx.CurrentName}.ini");

            if (!File.Exists(iniPath))
            {
                return;
            }
            Ini.SetFile(iniPath);
            if (File.Exists(ixiPath))
            {
                Ini.FilePath = iniPath;
            }
            else
            {
                Ini.ReadAll();
                Ini.SaveCache(ixiPath, iniPath);
            }

            var appPath = PathEx.Combine(Ini.Read("Root", "AppPath"));

            if (string.IsNullOrEmpty(appPath) || !File.Exists(appPath))
            {
                return;
            }

            var  instanceKey = Path.GetFileName(appPath).ToLower().GetHashCode().ToString();
            bool newInstance;

            using (new Mutex(true, instanceKey, out newInstance))
            {
#if x86
                var architecture = Ini.Read("Root", "Architecture").EqualsEx("x64");
                if (!Environment.Is64BitOperatingSystem && architecture)
                {
                    return;
                }
                architecture = Ini.Read("Root", "Architecture").EqualsEx("Current", "Now", "x64");
                if (Environment.Is64BitOperatingSystem && architecture)
                {
                    var name = string.Concat(Path.GetFileNameWithoutExtension(PathEx.LocalPath), "64.exe");
                    var path = PathEx.Combine(PathEx.LocalDir, name);
                    ProcessEx.Start(path);
                    Environment.ExitCode = 0;
                    Environment.Exit(Environment.ExitCode);
                }
#endif

                if (!Elevation.IsAdministrator && Ini.Read("Root", "Elevated", false))
                {
                    Elevation.RestartAsAdministrator();
                }

                var cmdLine = EnvironmentEx.CommandLine(Ini.Read("Root", "SortCmdLine", false)).Trim();
                cmdLine = string.Format(Ini.Read <string>("Root", "CmdLine", "{0}"), cmdLine).Trim();

                if (!newInstance)
                {
                    var pName   = Process.GetCurrentProcess().ProcessName;
                    var pHandle = Process.GetCurrentProcess().Handle;
                    var pCount  = Process.GetProcessesByName(pName).Where(p => p.Handle != pHandle).ToArray().Length;
                    if (pCount > 0)
                    {
                        if (Ini.Read("Root", "MultiInstances", false))
                        {
                            ProcessEx.Start(appPath, cmdLine, Elevation.IsAdministrator);
                        }
                        return;
                    }
                }
                var iniOwCount = Ini.Read("IniOverwrite", "Count", 0);
                if (iniOwCount > 0)
                {
                    var iniMap = new Dictionary <string, Dictionary <string, Dictionary <string, string> > >();
                    for (var i = 0; i < iniOwCount; i++)
                    {
                        var file = PathEx.Combine(Ini.Read("IniOverwrite", $"File_{i}"));
                        if (string.IsNullOrWhiteSpace(file))
                        {
                            continue;
                        }
                        var count = Ini.Read("IniOverwrite", $"Count_{i}", 0);
                        if (count <= 0)
                        {
                            continue;
                        }
                        for (var j = 0; j < count; j++)
                        {
                            var section = Ini.Read("IniOverwrite", $"Section_{i}_{j}");
                            if (string.IsNullOrWhiteSpace(section))
                            {
                                continue;
                            }
                            var key = Ini.Read("IniOverwrite", $"Key_{i}_{j}");
                            if (string.IsNullOrWhiteSpace(key))
                            {
                                continue;
                            }
                            var value = Ini.Read("IniOverwrite", $"Value_{i}_{j}");
                            if (string.IsNullOrWhiteSpace(value))
                            {
                                continue;
                            }
                            var isPath = Ini.Read("IniOverwrite", $"IsPath_{i}_{j}", false);
                            if (isPath)
                            {
                                value = PathEx.Combine(value);
                            }
                            if (!iniMap.ContainsKey(file))
                            {
                                iniMap[file] = new Dictionary <string, Dictionary <string, string> >();
                            }
                            if (!iniMap.ContainsKey(section))
                            {
                                iniMap[file][section] = new Dictionary <string, string>();
                            }
                            iniMap[file][section][key] = value;
                        }
                    }
                    foreach (var file in iniMap.Keys)
                    {
                        Helper.ConfigOverwrite(iniMap[file], file);
                    }
                }

                var dirMap   = new Dictionary <string, string>();
                var dirCount = Ini.Read("DirRouting", "Count", 0);
                if (dirCount > 0)
                {
                    for (var i = 0; i < dirCount; i++)
                    {
                        var srcPath = PathEx.Combine(Ini.Read("DirRouting", $"Source_{i}"));
                        if (string.IsNullOrWhiteSpace(srcPath))
                        {
                            continue;
                        }
                        var destPath = PathEx.Combine(Ini.Read("DirRouting", $"Destination_{i}"));
                        if (string.IsNullOrWhiteSpace(destPath))
                        {
                            continue;
                        }
                        dirMap.Add(srcPath, destPath);
                    }
                    Helper.DirectoryForwarding(Helper.Options.Start, dirMap);
                }

                var fileMap   = new Dictionary <string, string>();
                var fileCount = Ini.Read("FileRouting", "Count", 0);
                if (fileCount > 0)
                {
                    for (var i = 0; i < fileCount; i++)
                    {
                        var srcPath = PathEx.Combine(Ini.Read("FileRouting", $"Source_{i}"));
                        if (string.IsNullOrWhiteSpace(srcPath))
                        {
                            continue;
                        }
                        var destPath = PathEx.Combine(Ini.Read("FileRouting", $"Destination_{i}"));
                        if (string.IsNullOrWhiteSpace(destPath))
                        {
                            continue;
                        }
                        fileMap.Add(srcPath, destPath);
                    }
                    Helper.FileForwarding(Helper.Options.Start, fileMap);
                }

                var regKeys  = new List <string>();
                var regCount = Ini.Read("RegRouting", "Count", 0);
                if (regCount > 0)
                {
                    for (var i = 0; i < regCount; i++)
                    {
                        regKeys.Add(Ini.Read("RegRouting", $"Key_{i}"));
                    }
                    regKeys = regKeys.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
                }
                Helper.RegForwarding(Helper.Options.Start, regKeys.ToArray());

                var regOwCount = Ini.Read("RegOverwrite", "Count", 0);
                if (regKeys.Count > 0 && regOwCount > 0)
                {
                    for (var i = 0; i < regOwCount; i++)
                    {
                        var key = Ini.Read("RegOverwrite", $"Key_{i}");
                        if (string.IsNullOrWhiteSpace(key))
                        {
                            continue;
                        }
                        var count = Ini.Read("RegOverwrite", $"Count_{i}", 0);
                        if (count <= 0)
                        {
                            continue;
                        }
                        for (var j = 0; j < count; j++)
                        {
                            var entry = Ini.Read("RegOverwrite", $"Entry_{i}_{j}");
                            if (string.IsNullOrWhiteSpace(entry))
                            {
                                continue;
                            }
                            var value = Ini.Read("RegOverwrite", $"Value_{i}_{j}");
                            if (string.IsNullOrWhiteSpace(value))
                            {
                                continue;
                            }
                            RegistryValueKind kind;
                            switch (Ini.Read("RegOverwrite", $"Kind_{i}_{j}")?.ToUpper())
                            {
                            case "BINARY":
                                kind = RegistryValueKind.Binary;
                                break;

                            case "DWORD":
                                kind = RegistryValueKind.DWord;
                                break;

                            case "EXPANDSTRING":
                                kind = RegistryValueKind.ExpandString;
                                break;

                            case "MULTISTRING":
                                kind = RegistryValueKind.MultiString;
                                break;

                            case "QWORD":
                                kind = RegistryValueKind.QWord;
                                break;

                            case "STRING":
                                kind = RegistryValueKind.String;
                                break;

                            case "UNKNOWN":
                                kind = RegistryValueKind.Unknown;
                                break;

                            default:
                                kind = RegistryValueKind.None;
                                break;
                            }
                            if (kind == RegistryValueKind.String)
                            {
                                var path = PathEx.Combine(value);
                                if (PathEx.DirOrFileExists(path))
                                {
                                    value = path;
                                }
                            }
                            Reg.Write(key, entry, value, kind);
                        }
                    }
                }

                Helper.ApplicationStart(appPath, cmdLine);

                var clearOnlyDirs = Ini.Read("ClearOnly", "Dirs");
                if (!string.IsNullOrWhiteSpace(clearOnlyDirs))
                {
                    if (!clearOnlyDirs.EndsWith("|"))
                    {
                        clearOnlyDirs += "|";
                    }
                    var dirs = clearOnlyDirs.Split('|').Select(s => PathEx.Combine(s));
                    foreach (var dir in dirs)
                    {
                        try
                        {
                            if (string.IsNullOrWhiteSpace(dir) || !Directory.Exists(dir))
                            {
                                continue;
                            }
                            Directory.Delete(dir, true);
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                    }
                }

                var clearOnlyFiles = Ini.Read("ClearOnly", "Files");
                if (!string.IsNullOrWhiteSpace(clearOnlyFiles))
                {
                    if (!clearOnlyFiles.EndsWith("|"))
                    {
                        clearOnlyFiles += "|";
                    }
                    var files = clearOnlyFiles.Split('|').Select(s => PathEx.Combine(s));
                    foreach (var file in files)
                    {
                        try
                        {
                            if (string.IsNullOrWhiteSpace(file) || !File.Exists(file))
                            {
                                continue;
                            }
                            File.Delete(file);
                        }
                        catch (Exception ex)
                        {
                            Log.Write(ex);
                        }
                    }
                }

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
                Helper.FileForwarding(Helper.Options.Exit, fileMap);
                Helper.RegForwarding(Helper.Options.Exit, regKeys.ToArray());
            }
        }