Exemplo n.º 1
0
        private static void DoUpdateWithSingleThread(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
        {
            Thread worker = new Thread(() => DoUpdateWithSingleThreadWorker(updateDialog, downloadUrl, updateFile));

            worker.Name = "Updater.SingleThreadWorker";
            worker.Start();
        }
Exemplo n.º 2
0
        /// <summary>
        ///		Initializes the updater and sets up all the sub systems.
        /// </summary>
        /// <returns>True if initialization was sucessfull.</returns>
        private bool Initialize()
        {
            #region Command Line & Configuration Parsing

            // Parse the command lines for configuration options.
            ParseCommandLines(_commandLineArguments, true);

            // First things first lets read in the engine configuration file.
            _engineConfigFile = new XmlConfigFile(_configFilePath);

            // Get any configuration values relative to initializing the engine.
            _relativeBasePath = _engineConfigFile["basepath", _basePath];
            _basePath         = _relativeBasePath;

            // Parse the command lines for anything besides configuration options.
            ParseCommandLines(_commandLineArguments, false);

            // Check an update file has been specified.
            if (_updateFile == "")
            {
                MessageBox.Show("Unable to update, no update file was specified.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            #endregion
            #region Sub System Initialization

            // Create the updater's window.
            _window = new UpdaterWindow();
            _window.Show();

            #endregion
            return(true);
        }
Exemplo n.º 3
0
        public static void UpdateRyujinx(UpdaterWindow updateDialog, string downloadUrl)
        {
            // Empty update dir, although it shouldn't ever have anything inside it
            if (Directory.Exists(UpdateDir))
            {
                Directory.Delete(UpdateDir, true);
            }

            Directory.CreateDirectory(UpdateDir);

            string updateFile = Path.Combine(UpdateDir, "update.bin");

            // Download the update .zip
            updateDialog.MainText.Text       = LocaleManager.Instance["UpdaterDownloading"];
            updateDialog.ProgressBar.Value   = 0;
            updateDialog.ProgressBar.Maximum = 100;

            Task.Run(() =>
            {
                if (_buildSize >= 0)
                {
                    DoUpdateWithMultipleThreads(updateDialog, downloadUrl, updateFile);
                }
                else
                {
                    DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);
                }
            });
        }
Exemplo n.º 4
0
        private void CheckAndUpdate()
        {
            try {
                var     urlAddress = @"http://agentik.com/update/Agentik.exe";
                Version currentVersion = null, newVersion = null;
                string  execPath = Assembly.GetExecutingAssembly().Location;
                if (!String.IsNullOrEmpty(execPath))
                {
                    currentVersion = new Version(FileVersionInfo.GetVersionInfo(execPath).FileVersion);
                }

                String versionUrl = "http://agentik.com/update/Version.xml";
                var    xmlDoc     = new XmlDocument();
                xmlDoc.Load(versionUrl);
                var elements = xmlDoc.GetElementsByTagName("version");
                newVersion = new Version(elements[0].InnerText);

                if (newVersion > currentVersion)
                {
                    if (DXMessageBox.Show("Доступна новая версия. Скачать?", "AGENTIK", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        var localPath = Path.GetTempPath() + "Agentik.exe";
                        var updater   = new UpdaterWindow(urlAddress, localPath);
                        updater.ShowDialog();
                        Close();
                    }
                }
            }
            catch (Exception ex) {
                _log.Error(ex);
            }
        }
Exemplo n.º 5
0
        private void UpdateCheck_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new UpdaterWindow();

            dialog.Owner = this;
            dialog.ShowDialog();
        }
Exemplo n.º 6
0
        private void Setup()
        {
            SessionhasAdminRights = IsUserAdministrator();

            try {
                Task.Run(async() => {
                    var hasUpdate = await _updateManager.FetchUpdateAsync();

                    if (!hasUpdate)
                    {
                        return;
                    }

                    var thread = new Thread(() => {
                        var updaterWindow = new UpdaterWindow(_updateManager)
                        {
                            ShowActivated = true
                        };

                        updaterWindow.Show();

                        updaterWindow.StartUpdateProcess();

                        System.Windows.Threading.Dispatcher.Run();
                    });

                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                });
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                Directory.CreateDirectory(AppDataPath);
                Directory.CreateDirectory(ExportPath);
            }

            catch (Exception ex) {
                ex.Show();
            }

            Views = new ViewCollection(); // Make a ViewCollection object

            ToolsMenu.ItemsSource = ViewCollection.GetAllToolTypes().Where(o => o.GetCustomAttribute <HiddenToolAttribute>() == null).Select(o => {
                var name = ViewCollection.GetName(o);
                var item = new MenuItem {
                    Header = "_" + name, ToolTip = $"Open {name}."
                };
                item.Click += ViewSelectMenuItemOnClick;
                return(item);
            }).OrderBy(o => o.Header);
        }
Exemplo n.º 7
0
        public static int Run(Arguments args)
        {
            Log.InfoFormat("Starting update of v{0} to {1}",
                           Constants.ApplicationVersion,
                           args.InstallationPath);

            var app = new UpdateApplication();
            var dispatcher = new UiDispatcher(System.Windows.Threading.Dispatcher.CurrentDispatcher);
            var window = new UpdaterWindow(new UpdateWindowViewModel(dispatcher, args.InstallationPath));
            window.Show();
            return app.Run();
        }
Exemplo n.º 8
0
        private static void DoUpdateWithSingleThreadWorker(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
        {
            using (HttpClient client = new HttpClient())
            {
                // We do not want to timeout while downloading
                client.Timeout = TimeSpan.FromDays(1);

                using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result)
                    using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result)
                    {
                        using (Stream updateFileStream = File.Open(updateFile, FileMode.Create))
                        {
                            long totalBytes  = response.Content.Headers.ContentLength.Value;
                            long byteWritten = 0;

                            byte[] buffer = new byte[32 * 1024];

                            while (true)
                            {
                                int readSize = remoteFileStream.Read(buffer);

                                if (readSize == 0)
                                {
                                    break;
                                }

                                byteWritten += readSize;

                                updateDialog.ProgressBar.Value = ((double)byteWritten / totalBytes) * 100;
                                updateFileStream.Write(buffer, 0, readSize);
                            }
                        }
                    }

                InstallUpdate(updateDialog, updateFile);
            }
        }
Exemplo n.º 9
0
        private static void MoveAllFilesOver(string root, string dest, UpdaterWindow dialog)
        {
            foreach (string directory in Directory.GetDirectories(root))
            {
                string dirName = Path.GetFileName(directory);

                if (!Directory.Exists(Path.Combine(dest, dirName)))
                {
                    Directory.CreateDirectory(Path.Combine(dest, dirName));
                }

                MoveAllFilesOver(directory, Path.Combine(dest, dirName), dialog);
            }

            foreach (string file in Directory.GetFiles(root))
            {
                File.Move(file, Path.Combine(dest, Path.GetFileName(file)), true);

                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    dialog.ProgressBar.Value++;
                });
            }
        }
Exemplo n.º 10
0
        private static async void InstallUpdate(UpdaterWindow updateDialog, string updateFile)
        {
            // Extract Update
            updateDialog.MainText.Text     = LocaleManager.Instance["UpdaterExtracting"];
            updateDialog.ProgressBar.Value = 0;

            if (OperatingSystem.IsLinux())
            {
                using (Stream inStream = File.OpenRead(updateFile))
                    using (Stream gzipStream = new GZipInputStream(inStream))
                        using (TarInputStream tarStream = new TarInputStream(gzipStream, Encoding.ASCII))
                        {
                            updateDialog.ProgressBar.Maximum = inStream.Length;

                            await Task.Run(() =>
                            {
                                TarEntry tarEntry;
                                while ((tarEntry = tarStream.GetNextEntry()) != null)
                                {
                                    if (tarEntry.IsDirectory)
                                    {
                                        continue;
                                    }

                                    string outPath = Path.Combine(UpdateDir, tarEntry.Name);

                                    Directory.CreateDirectory(Path.GetDirectoryName(outPath));

                                    using (FileStream outStream = File.OpenWrite(outPath))
                                    {
                                        tarStream.CopyEntryContents(outStream);
                                    }

                                    File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc));

                                    TarEntry entry = tarEntry;

                                    Dispatcher.UIThread.Post(() =>
                                    {
                                        updateDialog.ProgressBar.Value += entry.Size;
                                    });
                                }
                            });

                            updateDialog.ProgressBar.Value = inStream.Length;
                        }
            }
            else
            {
                using (Stream inStream = File.OpenRead(updateFile))
                    using (ZipFile zipFile = new ZipFile(inStream))
                    {
                        updateDialog.ProgressBar.Maximum = zipFile.Count;

                        await Task.Run(() =>
                        {
                            foreach (ZipEntry zipEntry in zipFile)
                            {
                                if (zipEntry.IsDirectory)
                                {
                                    continue;
                                }

                                string outPath = Path.Combine(UpdateDir, zipEntry.Name);

                                Directory.CreateDirectory(Path.GetDirectoryName(outPath));

                                using (Stream zipStream = zipFile.GetInputStream(zipEntry))
                                    using (FileStream outStream = File.OpenWrite(outPath))
                                    {
                                        zipStream.CopyTo(outStream);
                                    }

                                File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc));

                                Dispatcher.UIThread.Post(() =>
                                {
                                    updateDialog.ProgressBar.Value++;
                                });
                            }
                        });
                    }
            }

            // Delete downloaded zip
            File.Delete(updateFile);

            List <string> allFiles = EnumerateFilesToDelete().ToList();

            updateDialog.MainText.Text       = LocaleManager.Instance["UpdaterRenaming"];
            updateDialog.ProgressBar.Value   = 0;
            updateDialog.ProgressBar.Maximum = allFiles.Count;

            // Replace old files
            await Task.Run(() =>
            {
                foreach (string file in allFiles)
                {
                    try
                    {
                        File.Move(file, file + ".ryuold");

                        Dispatcher.UIThread.Post(() =>
                        {
                            updateDialog.ProgressBar.Value++;
                        });
                    }
                    catch
                    {
                        Logger.Warning?.Print(LogClass.Application, string.Format(LocaleManager.Instance["UpdaterRenameFailed"], file));
                    }
                }

                Dispatcher.UIThread.Post(() =>
                {
                    updateDialog.MainText.Text       = LocaleManager.Instance["UpdaterAddingFiles"];
                    updateDialog.ProgressBar.Value   = 0;
                    updateDialog.ProgressBar.Maximum = Directory.GetFiles(UpdatePublishDir, "*", SearchOption.AllDirectories).Length;
                });

                MoveAllFilesOver(UpdatePublishDir, HomeDir, updateDialog);
            });

            Directory.Delete(UpdateDir, true);

            SetUnixPermissions();

            updateDialog.MainText.Text      = LocaleManager.Instance["DialogUpdaterCompleteMessage"];
            updateDialog.SecondaryText.Text = LocaleManager.Instance["DialogUpdaterRestartMessage"];

            updateDialog.ProgressBar.IsVisible = false;
            updateDialog.ButtonBox.IsVisible   = true;
        }
Exemplo n.º 11
0
        private static void DoUpdateWithMultipleThreads(UpdaterWindow updateDialog, string downloadUrl, string updateFile)
        {
            // Multi-Threaded Updater
            long chunkSize      = _buildSize / ConnectionCount;
            long remainderChunk = _buildSize % ConnectionCount;

            int completedRequests       = 0;
            int totalProgressPercentage = 0;

            int[] progressPercentage = new int[ConnectionCount];

            List <byte[]>    list       = new List <byte[]>(ConnectionCount);
            List <WebClient> webClients = new List <WebClient>(ConnectionCount);

            for (int i = 0; i < ConnectionCount; i++)
            {
                list.Add(Array.Empty <byte>());
            }

            for (int i = 0; i < ConnectionCount; i++)
            {
#pragma warning disable SYSLIB0014
                // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient.
                using (WebClient client = new WebClient())
#pragma warning restore SYSLIB0014
                {
                    webClients.Add(client);

                    if (i == ConnectionCount - 1)
                    {
                        client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}");
                    }
                    else
                    {
                        client.Headers.Add("Range", $"bytes={chunkSize * i}-{chunkSize * (i + 1) - 1}");
                    }

                    client.DownloadProgressChanged += (_, args) =>
                    {
                        int index = (int)args.UserState;

                        Interlocked.Add(ref totalProgressPercentage, -1 * progressPercentage[index]);
                        Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage);
                        Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage);

                        updateDialog.ProgressBar.Value = totalProgressPercentage / ConnectionCount;
                    };

                    client.DownloadDataCompleted += (_, args) =>
                    {
                        int index = (int)args.UserState;

                        if (args.Cancelled)
                        {
                            webClients[index].Dispose();

                            return;
                        }

                        list[index] = args.Result;
                        Interlocked.Increment(ref completedRequests);

                        if (Interlocked.Equals(completedRequests, ConnectionCount))
                        {
                            byte[] mergedFileBytes = new byte[_buildSize];
                            for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++)
                            {
                                Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length);
                                destinationOffset += list[connectionIndex].Length;
                            }

                            File.WriteAllBytes(updateFile, mergedFileBytes);

                            try
                            {
                                InstallUpdate(updateDialog, updateFile);
                            }
                            catch (Exception e)
                            {
                                Logger.Warning?.Print(LogClass.Application, e.Message);
                                Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");

                                DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);

                                return;
                            }
                        }
                    };

                    try
                    {
                        client.DownloadDataAsync(new Uri(downloadUrl), i);
                    }
                    catch (WebException ex)
                    {
                        Logger.Warning?.Print(LogClass.Application, ex.Message);
                        Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater.");

                        for (int j = 0; j < webClients.Count; j++)
                        {
                            webClients[j].CancelAsync();
                        }

                        DoUpdateWithSingleThread(updateDialog, downloadUrl, updateFile);

                        return;
                    }
                }
            }
        }
Exemplo n.º 12
0
 public IUpdaterUI CreateUpdateUIDialog()
 {
     return(UpdaterWindow.CreateFromGladeFile());
 }
Exemplo n.º 13
0
        private async Task Update(bool allowSkip = true, bool notifyUser = false)
        {
            try {
                var assetNamePattern = Environment.Is64BitProcess ? "release_x64.zip" : "release.zip";
                var updateManager    = new UpdateManager("OliBomby", "Mapping_Tools", assetNamePattern);
                var hasUpdate        = await updateManager.FetchUpdateAsync();

                if (!hasUpdate)
                {
                    if (notifyUser)
                    {
                        MessageQueue.Enqueue("No new versions available.");
                    }
                    return;
                }

                // Check if this version is newer than the version we skip
                var skipVersion = SettingsManager.Settings.SkipVersion;
                if (allowSkip && skipVersion != null && !(updateManager.UpdatesResult.LastVersion > skipVersion))
                {
                    if (notifyUser)
                    {
                        MessageQueue.Enqueue($"Version {updateManager.UpdatesResult.LastVersion} skipped because of user config.");
                    }
                    return;
                }

                Dispatcher.Invoke(() => {
                    _updaterWindow = new UpdaterWindow(updateManager.Progress)
                    {
                        ShowActivated = true
                    };

                    _updaterWindow.ActionSelected += async(sender, action) => {
                        switch (action)
                        {
                        case UpdateAction.Restart:
                            await updateManager.DownloadUpdateAsync();
                            updateManager.RestartAfterUpdate = true;
                            updateManager.StartUpdateProcess();

                            _updaterWindow.Close();
                            Close();
                            break;

                        case UpdateAction.Wait:
                            await updateManager.DownloadUpdateAsync();
                            updateManager.RestartAfterUpdate = false;
                            updateManager.StartUpdateProcess();

                            _updaterWindow.Close();
                            break;

                        case UpdateAction.Skip:
                            // Update the skip version so we skip this version in the future
                            SettingsManager.Settings.SkipVersion = updateManager.UpdatesResult.LastVersion;
                            _updaterWindow.Close();
                            break;

                        default:
                            _updaterWindow.Close();
                            break;
                        }
                    };

                    _updaterWindow.Closed += (sender, e) => {
                        updateManager.Dispose();
                    };

                    _updaterWindow.Show();
                });
            } catch (Exception e) {
                MessageBox.Show("UPDATER_EXCEPTION: " + e.Message);
                if (notifyUser)
                {
                    MessageQueue.Enqueue("Error fetching update: " + e.Message);
                }
            }
        }