Exemplo n.º 1
0
 private static void SaveTextFile(Control control, IWin32Window owner = null)
 {
     if (!(control is Control c))
     {
         return;
     }
     if (string.IsNullOrEmpty(c.Text))
     {
         MessageBoxEx.Show(owner, UIStrings.TextCanNotBeEmpty, MessageBoxButtons.OK, MessageBoxIcon.Warning);
         return;
     }
     using (var dialog = new SaveFileDialog())
     {
         dialog.Filter   = $@"{UIStrings.TextFiles}|*.txt";
         dialog.FileName = $"{Path.GetFileNameWithoutExtension(PathEx.LocalPath)} {DateTime.Now:yyyy-MM-dd HH.mm.ss}.txt";
         if (dialog.ShowDialog() == DialogResult.OK)
         {
             try
             {
                 File.WriteAllText(dialog.FileName, TextEx.FormatNewLine(c.Text));
                 MessageBoxEx.Show(owner, UIStrings.FileSuccessfullySaved, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             }
             catch (Exception ex) when(ex.IsCaught())
             {
                 MessageBoxEx.Show(owner, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             return;
         }
         MessageBoxEx.Show(owner, UIStrings.OperationCanceled, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
     }
 }
Exemplo n.º 2
0
 private static void WriteInnerLine(string message = default, string caption = default, ConsoleColor captionFgColor = DefaultFgColor, ConsoleColor captionBgColor = DefaultBgColor)
 {
     if (string.IsNullOrWhiteSpace(message))
     {
         Console.WriteLine();
         return;
     }
     if (!_active)
     {
         _active = true;
     }
     message = message.Trim();
     if (!string.IsNullOrWhiteSpace(caption))
     {
         caption = " " + caption.Trim();
         if (!caption.EndsWith(":"))
         {
             caption = $"{caption}:";
         }
         SetColors(captionFgColor, captionBgColor);
         Console.Write(caption);
         SetColors();
         for (var i = caption.Length; i < 10; i++)
         {
             Console.Write(@" ");
         }
         if (message.ContainsEx("\r", "\n"))
         {
             var lines = TextEx.FormatNewLine(message).SplitNewLine();
             for (var i = 1; i < lines.Length; i++)
             {
                 lines[i] = lines[i].PadLeft(lines[i].Length + 11);
             }
             message = lines.Join(Environment.NewLine);
         }
     }
     Console.WriteLine(@" " + message);
 }
Exemplo n.º 3
0
        private bool SetChangeLogText(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(false);
            }
            changeLog.Font = new Font("Consolas", 8.25f);
            changeLog.Text = TextEx.FormatNewLine(text);
            var colorMap = new Dictionary <Color, string[]>
            {
                {
                    Color.PaleGreen, new[]
                    {
                        " PORTABLE APPS SUITE",
                        " UPDATED:",
                        " CHANGES:"
                    }
                },
                {
                    Color.SkyBlue, new[]
                    {
                        " Global:",
                        " Apps Launcher:",
                        " Apps Downloader:",
                        " Apps Suite Updater:"
                    }
                },
                {
                    Color.Khaki, new[]
                    {
                        "Version History:"
                    }
                },
                {
                    Color.Plum, new[]
                    {
                        "{", "}",
                        "(", ")",
                        "|",
                        ".",
                        "-"
                    }
                },
                {
                    Color.Tomato, new[]
                    {
                        " * "
                    }
                },
                {
                    Color.Black, new[]
                    {
                        new string('_', 84)
                    }
                }
            };

            foreach (var line in changeLog.Text.Split('\n'))
            {
                if (line.Length < 1 || !DateTime.TryParseExact(line.Trim(' ', ':'), "d MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var _))
                {
                    continue;
                }
                changeLog.MarkText(line, Color.Khaki);
            }
            foreach (var color in colorMap)
            {
                foreach (var s in color.Value)
                {
                    changeLog.MarkText(s, color.Key);
                }
            }
            return(true);
        }
Exemplo n.º 4
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            Version localVersion;

            try
            {
                var version = FileVersionInfo.GetVersionInfo(_appPath).FileVersion;
                if (version.Contains(','))
                {
                    version = version.Split(',').Select(c => c.Trim()).Join('.');
                }
                localVersion = Version.Parse(version);
            }
            catch
            {
                localVersion = new Version("0.0.0.0");
            }
            Version onlineVersion;

            try
            {
                var source = NetEx.Transfer.DownloadString(Resources.VersionUrl);
                if (string.IsNullOrEmpty(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.VersionHeader)).Take(1).Join();
                var inner = Regex.Match(source, Resources.VersionRegex).Groups[1].ToString();
                if (string.IsNullOrEmpty(inner))
                {
                    throw new ArgumentNullException(nameof(inner));
                }
                var index = inner.IndexOf('(');
                if (index < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(index));
                }
                var ver = inner.Substring(0, index).Trim(' ', 'v').Split('.');
                if (!Version.TryParse($"{ver.Take(2).Join('.')}.0.{ver.Last()}", out onlineVersion))
                {
                    throw new ArgumentNullException(nameof(onlineVersion));
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            if (localVersion < onlineVersion)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _transfer.DownloadFile(Resources.UpdateUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 5
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var regexUrl = Resources.RegexUrl;
                if (!Ini.ReadDirect("Settings", "BetaUpdates").EqualsEx("1", "True"))
                {
                    regexUrl += "/latest";
                }
                var source = NetEx.Transfer.DownloadString(regexUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source);
#if x86
                const string arch = "32";
#else
                const string arch = "64";
#endif
                source = source.SplitNewLine().Where(x => x.ContainsEx(Resources.SearchPrefix) && x.ContainsEx(string.Format(Resources.SearchSuffix, arch))).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexPattern, RegexOptions.Singleline))
                {
                    var mPath = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mPath) || mPath.Count(c => c == '/') != 1)
                    {
                        continue;
                    }
                    updUrl = string.Format(Resources.UpdateUrl, mPath);
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "7z.zip");
                        ResourcesEx.Extract(Resources._7z, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 6
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            FormEx.Dockable(this);

            Lang.SetControlLang(this);

            // Check internet connection
            if (!(_ipv4 = NetEx.InternetIsAvailable()) && !(_ipv6 = NetEx.InternetIsAvailable(true)))
            {
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            // Get update infos from GitHub if enabled
            if (Ini.Read("Settings", "UpdateChannel", 0) > 0)
            {
                if (!_ipv4 && _ipv6)
                {
                    Environment.ExitCode = 1;
                    Application.Exit();
                    return;
                }
                try
                {
                    var path = PathEx.AltCombine(Resources.GitRawProfileUri, Resources.GitSnapshotsPath, "Last.ini");
                    if (!NetEx.FileIsAvailable(path, 60000))
                    {
                        throw new PathNotFoundException(path);
                    }
                    var data = NetEx.Transfer.DownloadString(path);
                    if (string.IsNullOrWhiteSpace(data))
                    {
                        throw new ArgumentNullException(nameof(data));
                    }
                    _lastStamp = Ini.ReadOnly("Info", "LastStamp", data);
                    if (string.IsNullOrWhiteSpace(_lastStamp))
                    {
                        throw new ArgumentNullException(_lastStamp);
                    }
                    path = PathEx.AltCombine(Resources.GitRawProfileUri, Resources.GitSnapshotsPath, $"{_lastStamp}.ini");
                    if (!NetEx.FileIsAvailable(path, 60000))
                    {
                        throw new PathNotFoundException(path);
                    }
                    data = NetEx.Transfer.DownloadString(path);
                    if (string.IsNullOrWhiteSpace(data))
                    {
                        throw new ArgumentNullException(nameof(data));
                    }
                    _hashInfo = data;
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
            }

            // Get update infos if not already set
            if (string.IsNullOrWhiteSpace(_hashInfo))
            {
                // Get available download mirrors
                var dnsInfo = string.Empty;
                for (var i = 0; i < 3; i++)
                {
                    if (!_ipv4 && _ipv6)
                    {
                        dnsInfo = Resources.IPv6DNS;
                        break;
                    }
                    try
                    {
                        var path = PathEx.AltCombine(Resources.GitRawProfileUri, Resources.GitDnsPath);
                        if (!NetEx.FileIsAvailable(path, 60000))
                        {
                            throw new PathNotFoundException(path);
                        }
                        var data = NetEx.Transfer.DownloadString(path);
                        if (string.IsNullOrWhiteSpace(data))
                        {
                            throw new ArgumentNullException(nameof(data));
                        }
                        dnsInfo = data;
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    if (string.IsNullOrWhiteSpace(dnsInfo) && i < 2)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    break;
                }
                if (!string.IsNullOrWhiteSpace(dnsInfo))
                {
                    foreach (var section in Ini.GetSections(dnsInfo))
                    {
                        var addr = Ini.Read(section, _ipv4 ? "addr" : "ipv6", dnsInfo);
                        if (string.IsNullOrEmpty(addr))
                        {
                            continue;
                        }
                        var domain = Ini.Read(section, "domain", dnsInfo);
                        if (string.IsNullOrEmpty(domain))
                        {
                            continue;
                        }
                        var ssl = Ini.ReadOnly(section, "ssl", false, dnsInfo);
                        domain = PathEx.AltCombine(ssl ? "https:" : "http:", domain);
                        if (!DownloadMirrors.ContainsEx(domain))
                        {
                            DownloadMirrors.Add(domain);
                        }
                    }
                }
                if (DownloadMirrors.Count == 0)
                {
                    Environment.ExitCode = 1;
                    Application.Exit();
                    return;
                }

                // Get file hashes
                foreach (var mirror in DownloadMirrors)
                {
                    try
                    {
                        var path = PathEx.AltCombine(mirror, Resources.ReleasePath, "Last.ini");
                        if (!NetEx.FileIsAvailable(path, 60000))
                        {
                            throw new PathNotFoundException(path);
                        }
                        var data = NetEx.Transfer.DownloadString(path);
                        if (string.IsNullOrWhiteSpace(data))
                        {
                            throw new ArgumentNullException(nameof(data));
                        }
                        _lastFinalStamp = Ini.ReadOnly("Info", "LastStamp", data);
                        if (string.IsNullOrWhiteSpace(_lastFinalStamp))
                        {
                            throw new ArgumentNullException(nameof(_lastFinalStamp));
                        }
                        path = PathEx.AltCombine(mirror, Resources.ReleasePath, $"{_lastFinalStamp}.ini");
                        if (!NetEx.FileIsAvailable(path, 60000))
                        {
                            throw new PathNotFoundException(path);
                        }
                        data = NetEx.Transfer.DownloadString(path);
                        if (string.IsNullOrWhiteSpace(data))
                        {
                            throw new ArgumentNullException(nameof(data));
                        }
                        _hashInfo = data;
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    if (!string.IsNullOrWhiteSpace(_hashInfo))
                    {
                        break;
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(_hashInfo))
            {
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            // Compare hashes
            var updateAvailable = false;

            try
            {
                foreach (var key in Ini.GetKeys("SHA256", _hashInfo))
                {
                    var file = Path.Combine(HomeDir, $"{key}.exe");
                    if (!File.Exists(file))
                    {
                        file = PathEx.Combine(PathEx.LocalDir, $"{key}.exe");
                    }
                    if (Ini.Read("SHA256", key, _hashInfo).EqualsEx(Crypto.EncryptFileToSha256(file)))
                    {
                        continue;
                    }
                    updateAvailable = true;
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                Environment.ExitCode = 1;
                Application.Exit();
                return;
            }

            // Install updates
            if (updateAvailable)
            {
                if (MessageBox.Show(Lang.GetText(nameof(en_US.UpdateAvailableMsg)), Text, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    // Update changelog
                    if (DownloadMirrors.Count > 0)
                    {
                        var changes = string.Empty;
                        foreach (var mirror in DownloadMirrors)
                        {
                            var path = PathEx.AltCombine(mirror, Resources.ReleasePath, "ChangeLog.txt");
                            if (string.IsNullOrWhiteSpace(path))
                            {
                                continue;
                            }
                            if (!NetEx.FileIsAvailable(path, 60000))
                            {
                                continue;
                            }
                            changes = NetEx.Transfer.DownloadString(path);
                            if (!string.IsNullOrWhiteSpace(changes))
                            {
                                break;
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(changes))
                        {
                            changeLog.Font = new Font("Consolas", 8.25f);
                            changeLog.Text = TextEx.FormatNewLine(changes);
                            var colorMap = new Dictionary <Color, string[]>
                            {
                                {
                                    Color.PaleGreen, new[]
                                    {
                                        " PORTABLE APPS SUITE",
                                        " UPDATED:",
                                        " CHANGES:"
                                    }
                                },
                                {
                                    Color.SkyBlue, new[]
                                    {
                                        " Global:",
                                        " Apps Launcher:",
                                        " Apps Downloader:",
                                        " Apps Suite Updater:"
                                    }
                                },
                                {
                                    Color.Khaki, new[]
                                    {
                                        "Version History:"
                                    }
                                },
                                {
                                    Color.Plum, new[]
                                    {
                                        "{", "}",
                                        "(", ")",
                                        "|",
                                        ".",
                                        "-"
                                    }
                                },
                                {
                                    Color.Tomato, new[]
                                    {
                                        " * "
                                    }
                                },
                                {
                                    Color.Black, new[]
                                    {
                                        new string('_', 84)
                                    }
                                }
                            };
                            foreach (var line in changeLog.Text.Split('\n'))
                            {
                                if (line.Length < 1 || !DateTime.TryParseExact(line.Trim(' ', ':'), "d MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _))
                                {
                                    continue;
                                }
                                changeLog.MarkText(line, Color.Khaki);
                            }
                            foreach (var color in colorMap)
                            {
                                foreach (var s in color.Value)
                                {
                                    changeLog.MarkText(s, color.Key);
                                }
                            }
                        }
                    }
                    else
                    {
                        changeLog.Dock     = DockStyle.None;
                        changeLog.Size     = new Size(changeLogPanel.Width, TextRenderer.MeasureText(changeLog.Text, changeLog.Font).Height);
                        changeLog.Location = new Point(0, changeLogPanel.Height / 2 - changeLog.Height - 16);
                        changeLog.SelectAll();
                        changeLog.SelectionAlignment = HorizontalAlignment.Center;
                        changeLog.DeselectAll();
                    }
                    ShowInTaskbar = true;
                    return;
                }
            }

            // Exit the application if no updates were found
            Environment.ExitCode = 2;
            Application.Exit();
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Sets registry values from an INI config or from a REG file.
        /// </summary>
        /// <param name="fileOrContent">
        ///     The path or content of an INI or REG file.
        /// </param>
        public static void SetConfig(string fileOrContent)
        {
            if (string.IsNullOrWhiteSpace(fileOrContent))
            {
                return;
            }
            var sections = Ini.GetSections(fileOrContent, false);

            try
            {
                if (sections.All(x => x.StartsWith("HKEY_")) && sections.All(x => Ini.GetKeys(x, fileOrContent, false).All(y => y.Equals("@") || y.StartsWith("\"") && y.EndsWith("\""))))
                {
                    try
                    {
                        var regex   = new Regex("%(.+?)%");
                        var content = File.Exists(fileOrContent) ? File.ReadAllText(fileOrContent) : fileOrContent;
                        foreach (var variable in regex.Matches(content).Cast <Match>().Select(x => x.Value).Distinct())
                        {
                            var value = EnvironmentEx.GetVariableValue(variable);
                            if (!content.ContainsEx(variable))
                            {
                                continue;
                            }
                            content = content.Replace(variable, value);
                        }
                        var cArray = TextEx.FormatNewLine(content).SplitNewLine();
                        Reg.ImportFile(cArray);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }

            foreach (var section in Ini.GetSections(fileOrContent, false))
            {
                var key = Ini.Read(section, "Key", default(string), fileOrContent);
                if (string.IsNullOrEmpty(key))
                {
                    continue;
                }

                var entry = Ini.Read(section, "Entry", default(string), fileOrContent);
                var value = Ini.Read(section, "Value", default(string), fileOrContent);
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(entry))
                {
                    entry = PathEx.Combine(entry);
                }
                value = PathEx.Combine(value);

                var kind = Ini.Read(section, "Kind", default(string), fileOrContent);
                if (string.IsNullOrEmpty(kind))
                {
                    continue;
                }

                try
                {
                    Reg.Write(key, !string.IsNullOrWhiteSpace(entry) ? entry : null, value, (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), kind));
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                    continue;
                }

                var temp = Ini.Read(section, "Temp", default(string), fileOrContent);
                if (!temp.EqualsEx("True", "Entry"))
                {
                    continue;
                }

                AppDomain.CurrentDomain.ProcessExit += (s, e) =>
                {
                    switch (temp.ToLower())
                    {
                    case "true":
                        Reg.RemoveSubKey(key);
                        break;

                    case "entry":
                        Reg.RemoveEntry(key, entry);
                        break;
                    }
                };
            }
        }
Exemplo n.º 8
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            var    source = NetEx.Transfer.DownloadString(Resources.UpdateUrl);
            string updUrl;

            try
            {
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.AppName) && !x.ContainsEx(".zip")).FirstOrDefault();
                source = source.Split("\"").SkipWhile(x => !x.ContainsEx(Resources.AppName) && !x.ContainsEx(".zip")).FirstOrDefault();
                if (string.IsNullOrEmpty(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                updUrl = source;
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 9
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                var source = NetEx.Transfer.DownloadString(Resources.RegexFirstUrl);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexSecBtnMatch)).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexSecUrlPattern, RegexOptions.Singleline))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    source = NetEx.Transfer.DownloadString(mUrl);
                    if (string.IsNullOrWhiteSpace(source))
                    {
                        throw new ArgumentNullException(nameof(source));
                    }
                    source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(Resources.RegexThirdBtnMatch) || !Resources.RegexThirdExtMatch.SplitNewLine().Any(y => x.ContainsEx(y))).Take(1).Join();
                    foreach (Match match2 in Regex.Matches(source, Resources.RegexThirdUrlPattern, RegexOptions.Singleline))
                    {
                        mUrl = match2.Groups[1].ToString();
                        if (string.IsNullOrWhiteSpace(mUrl))
                        {
                            continue;
                        }
                        if (mUrl.ContainsEx("/show/"))
                        {
                            mUrl = mUrl.Replace("/show/", "/get/");
                        }
                        updUrl = mUrl;
                        break;
                    }
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppName));
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 10
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            var    source = NetEx.Transfer.DownloadString(Resources.RegexUrl);
            string updUrl = null;

            try
            {
                var pattern = string.Format(Resources.RegexUrlPattern,
#if x86
                                            "32"
#else
                                            "64"
#endif
                                            );
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx("p95") && !x.ContainsEx(".zip")).Take(1).Join();
                foreach (Match match in Regex.Matches(source, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    updUrl = string.Format(Resources.UpdateUrl, mUrl,
#if x86
                                           "32"
#else
                                           "64"
#endif
                                           );
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);
            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }
Exemplo n.º 11
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = Resources.WindowTitle;
            TaskBar.Progress.SetState(Handle, TaskBar.Progress.Flags.Indeterminate);
            if (!NetEx.InternetIsAvailable())
            {
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Err_00, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Application.Exit();
                return;
            }
            string updUrl = null;

            try
            {
                _tmpDir = PathEx.Combine(Path.GetTempPath(), PathEx.GetTempDirName(Resources.AppDisplayName));
                var hlpPath = Path.Combine(_tmpDir, "js.zip");
                ResourcesEx.Extract(Resources.js, hlpPath, true);
                Compaction.Unzip(hlpPath, _tmpDir);
                Thread.Sleep(200);
                var helperPath = Path.Combine(_tmpDir, "read.js");
                var source     = Path.Combine(_tmpDir, "source.txt");
                File.WriteAllText(helperPath, Resources.JsScript);
                using (var p = ProcessEx.Send(string.Format(Resources.RunScript, _tmpDir), Elevation.IsAdministrator, ProcessWindowStyle.Hidden, false))
                    if (p?.HasExited == false)
                    {
                        p.WaitForExit();
                    }
                source = File.ReadAllText(source);
                if (string.IsNullOrWhiteSpace(source))
                {
                    throw new ArgumentNullException(nameof(source));
                }
                source = TextEx.FormatNewLine(source).SplitNewLine().SkipWhile(x => !x.ContainsEx(".exe")).Take(1).Join();
                foreach (Match match in Regex.Matches(source, Resources.RegexUrlPattern, RegexOptions.Singleline))
                {
                    var mUrl = match.Groups[1].ToString();
                    if (string.IsNullOrWhiteSpace(mUrl))
                    {
                        continue;
                    }
                    updUrl = mUrl.Trim('"');
                    break;
                }
                if (!NetEx.FileIsAvailable(updUrl, 60000, Resources.UserAgent))
                {
                    throw new PathNotFoundException(updUrl);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                if (!_silent || !File.Exists(_appPath))
                {
                    MessageBoxEx.Show(Resources.Msg_Warn_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Application.Exit();
                return;
            }
            var localDate  = File.GetLastWriteTime(_appPath);
            var onlineDate = NetEx.GetFileDate(updUrl, Resources.UserAgent);

            if ((onlineDate - localDate).Days > 0)
            {
                if (_silent || MessageBoxEx.Show(Resources.Msg_Hint_00, Resources.WindowTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    var archivePath = PathEx.Combine(PathEx.LocalDir, $"..\\{PathEx.GetTempFileName()}");
                    if (!File.Exists(archivePath))
                    {
                        var hlpPath = Path.Combine(_tmpDir, "iu.zip");
                        ResourcesEx.Extract(Resources.iu, hlpPath, true);
                        Compaction.Unzip(hlpPath, _tmpDir);
                        _transfer.DownloadFile(updUrl, archivePath);
                        Opacity = 1f;
                        CheckDownload.Enabled = true;
                        return;
                    }
                    ExtractDownload.RunWorkerAsync();
                }
                Application.Exit();
                return;
            }
            if (!_silent)
            {
                MessageBoxEx.Show(Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Application.Exit();
        }